mardi 4 août 2015

string handling in c and C++ mix programming

I want to use an API from a library. I am confused about its second argument.

    cs_disasm(handle,(const uint8_t*)("\xff\x43\x12\xd1"),4 , 0x0, 1, &insn);

The above code works fine. "\xff\x43\x12\xd1", this string represents a machine code. I want this API to accept arbitrary machine code. What I have now is an

uint32_t machine_code. I use it as follow, but not work.
std::stringstream ss;
ss<< std::hex  << setfill('0') << setw(2) <<  (int)(machine_code&0xff); // int decimal_value
std::string res1 ( ss.str() );
ss.str(std::string());
//cout << res1 << endl;

ss<< std::hex << setfill('0') << setw(2) << (int)((machine_code>>8)&0xff); // int decimal_value
std::string res2 ( ss.str() );
ss.str(std::string());


ss<< std::hex << setfill('0') << setw(2)  << (int)((machine_code>>16)&0xff); // int decimal_value
std::string res3 ( ss.str() );
ss.str(std::string());

ss<< std::hex << setfill('0') << setw(2) << (int)((machine_code>>24)&0xff); // int decimal_value
std::string res4 ( ss.str() );
string modified_machine_code = "\\x"+ res1 +"\\x"+  res2 +"\\x"+ res3 +"\\x"+ res4;
cs_disasm(hao_handle,(const uint8_t*)(modified_machine_code.c_str()),4 , 0x0, 1, &hao_insn);

What is the problem with my code? If you have a better solution, that is also great.

Generic function dispatch mechanism

I am trying to write a generic function dispatch mechanism where I do some additional work before calling the actual function (e.g. time the function's execution). The following code works, except for functions of the type void f(....) since we are declaring ret.

#define execute(fn, ...)    exec_helper(#fn, fn, ##__VA_ARGS__)
#define execute0(fn)        exec_helper(#fn, fn)

template <typename TASK, typename... ARGS>
auto exec_helper(const char *fn_name, TASK&& task, ARGS&&... args)
{
      //std::function<std::result_of_t<TASK(ARGS...)> ()> func
      //           = std::bind(std::forward<TASK>(task),
      //                       std::forward<ARGS>(args)...);

#ifdef TIME_FUNC
      auto start = std::chrono::steady_clock::now();
#endif

      auto ret = task(std::forward<ARGS>(args)...);

#ifdef TIME_FUNC
      auto end = std::chrono::steady_clock::now();
      auto diff = end - start;
      auto time = std::chrono::duration<double, std::milli>(diff).count();
      std::cout << "\n" << fn_name << "\t = "
                << std::setprecision(3) << time << " ms\n";
#endif

      return ret;
}

Is there a way to make it work for these type of functions as well? Perhaps using some template tricks?

Usage of members of a strongly typed enum in a member function's default arguments

I am using G++ mostly and nowadays Visual Studio 2015. I wanted to build my project with VC++2015 but I get error messages that saying invalid use of '::' in a function given default arguments with a forward declared strongly typed enum.

Here is some code:

struct Foo
{
    //! Forward declaration of Bar
    enum class Bar : short;

    //! "Faulty" function with default argument
    void DoSmth(Bar aBar = Bar::Baz)
    {
        // ... code ...
    }

    //! Complete declaration of Bar
    enum class Bar : short
    {
        Baz
    };
};

int main() { }

It gives me the following error at the declaration of the function DoSmth() with the default argument Bar::Baz:

test.cpp(7): error C2589: '::': illegal token on right side of '::'
test.cpp(7): error C2059: syntax error: '::'
test.cpp(17): fatal error C1903: unable to recover from previous error(s); stopping compilation

With G++ (tested with 4.9 and 5.1) the code compiles just fine but with VC++2015 it doesn't.

Im fully aware that I have to declare something before usage but. Is it just because that VC++2015 does not look within the scope of the class for the complete declaration and definition of Bar but G++ does? Or maybe does G++ just take the complete declaration and "merges" it with the forward declaration (as they are in the same scope) and thus makes it completely available to the class? Or maybe I am just plain wrong and something complete different causes this?

I can live with it that I have to change all my declarations for strongly typed enums in order to make it work with VC++2015.

But I also want to know why this is?

Detect only thicker horizontal lines in opencv

Is there any algorithm in opencv to detect only thicker horizontal lines which are thicker than a given threshold in opencv. The thickness of the detected lines should exceed that given value. Normally in houghLines function there is no parameter to give a threshold thickness. [anyway my purpose is to detect all the background lines (white spaces exceeding certain height and width) in a document article and get the average thickness of those detected lines. If more clarified my ultimate purpose is to calculate the average distance between text lines in a document]

Using iterators as offset index

Apologies if this was already asked. I couldn't find an answer to that. Is it legal to use an iterator as an offset index? For example:

for (list<T> iterator::it = v2->vals.begin(); it!=v2->vals.end();++i) {
    v3.push_back(v2[it] + v1[it]);
}

where : const Vec& v2 and vals is a list in Vec class's protected.

Many thanks!

Invalid handle exception

I have unit test that tests whether my functionality won't allow to use closed socket. So it looks somehow like this:

closesocket(sock);
int result;
result = getsockopt(sock,SOL_SOCKET,SO_TYPE, type, len);
if(result == SOCKET_ERROR)
    //write error etc.

On Windows platform call to getsockopt does not raise an exception "0xC0000008: An invalid handle was specified.". On Windows Phone ARM platform it raises an exception and while i can turn off the First-chance exception i cannot really turn off the uncaught exception.

Trying

try{
getsockopt();
}
catch(...)
{}

doesn't work. Is there a way I can silence this exception ?

Mutexes and deadlocks

After asking a question about mutexes here, I was warned about deadlocks.

Would the example I put together below be a reasonable way to avoid deadlocks?

class Foo
{
public:
    Foo();

    void Thread();

    int GetWidgetProperty();
    int GetGadgetProperty();

private:

    Widget widget_;
    Gadget gadget_;

    VDK::MutexID widgetLock;
    VDK::MutexID gadgetLock;
};


Foo::Foo()
    : widget_(42)
    , gadget_(widget_)
{
    widgetLock = VDK::CreateMutex();
    gadgetLock = VDK::CreateMutex();
}

void Foo::Thread()
{
    while(1)
    {
        VDK::AcquireMutex(widgetLock);
        // Use widget
        VDK::ReleaseMutex(widgetLock);

        VDK::AcquireMutex(widgetLock);
        VDK::AcquireMutex(gadgetLock);
        // use gadget
        VDK::ReleaseMutex(widgetLock);
        VDK::ReleaseMutex(gadgetLock);
    }
}

int Foo::GetWidgetProperty()
{
    VDK::AcquireMutex(widgetLock);
    return widget_.GetProp();
    VDK::ReleaseMutex(widgetLock);
}

int Foo::GetGadgetProperty()
{
    VDK::AcquireMutex(widgetLock);
    VDK::AcquireMutex(gadgetLock);
    return gadget.GetProp();
    VDK::ReleaseMutex(widgetLock);
    VDK::ReleaseMutex(gadgetLock);  
}

Since the call GetGadgetProperty could result in using the widget, I'm guessing we also need to protect our self with a lock here. My question is, am I requiring and releasing them in the right order?

Strange characters using std :: cin

I have been developing an application in C++ with Xcode 6.3.2 under OSX Yosemite and whenever I ask the operator to enter a parameter with the code below, it works fine, except if at some point the operator makes a mistake while typing and corrects his entry using the arrows on the keyboard. If he does so, this is the output he gets :

Please enter the name of the object : test
You entered : test

Here is the code :

#include <iostream>
using namespace std;

int main( int argc, char** argv )
{
    char *object_name = new char [20];
    cout << "\nPlease enter the name of the object : ";
    cin >> object_name;
    cout << "You entered : " << object_name;
}

How could I get rid of those characters ?

Thank you.

How can I add a SWIG-generated C++ DLL reference to a C# project?

I am using SWIG to generate a DLL that will expose C++ functionality to a C# project. At the moment I:

  1. Define a SWIG interface file

    %module example
    %{
    /* Includes the header in the wrapper code */
    #include "../pointmatcher/PointMatcher.h"
    %}
    
    ...
    
    %include "../pointmatcher/PointMatcher.h"
    
    
  2. Use SWIG to generate a .cxx wrapper

    swig.exe -c++ -csharp -outdir csharp example.i
    
    
  3. Compile the .cxx wrapper with MSBUILD via CMake

    # create wrapper DLL
    add_library(example SHARED ${WRAP_CSHARP_FILE})
    target_link_libraries(example pointmatcher)
    install(TARGETS example
            ARCHIVE DESTINATION ${INSTALL_LIB_DIR}
            LIBRARY DESTINATION ${INSTALL_LIB_DIR}
            RUNTIME DESTINATION ${INSTALL_BIN_DIR})
    
    

I then have a DLL file (example.dll) which I can inspect via Dependency Walker, and confirm that methods are being exposed as follows:

Dependency Walker inspection of DLL

However, when I try to add this MSVC DLL as a reference to a C# project I get the error "It is not a valid assembly or COM component".

Based on answers at How can I add a VC++ DLL as a reference in my C# Visual Studio project? I have confirmed that SWIG itself generates P/Invoke calls, and that tlbimp doesn't recognise the DLL either.

Create Pango Layout Before Cairo Surface

In my application, I am using Pango and Cairo to create text textures. These textures have their width fixed, but should scale their height to fit text contents. The parent objects involved in this situation will then scale their heights to match the text.

The problem is, the way I have been initializing Pango and Cairo does not allow for this. Currently, the system is set up by:

cairo_surface_t* cairoSurface = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, sizeX, sizeY );
cairo_t* cairoContext = cairo_create( cairoSurface );
PangoLayout* pangoLayout = pango_cairo_create_layout( cairoContext );

Which fixes the height, at least of the surface - something I do not want to do, at least not all the time.

My understanding is that if the layout height is not specified, it will automatically scale the height, which can then be found via pango_layout_get_size(). I would like to create the layout first and then use the output of this function to create the surface.

However, pango_cairo_create_layout() requires the surface to already be created, and I have been unable to find a way to render a layout from pango_layout_new() via Cairo. The API docs one of the render functions, pango_cairo_update_layout(), specify that pango_cairo_create_layout() had to be used to create the layout; however, the more important function, pango_cairo_show_layout(), notes no such requirement, and I am not sure if that means that any Pango layout is allowed or not. While I could test if it works, I'm afraid that trial and error could lead me to undefined behavior.

I feel like I'm stuck in a chicken and egg situation, and the documentation for Pango is mostly an API reference with little explanation of how the library is intended to be used. Is there a way to do this properly?


Updating this with some more information.

It seems to partially work if I pass a layout from pango_layout_new() to pango_cairo_show_layout(). To be specific, if I do not set up any kind of fonts, just create an empty ft2 fontmap, it will render, but with boxes for all characters. If I do set up a fontmap, it crashes on pango_cairo_show_layout(). The relevant portions of the setup are:

FcConfig *fontConfig = FcConfigCreate();
gchar* workingDir = g_get_current_dir();
gchar* resourceDir = g_strjoin( NULL, workingDir, "/Resources", (char*)0 );
FcConfigAppFontAddDir( fontConfig, (const FcChar8*)resourceDir );
g_free(workingDir);
g_free(resourceDir);
FcConfigBuildFonts( fontConfig );
FcConfigSetCurrent( fontConfig );

PangoFontMap* font_map = pango_ft2_font_map_new();
PangoContext* context = pango_font_map_create_context( font_map );
PangoLayout* pangoLayout = pango_layout_new( context );

PangoFontDescription* font_desc = pango_font_description_from_string( defaultFont.c_str( ) );
pango_layout_set_font_description( pangoLayout, font_desc );
pango_font_map_load_font( font_map, context, font_desc );
pango_font_description_free( font_desc );

pango_cairo_show_layout( cairoContext, pangoLayout );

I'm still at a complete loss as to how to handle any of this, let alone why the program would crash without any kind of feedback on this function. Even potentially helpful documentations or examples would be appreciated.

How to check the window handle is password field?

I have a window handle (HWND), which was captured from another process not by the current process. Now I have to check The edit control is password field or a normal text field. can I do it successfully?

 I am trying with this one but always I got 0 as result.

uint EM_GETPASSWORDCHAR=210;

SendMessage(hWnd.ToInt32(), EM_GETPASSWORDCHAR, 0, 0);

Compiler C++ for a site, auto-debugger, show the errors [duplicate]

This question already has an answer here:

Guys I have a BIG question for you, I want to make an educational software on a website which helps people to remove the errors from their code, for that I need a c++ compiler (someone can help me with that? i want to put it on the website), an auto-debugger...what means that? I want to process the code from a text-box (an html elemnt) like: if(a == b); the auto-debugger must show: correct sintax is: if(a == b) and you mistake is when you put ";". Someone can help me with that? My first necessity is the C++ compiler for an website, and the second is the auto-debugger pls help. :)) Here we can use HTML, PHP, MySql, Jscript, etc... I will post here the website after i finish those things, so stay tunned ;)

forcing template type to be reference by deduction

Say I have a function func:

template<typename T>
auto func(T arg){
    std::cout << std::boolalpha;
    std::cout << "T is ref: " << std::is_reference<T>::value << '\n';
}

Is there a way I can force T to be deduced as a reference type without explicitly specifying the template parameters?

Like being able to write something like:

auto main() -> int{
    auto x = 5;
    func(std::ref(x));
}

but without having to specialize for std::reference_wrapper.

static_casting does not stop the decay of int& into int for T.

Imagine that I can not change the function signature.

Compile IPerf 2.0.5 source for Android 5.0.2 with Position Independent compilation method

How can I compile IPerf 2.0.5 to generate Position Independent Executable for Android Lollipop 5.0? Can you also share more details on where to add compiler flags in make file of iperf 2.0.5 source code.

The Iperf Source code is found here.

C++ Crash/exception handler in Qt application with thread support on Windows

I want to make a crash/exception handler for my Qt application. I have the handler working already (not included in the code below). The problem is on Windows that it only works if the crash occures in the same thread where signal() and std::set_terminate() is called.

On Linux it seems to work for all threads by default.

Is there a way to make it work for all application threads on Windows?

#include "mainwindow.h"
#include <QApplication>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <exception>

void seg_handler(int sig)
{
    // Crash/exception handling code
    // ...
    exit(1);
}

void std_handler( void ) {
     seg_handler(1);
}

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

    signal(SIGSEGV, seg_handler);
    std::set_terminate( std_handler );

    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

Why to chose Universal App(C++) over Universal App (C#) for Windows? [on hold]

Okay. Here is what I know. First of all C# can have great performance on Windows OSs, sometimes better than C++, because it is optimized at the transition from IL to machine language. It is, of course, more manageable than C++.

There are lots of things that I don't know. Can somebody enlighten this topic?

Vera++ Setup Issues

Basically, I have some code that me and a group of others is working on. We have some tests written for nightly testing using Ctest, google mock, and google test. Now we want to use Vera++ to check our coding styles. None of us have ever used this before and I'm not familiar with how this works. I looked at the installation documentation on their Bitbucket site, but I can't seem to understand how it actually is run and works. I didn't build it from the source code, I just ran the executable, because I'm lazy. Does anyone know how this is run, or know of any documentation or tutorials elsewhere that i can find to educate myself?

Is this a good algorithm to implement it by C++/OpenCL?

In the main script:

1- define 4 string variables (read them from input file).

2- pass them to kernel.


In the Kernel (3000 threads)

1- read the 4 string variables.

2- do some math operations (SQRT, EXP, …) on the global id and put the result in the X double variable.

3- Insert this double variable between Strings.

4- generate txt file and put the stings and X in it.

5- call NGSPICE ROUTINE (it is a simulation tool and can be called by SYSTEM).

6- NGSPICE will output a file.

7- we need to read this file to find a number that we will consider it our Kernel output.

8- We have to compare all kernel outputs and get the Lowest one.

9- print the lowest number to txt file.

My questions are:

  • did you think this Algorithm will give me a good results?
  • Is it possible to do all these steps in kernel?
  • Since I did not find a lot examples for deal with Strings by OpenCL could you please give me any related resources or examples.

QT How to read a ComboBox from a different source?

In my main.cpp I set an identifier using a combo box. In a different source.cpp I want to be able to read the current value in the combo box. I've tried...

Ui::MainWindow->comboBox->currentText();

but that just gives me the error...

expected primary-expression before '->' token
     QString identifier =  Ui::MainWindow->comboBox->currentText();

What am I missing? Was I supposed to define Ui::MainWindow in my header file? Or is their a better way of doing this? Thanks

32bit Flash thunk hook code OK. but 64bit code occur 'Access Violation'

I write vc++ code with flash.

I want to hooking flash because mouse right button operation and flash's transparent.

In my code, use flash32*.ocx or flash64*.ocx (Active-X)


reference code :

  1. 플래시콘 컨트롤 (FlashconAxWindow) | 마을 :: 컨텐츠 상세보기 (korean. sorry^^).

  2. Another new thunk copy from ATL - CodeProject.


32bit compile and execute all ok. but in 64bit program occur access violation


Here is sample code : ThunkTest.zip - Google Drive

(VS2005 project)

Please help or advice.

Obstacle detection using image processing

My project goal, is the detection of obstacle using image processing, I've searched several times on the net in order to find some leads, but in turn, there is no such thing quit clear.

However, I think that the stereoscopy may work through the disparity map.

So guys, I'm begging you to give me some leads, or codes, or anything that may help.

Regards.

Boost serialization of class handling a possible null pointer

I want to serialize the following class wrapping a pointer which can handle a null m_element as you can see when calling the default constructor. This follows this question.

Live MCVE on Coliru

template <typename T>
struct Ptr { // Ptr could use init constructor here but this is not the point
    Ptr() { m_elem = 0; }
    Ptr(const T* elem) {
        if (elem)
            m_elem = new T(*elem);
        else
            m_elem = 0;
    }
    Ptr(const T& elem)
    {
        m_elem = new T(elem);
    }
    Ptr(const Ptr& elem)
    {
        if (elem.m_elem)
            m_elem = new T(*(elem.m_elem));
        else
            m_elem = 0;
    }
    virtual ~Ptr() { delete m_elem; m_elem = 0; };

    const T& operator*() const { return *m_elem; };
    T& operator*() { return *m_elem; };

    const T* operator->() const { return m_elem; };
    T* operator->() { return m_elem; };

    T* m_elem;
};

namespace boost { namespace serialization {

    // Not sure about the approach to manage null m_elem here
    template<class Archive, class T>
    void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
    {
        T elem = 0;
        if (ptr.m_elem != 0)
            ar& boost::serialization::make_nvp("data", *ptr.m_elem);
        else
            ar& boost::serialization::make_nvp("data", elem);
    }

    // How to implement load ?
    template<class Archive, class T>
    void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
    {
        T *elem;
        ar & boost::serialization::make_nvp("data", elem);
    }

    template<class Archive, class T>
    void serialize(Archive & ar, Ptr<T> &ptr, const unsigned int version)
    {
        boost::serialization::split_free(ar, ptr, version);
    }

}} // end namespace


int main()
{
    {
        Ptr<A> p;
        std::ostringstream oss;
        boost::archive::xml_oarchive oa(oss);
        oa << BOOST_SERIALIZATION_NVP(p);
        std::cout << oss.str() << std::endl;

        // The deserialization gives a compiler error here
        /*
        Ptr<double> po;
        std::istringstream iss;
        iss.str(oss.str());
        boost::archive::xml_iarchive ia(iss);
        ia >> BOOST_SERIALIZATION_NVP(po);
        */
    }
    {
        Ptr<double> p(new double(2.0));
        std::cout << *(p.m_elem) << std::endl;

        std::ostringstream oss;
        boost::archive::xml_oarchive oa(oss);
        oa << BOOST_SERIALIZATION_NVP(p);
        std::cout << oss.str() << std::endl;

        // The deserialization gives a compiler error here
        /*
        Ptr<double> po;
        std::istringstream iss;
        iss.str(oss.str());
        boost::archive::xml_iarchive ia(iss);
        ia >> BOOST_SERIALIZATION_NVP(po);
        */
    }
}

The serialization seems to work but the deserialization gives a compiler error here. I am working in C++0x.

  • How can I provide safe save and load functions for serializing Ptr without changing Ptr if possible ?
  • If you recommend to change Ptr, what do you propose ?

How to debug binding parameters in SQLite3?

In the other question I learned how to properly bind parameters to prepared SQL statements. However, I found out that sqlite3_step() returns with SQLITE_DONE if I don't bind all parameters. I would rather consider this to be an error. Furthermore, I do not know if this is the source of error in my code, hence my questions aim at understanding how to debug the behavior of SQLite during the binding process:

  1. How can I determine which parameters are not set?
  2. Can I somehow see the statement with bound parameters inserted, for debugging purposes?
  3. Why does SQLite not respond with SQLITE_NOT_ALL_PARAMETERS_SET or SQLITE_ERROR if not all parameters are set?

wxWidgets console application in Code::Blocks

I need to create a console application in Code::Blocks using some of wxWidgets classes (such as wxThread, wxHTTP, ...).

There are no "wxWidgets console application" wizard in Code::Blocks, so I choose just a "Console application", getting main.cpp created with the following code:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

It compiles and runs Ok.

When I replace it with a contents of examples/samples/console/console.cpp from wxWidgets's examples (skipped some text to be shorter):

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
    #include "wx/wx.h"
#endif
#include <wx/app.h>
#include <wx/cmdline.h>

// implementation
static const wxCmdLineEntryDesc cmdLineDesc[] =
{
    ...
};

int main(int argc, char **argv)
{
    wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
    //!: **ERROR HERE:^**

    wxInitializer initializer;
    if ( !initializer )
    {
        fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
        return -1;
    }
    ...
    // do something useful here
    return 0;
}

I got "undefined reference to wxAppConsoleBase::CheckBuildOptions(char const*, char const*)" error (gcc) at specified line.

What am I doing wrong?

How to fix this?

I can compile my GUI projects with wxWidgets (version 3.0) with no problem, so it looks like I need to specify some defines, includes or any other magic to make it work. I tried to understand example's makefile, but with no luck.

Declare a function noexcept which can theoretically throw but not practically

Is it safe to declare the following function noexcept even though v.at(idx) could theoretically throw a out_of_range exception, but practically not due to the bounds check?

int get_value_or_default(const std::vector<int>& v, size_t idx) noexcept {
    if (idx >= v.size()) {
        return -1;
    }
    return v.at(idx);
}

Visual Studio 2015: C++ decorations despite extern "C"

I'm trying to use an SDK from that I have a H and OBJ file. The H file declares all functions as extern "C", yet while linking, I get "Can't resolve external symbol _ibclr@4". The function is called ibclr and takes a 4B-parameter, so it looks like that's just the C++ decoration. But how is extern "C" not working?

Compiler error when passing rvalue reference through variadic templates

There is a requirement where I need to pass an rvalue from 1 function to another function via variadic template. To avoid real code complexity, minimal example is below using int:

void Third (int&& a)
{}

template<typename... intrgs>
void Second (intrgs&&... args) {
  Third(args...);
}

void First (int&& a) {
  Second(std::move(a));  // error: cannot bind ‘int’ lvalue to ‘int&&’
  Third(std::move(a));  // OK
}

int main () {
  First(0);
}

First(0) is called properly. If I invoke Third(int&&) directly then it works fine using std::move(). But calling Second(Args&&...) results in:

error: cannot bind ‘int’ lvalue to ‘int&&’
   Third(args...);        ^
note:   initializing argument 1 of ‘void Third(int&&)’
 void Third (int&& a)

What is the correct way to achieve the successful compilation for Second(Args&&...)?

FYI: In real code the Second(Args&&...) is mix of lvalues, rvalues and rvalue references.

What all can be the third arguement in for_each in C++?

What all can be the third parameter in for_each in C++ ? I read its unary function but the code which I encountered had object of some class as third arguement.

c++ OLE Microsoft Word - scrolling

Is it possible to catch scroll event from Microsoft Office word? For example if somebody scrolls document I want to know that he scrolls and get position of scrollbar?

I need to use pure c++ and winapi. Of course is possible to use OLE or something else but in c++.

Data compare of files is wrong. Why?

So, the thing is, this program checks if there are duplicate files in a directory. It uses mostly the windows.h library. To spare code, all the file paths are stored in the buffer finalizedList. The list is always correct, don't worry about it.

To show you the problem, here are the files in the directory:

  • duplicate_delete.exe = The program itself
  • hello.txt = The original text file
  • hello - Copy.txt = A duplicate of "hello.txt". They are exactly the same.
  • hello.cpp = A file that has the exact same name with the original text file, except its extension. (AKA "The Bad Guy")

Now, anytime I run the program while "hello.cpp" is in the directory, this is the output of the program:

Creating list...
Finalizing list...
Starting compare procedure...
Checking: duplicate_delete.exe vs. hello - Copy.txt --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.cpp --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.txt --> DIFFERENT
Checking: hello - Copy.txt vs. hello.cpp --> DIFFERENT
Checking: hello - Copy.txt vs. hello.txt --> DIFFERENT
Checking: hello.cpp vs. hello.txt --> DIFFERENT
Finished.
Press any key to continue . . .

But, when I delete that file the output is this:

Creating list...
Finalizing list...
Starting compare procedure...
Checking: duplicate_delete.exe vs. hello - Copy.txt --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.txt --> DIFFERENT
Checking: hello - Copy.txt vs. hello.txt --> DUPLICATE
Finished.
Press any key to continue . . .

Now... Why does that happen? Or to put it in a better way, how can that happen?

Here are parts of the code:

This is the function that initiates the compare procedure between all the files:

void startCompare()
{
    WCHAR currentFile[1024], comparedFile[1024];
    DWORD i, j;
    i = 0;

    for (j = 0; j < fileListP; ++j)
    {
        lstrcpy(currentFile, finalizedList[j]);
        if (!openFile1(currentFile)) wprintf(L"File \"%ls\" couldn not be opened for comparing.\n", currentFile);
        else
        {
            for (i = j + 1; i < fileListP; ++i)
            {
                lstrcpy(comparedFile, finalizedList[i]);
                if (!openFile2(comparedFile)) wprintf(L"File \"%ls\" couldn not be compared with file \"%ls\".\n", currentFile, comparedFile);
                else
                {
                    if (!compare())
                    {
                        wprintf(L"Checking: %ls vs. %ls --> DUPLICATE\n", currentFile, comparedFile);
                        lstrcpy(deleteList[deleteListP], currentFile);
                        ++deleteListP;
                    }
                    else
                    {
                        wprintf(L"Checking: %ls vs. %ls --> DIFFERENT\n", currentFile, comparedFile);
                    }
                    CloseHandle(file2);
                }
            }
            CloseHandle(file1);
        }
    }
}

The handles are internally set by the functions "openFile1" and "openFile2". If the two last functions return 0, it means that the handles weren't set successfully.

This function actually compares the files "file1" and "file2".

DWORD compare()
{
    DWORD a, b;
    BYTE byte1, byte2;

    while (1)
    {
        ReadFile(file1, &byte1, 1, &a, NULL);
        ReadFile(file2, &byte2, 1, &b, NULL);
        //a = fread(&byte1, 1, 1, file1);
        //b = fread(&byte2, 1, 1, file2);
        if (a != b) return 1;
        if (byte2 != byte1) return 1;
        if (a == 0 && b == 0) break;
    }

    return 0;
}

How to get current disk number/name which contains running Windows/Linux?

Let's assume that a PC contains several storage devices and we have C++/Qt utility which contains 2 blackbox functions (we don't consider their implementation here):

QString get_disk_serial(int drive_number); //for Windows 

QString get_disk_serial(const QString& device); //for Linux. For example, "/dev/sda"

I need to know (using C++) which disk is used in the current session (what disk number is active/what device name is active). In my context active disk is a disk which contains the partition, which in turn contains running operating system.

How to set mouse move frequency

I need to update my window each time I catch the mouse move event, but I would like to call the update function not to many times (since it would be only a waste of computational time).

Let's say that I would like to update the window only once for each second, that is, if in a single second I receive 20 mouse move calls I will perform only the first call ignoring the following 19 calls.

LRESULT WndProc()
{
case WM_MOUSEMOVE:
   update(); // avoid to many calls
}

Should I use a simple counter and a stopwatch or are there better ways to do the same thing?

implement factory pattern for products with conditional compiling

I'd like to implement factory (or some other pattern) in a way that will allow me to compile the code without introducing type dependency.

enum CarType
{
 BMW,
 PORSCHE,
 MERC
};

class CarFactory
{
  public:
 static Car* create(CarType type)
 {
  switch(type)
  {
    case BMW : return new BMWCar();
    case PORSCHE : return new PorscheCar();
    default : return new MercCar();
  }
 }
};

When I compile CarFactory, I need to include BMWCar, PorscheCar and MercCar as a part of my compilation/linking unit.

The way my codebase is setup, we may want to ship BMWCar only, or two or all three of them. So, I cannot make the create() dependent on the type.

How can I adapt the factory pattern for this ? Also, I'd like to avoid doing ifdefs since this is just a sample of my problem. The real codebase is huge and is not a practical solution to ifdef the code.

Update: Also, I am not allowed to use:

  • templates
  • has to conform to c++ 98 standard
  • cannot use boost

These are mostly due to customer build toolchain restrictions. I don't have a choice in changing these.

Concatenating mismatched string WORKS in VC2015 - How?

When we have either of these:

auto city1 = "New "  L"Delhi";
auto city2 = L"New " "York";

Any pre-VS2015 compiler would raise error:

error C2308: concatenating mismatched strings

But with VC2015 compiler, it compiles well and the resultant type (auto deduction) is a wide-char string.

My question is: When and How this is made possible - any standard specification?

displaying 16bit unsigned integers in opengl

I would like a simple way of achieving this, but seem to be bjorking the parameters to glTexImage2D. I have an std::vector<uint16_t> depth_buffer that, on a frame-by-frame basis has depth measurements coming from a kinect. There are exactly 640 x 480 of them, one depth measurement per pixel. If the world went my way, the call should be

glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, 640, 480, 0, GL_LUMINANCE16, GL_UNSIGNED_SHORT, depth_buffer.data());

Where internalFormat (third parameter) is GL_LUMINANCE16 because they are 16 bit unsigned integers, and format is the same because that is exactly how the data is coming in. The type parameter should be GL_UNSIGNED_SHORT...because these are shorts and not bytes.

Surprisingly, if I change it to be

glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, 640, 480, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, depth_buffer.data());

where internalFormat is still GL_LUMINANCE16, format is just GL_LUMINANCE without the 16, and type is GL_UNSIGNED_BYTE, then I get something. Things are clearly being skipped, but just changing to GL_UNSIGNED_SHORT doesn't cut it.

Depending on which documentation you read, format (the second GL_LUMINANCE) may or may not allow the 16 after it (anybody know why? experimentation seems to confirm this). But my chief concern here is why GL_UNSIGNED_**SHORT** seems to be invalid (either all black or all white) depending on the internalFormat -- format combination.

I've tried an obscene amount of combinations here, and am looking for the right approach. Anybody have some advice for achieving this? I'm not opposed to using fbo's, but would really like to avoid it if possible...since it definitely should be doable.

Thanks for any help!

Mutex for simple data types

I'm pretty new to concurrency, and I'm having trouble deciding on how to use mutexes. At the moment they are sprinkled all over my code where two threads interact. Would this use of mutexes be appropriate?

class Foo
{
public:
    void SetMember(int n) {  AcquireMutex(..); n_ = n; ReleaseMutex(...);}
private:
   Thread()
   {
      while(1)
      {
         AcquireMutex(..);
         // Do something with n_
         ReleaseMutex(...);
       }
   }
};

I have quite a few data members that can be read and set from the outside by a different thread, and I'm finding it to be a headache to keep track of all the acquiring and releasing of mutexes.

Incompatibility of linking between different Visual C++ objects and the DirectX SDK

I understand that attempting to link objects/libraries that were compiled with different Visual C++ toolset versions will result in failure as was described here error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj.

However, when working with the 2010 DirectX SDK there is seemingly no problem with linking to these old libraries (eg. d3d11.lib, etc.) even if we use VC++12/13/15.

Why is it that we can link to these old DirectX libraries but not ones created by earlier versions of VC++. Also, if not VC++, what was used to compile these DirectX libraries in the first place?

Changing type for each variadic template argument

I have some class:

template<typename... Args>
class X
{
    using F = void(*)(Args...);
};

Now I want variadic parameters in F definition become converted with a specific condition:

using F = void(*)(typename std::conditional<std::is_fundamental<Args>::value, Args, Args&&>::type...);

So, for example, for class X<int, MyCustomT> definition X::F should become void(*)(int, MyCustomT&&)

WebView loadUrl(url) is opening in default browser

im trying to make app based on WebView of mobile page. The thing is that page loads in default user's browser instead of app. Here is my code, any thoughts about what am i doing wrong?

package pl.beat_down.bdmobile;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.app.Activity;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://beat-down.pl/m";
WebView view = (WebView) this.findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) { 
int id = item.getItemId();

if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}    

c++ function passes bad parameter

I have this function as constructor:

Graph::Graph(std::string filename)
{
    std::ifstream file(filename);
    file >> vertexNum_;
    edgeNum_ = 0;
    int edges;
    file >> edges;
    for(int i = 0; i < edges; edges++)
    {
        int s,e;
        file >> s;
        file >> e;
        if(!AddEdge(s,e)){
            std::cout << "Bad file!";
            break;
        }
    }
    file.close();
}

When I call from main Graph g("test.in"); it gives me Segfault because in the function parameter filename is empty string (shown in debugger). I'm using QtCreator.

Any ideas where the problem is?

TEdit Input Validation on C++ Builder XE8

I am very new to C++ Builder XE8.

I want the minimum and maximum length of numbers that must be typed is as much as six numbers, also I need to make sure that only number is entered (0 is exception), and not an alphabetic character, backspace, punctuation, etc.

I would also like to produce an error box if anything other than a number is entered.

I've tried a few combinations of codes, three of which can be seen below, but none of those codes works.

Any help would sure be appreciated!

(1).

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key)
{
  Edit1->MaxLength = 6;

  if (!((int)Key == 1-9)) {
  ShowMessage("Please enter numerals only");
  Key = 0;
  }
}

(2).

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key)
{
  Edit1->MaxLength = 6;

  if (Key <1 && Key >9) {
  ShowMessage("Please enter numerals only");
  Key = 0;
  }
}

(3).

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key)
{
  Edit1->MaxLength = 6;

  if( Key == VK_BACK )
   return;

  if( (Key >= 1) && (Key <= 9) )
   {
  if(Edit1->Text.Pos(1-9) != 1 )
   ShowMessage("Please enter numerals only");
   Key = 1;
  return;
  }
}

Error when using Decision Trees in OpenCV 3.0.0-rc1

I am doing some machine learning in OpenCV and i'm using Decision Trees. I am currently using OpenCV 3.0.0-rc1. Whenever i attempt to train Decision Trees with my training data and labels, i get either

terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

or

Segmentation fault

Depending on what i put into setMaxDepth(); if the number is larger than 22, it's bad_alloc, else it's seg fault. Here's my source code:

//import data
Mat trainData=imread("/home/jetson/Documents/CB/ml/td.jpg",CV_LOAD_IMAGE_GRAYSCALE);
Mat labels=imread("/home/jetson/Documents/CB/ml/lab.jpg",CV_LOAD_IMAGE_GRAYSCALE);
//convert to the right type
trainData.convertTo(trainData,CV_32FC1);
labels.convertTo(labels,CV_32SC1);
transpose(trainData,trainData);
Ptr<ml::TrainData> tData = ml::TrainData::create(trainData, ml::ROW_SAMPLE, labels);

cout <<"Training data ready\n";

Ptr<ml::DTrees> dec_trees = ml::DTrees::create();
//params
dec_trees->setMaxDepth(1);
dec_trees->setMinSampleCount(10);
dec_trees->setRegressionAccuracy(0.01f);
dec_trees->setUseSurrogates(false);
dec_trees->setMaxCategories(2);
dec_trees->setCVFolds(10);
dec_trees->setUse1SERule(true);
dec_trees->setTruncatePrunedTree(true);
dec_trees->setPriors(Mat());

cout <<"Params set\n";
dec_trees->train(tData);
cout <<"Done!\n";`

In addition to this, when i try to train a SVM model with the same data, using the same steps (below) it works just fine.

Ptr<ml::SVM> svm = ml::SVM::create();
//params
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::POLY);
svm->setGamma(3);
svm->setDegree(0.1);

cout <<"Params set\n";
svm->train(tData);
cout <<"Done!\n";

I need to point out that the error occurs when i try to train the model. I'm using the default parameters for decision trees, as suggested on the OpenCV documentation page. Does anybody know what's wrong here and how to go about fixing my problem?

Thanks in advance.

How to parse string pairs over multiple lines?

I'd like to parse content like:

tag = value
tag2 = value2
tag3 = value3

with the relaxation of allowing values over multiple lines and disregarding comments of the next tag. A tag is identified by not starting with the comment identifier '#' and starting at a new line. So this:

tag = value
  value continuation
tag2 = value2
  value continuation2
# comment for tag3
tag3 = value3

should parse the mapping:

tag : "value\nvalue continuation"
tag2 : "value2\nvalue continuation2"
tag3 : "value3"

How can I achieve this in a clean way? My current code for parsing one-line pairs looks sth like this:

while( std::getline( istr, line ) )
{
  ++lineCount;
  if( line[0] == '#' )
    currentComment.push_back( line );
  else if( isspace( line[0]) || line[0] == '\0' )
    currentComment.clear( );
  else
  {
    auto tag = Utils::string::splitString( line, '=' );
    if( tag.size() != 2 || line[line.size() - 1] == '=')
    {
      std::cerr << "Wrong tag syntax in line #" << lineCount << std::endl;
      return nullptr;
    }
    tagLines.push_back( line );
    currentComment.clear( );
  } 
}

Note that I don't require the results being stored in the types of containers that are currently used. I can switch to anything that fits better unless I get sets of (comment, tagname, value).

ALSA Linux C API Producer Consumer Audio Dies and XRun is Unrecoverable

I have a Qt 5.4 Application that runs on Raspberry Pi ( Raspbian Linux ). The main thread receives TCP packets whenever a remote sender decides and stops receiving them after random amounts of time. When it receives audio data, the data is pushed into a global, QSemaphore protected audio buffer. The main thread spawns a separate QThread that consumes data out of the buffer, when available, and plays it through ALSA. The problem is that the audio data begins playing ( and sounding ) fine but after roughly 11 packets received, the initial call to "snd_pcm_sframes_t available = snd_pcm_avail(m_PlaybackHandle);" returns a negative value and is never recoverable. I've tried various combinations of the following to recover the stream:

  • snd_pcm_drop(handle);
  • snd_pcm_drain(handle);
  • snd_pcm_prepare(handle);
  • static int xrun_recovery(snd_pcm_t *handle, int err);

I think I am hitting some kind of underrun/overrun issue but I am not sure who to fix and/or debug it. I do not reset the Audio Handle so I'd like to understand why it is randomly stopping playback and becomes unrecoverable.

  1. How can I debug this issue?
  2. Any ideas as to why this is happening?
  3. I really appreciate any help! Thanks.

Here is the producer:

// If Audio data - write to ALSA
if ( pck->evt_endpoint_data.endpoint == m_AudioEndpoint ) {

#ifdef BLUEGIGA_DEBUG
    qDebug() << "BlueGigaUart: Received Audio Data..." << pck->evt_endpoint_data.data.len;
#endif

    // Latch the endpoint
    m_CurrentEndpoint = m_AudioEndpoint;

    // Increment number received
    m_NumberTCPPacketsReceived++;

    // Create byte array to transfer including Audio Data
    QByteArray audio = QByteArray::fromRawData((const char*)recv_buffer,pck->evt_endpoint_data.data.len);

    // Push data into global audio buffer
    char readByte;
    for (int i = 0; i < audio.size(); ++i) {
        audioBufferIndex++;
        int subscript = audioBufferIndex % MAX_BUFFER_SIZE;
        readByte = audio.at(i);
        freeBytes.acquire();
        singleAudioBuffer[subscript] = readByte;
        usedBytes.release();
    }

    // Turn on the run bit
    m_AudioController->startPlayingAudio();

}

Here is my Thread run() function that consumes:

/**
 * Consume and play Audio data in a background thread
 */
void AudioController::run() {

    // Constantly consume and write audio data to ALSA from global buffer
    // in this background thread
    int counter = 0;
    int multiplier = 5;

    // Check if ALSA is configured - and if not then configure it
    if ( !m_AlsaConfigured ) {
        configureAlsa();
    }

    /** This Audio Buffer buffers enough data so that the Handset can hicup
     * and we will still have enough data to play to ALSA through it all
     */
    QByteArray *globalAudioBuffer = new QByteArray();
    globalAudioBuffer->clear();

    // Do this forever
    forever {

        usedBytes.acquire();
        char data = singleAudioBuffer[counter % MAX_BUFFER_SIZE];
        QByteArray audio = QByteArray::fromRawData((const char *)&data,1);
        globalAudioBuffer->append(audio);
        freeBytes.release();
        counter++;

        // Do we have enough buffers' worth?
        if ( globalAudioBuffer->length() >= ( EXPECTED_AUDIO_SIZE * multiplier ) ) {

            // Check if ALSA is configured - and if not then configure it
            if ( !m_AlsaConfigured ) {
#ifdef true
                qDebug() << "AudioController: Configuring ALSA...";
#endif
                configureAlsa();
            }

            // Push data into global audio buffer
            int bufferSize = 2400000;
            qint16 audioData[bufferSize];
            memset(audioData,0x00,bufferSize); // Zero it out
            int i = -1;
            while ( i++ < globalAudioBuffer->size() && (i++ < bufferSize) ) {
                if ( i >= globalAudioBuffer->size() ) {
                    break;
                }
                quint8 readByte = globalAudioBuffer->at(i);
                qint16 finalByte = readByte - 127;
                finalByte = finalByte * 258;
                audioData[i] = finalByte;
            }

            if ( m_ShouldPlayAudio && !m_NonTcpAudioPlaying ) {

                // Write the data to the ALSA device
                int error;
                fprintf(stderr,"snd_pcm_avail %d \n",snd_pcm_avail(m_PlaybackHandle));
                snd_pcm_sframes_t available = snd_pcm_avail(m_PlaybackHandle);
                fprintf(stderr,snd_strerror(available));
                if ( available < 0  ) {
                    /*
                     *  WHAT THE HECK THIS LOCKS UP?! After 11 packets of 239 bytes I get a negative available value
                     */
                    //snd_pcm_drop(m_PlaybackHandle);
                    //snd_pcm_prepare(m_PlaybackHandle);
                    //globalAudioBuffer->clear();
                    //continue;
                }
                //snd_pcm_drop(m_PlaybackHandle);
                //snd_pcm_prepare(m_PlaybackHandle);
                if ((error = snd_pcm_writei (m_PlaybackHandle, globalAudioBuffer->data(), globalAudioBuffer->size() < available ? globalAudioBuffer->size() : available)) != (globalAudioBuffer->size() < available ? globalAudioBuffer->size() : available)) {

                    if ((error != -EAGAIN) && (error < 0)) {

                        fprintf(stderr, "ALSA Play Error: %s\n", snd_strerror(error));

                        // Recover from underrun
                        if (xrun_recovery(m_PlaybackHandle, error) < 0) {

                            // No longer configured
                            m_AlsaConfigured = false;

                            // The handle becomes NULL
                            m_PlaybackHandle = NULL;

                            // Reset ALSA
                            configureAlsa();

                        }

                    }
                }

            }

            qDebug() << "Clearing buffer...";
            globalAudioBuffer->clear();

        }

    }

}

Here is the xrun recovery function:

/**
* ALSA Underrun and suspend recovery
*/
static int xrun_recovery(snd_pcm_t *handle, int err)
{

#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Recovering from Audio Xrun ( Overrun / Underrun )...";
#endif

    if (err == -EPIPE) { /* under-run */
        err = snd_pcm_prepare(handle);
        if (err < 0)

#ifdef AUDIO_DEBUG
            qDebug() << "Cannot recover from underrun - prepare failed!";
#endif
            printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));

            // Resetting ALSA now

#ifdef AUDIO_DEBUG
            qDebug() << "Cannot recover from underrun - Resetting ALSA Now!";
#endif

            // Cleanup and Close ALSA
            snd_pcm_drain(handle);
            snd_pcm_close(handle);
            handle = NULL;
            return -1;

        } else if (err == -ESTRPIPE) {
            while ((err = snd_pcm_resume(handle)) == -EAGAIN)
                sleep(1); /* wait until the suspend flag is released */
            if (err < 0) {
                err = snd_pcm_prepare(handle);
            if (err < 0)

#ifdef AUDIO_DEBUG
                qDebug() << "Cannot recover from suspend - prepare failed!";
#endif

                printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));

#ifdef AUDIO_DEBUG
                qDebug() << "Cannot recover from suspend - Resetting ALSA Now!";
#endif

                // Cleanup and Close ALSA
                snd_pcm_drain(handle);
                snd_pcm_close(handle);
                handle = NULL;
                return -1;

        }
        return -1;
    }
    return err;

}

Variables declared for this code:

#include <QSemaphore>

#define PRODUCER_DATA_SIZE 1000000000
#define MAX_BUFFER_SIZE 2048

extern long long int audioBufferIndex;
extern char singleAudioBuffer[];
extern QSemaphore freeBytes;
extern QSemaphore usedBytes;

ALSA setup code:

/**
 * Configure ALSA
 */
void AudioController::configureAlsa() {

#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Configuring ALSA...";
#endif

    // Error handling
    int err;

    // Device to Write to
    const char *snd_device_out = "default";

    if ((err = snd_pcm_open (&m_PlaybackHandle, snd_device_out, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
        fprintf (stderr, "Cannot open audio device %s (%s)\n",
                 snd_device_out,
                 snd_strerror (err));
#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Cannot open Audio Device...";
#endif

        // Reset Modules and try again
        configureAlsa();

    }

    if ((err = snd_pcm_hw_params_malloc (&m_HwParams)) < 0) {
        fprintf (stderr, "Cannot allocate hardware parameter structure (%s)\n",
                 snd_strerror (err));
#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Cannot open allocate hardware parameter structure...";
#endif

        // Reset Modules and try again
        configureAlsa();

    }

    if ((err = snd_pcm_hw_params_any (m_PlaybackHandle, m_HwParams)) < 0) {
        fprintf (stderr, "Cannot initialize hardware parameter structure (%s)\n",
                 snd_strerror (err));
#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Cannot initialize hardware parameter structure...";
#endif

        // Reset Modules and try again
        configureAlsa();

    }

    if ((err = snd_pcm_hw_params_set_access (m_PlaybackHandle, m_HwParams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
        fprintf (stderr, "Cannot set access type (%s)\n",
                 snd_strerror (err));
#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Cannot set access type...";
#endif

        // Reset Modules and try again
        configureAlsa();

    }

    //if ((err = snd_pcm_hw_params_set_format (m_PlaybackHandle, m_HwParams, SND_PCM_FORMAT_U8)) < 0) { // Unsigned 8 bit
    if ((err = snd_pcm_hw_params_set_format (m_PlaybackHandle, m_HwParams, SND_PCM_FORMAT_S16)) < 0) { // Signed 16 bit
        fprintf (stderr, "Cannot set sample format (%s)\n",
                 snd_strerror (err));
#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Cannot set sample formate...";
#endif

        // Reset Modules and try again
        configureAlsa();

    }

    uint sample_rate = 8000;
    if ((err = snd_pcm_hw_params_set_rate (m_PlaybackHandle, m_HwParams, sample_rate, 0)) < 0) { // 8 KHz
        fprintf (stderr, "Cannot set sample rate (%s)\n",
                 snd_strerror (err));
#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Cannot set sample rate...";
#endif

        // Reset Modules and try again
        configureAlsa();

    }

    if ((err = snd_pcm_hw_params_set_channels (m_PlaybackHandle, m_HwParams, 1)) < 0) { // 1 Channel Mono
        fprintf (stderr, "Cannot set channel count (%s)\n",
                 snd_strerror (err));
#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Cannot set channel count...";
#endif

        // Reset Modules and try again
        configureAlsa();

    }

    if ((err = snd_pcm_hw_params (m_PlaybackHandle, m_HwParams)) < 0) {
        fprintf (stderr, "Cannot set parameters (%s)\n",
                 snd_strerror (err));
#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Cannot set parameters...";
#endif

        // Reset Modules and try again
        configureAlsa();

    }

    snd_pcm_hw_params_free (m_HwParams);

    // Flush handle prepare for playback
    snd_pcm_drop(m_PlaybackHandle);

    if ((err = snd_pcm_prepare (m_PlaybackHandle)) < 0) {
        fprintf (stderr, "cannot prepare audio interface for use (%s)\n",
                 snd_strerror (err));
#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Cannot prepare audio interface...";
#endif

        // Reset Modules and try again
        configureAlsa();

    }

    // It is now configured
    m_AlsaConfigured = true;

#ifdef AUDIO_DEBUG
    qDebug() << "AudioController: Done Configuring ALSA...";
#endif


}

UPDATE: I've added a minimal compilable example here: git@github.com:phishstang65/AudioPlayer.git

Output from running this example looks like this:

AudioController: Done Configuring ALSA...
Playing now...
Playing now...
Playing now...
Playing now...
Playing now...
1195 snd_pcm_avail 2097152 
Playing now...
Playing now...
Playing now...
Playing now...
Playing now...
2390 snd_pcm_avail -32 
Error
Broken pipe
Playing now...
Playing now...

Only first frame showed in RTSP Streaming with libvlc

I want to get video of an IP camera and stream it to another IP by libVLC. I write these codes based on examples of libvlc docs. The video streamed successfully and video showed without any problem in destination.But in my display, only first frame was shown. After some search I guessed this problem will be solve by adding RTP over TCP option. But after this change my problem didn't solve yet.

I use Microsoft visual C++ and my codes are:

#include <stdio.h>
 #include <stdlib.h>
 #include <vlc/vlc.h>
#include <Windows.h>
 int main(int argc, char* argv[])
 {
     libvlc_instance_t * inst;
     libvlc_media_player_t *mp;
     libvlc_media_t *m;


     char *myarg0 = "--sout=#transcode{vcodec=h264,scale=Auto,acodec=mpga,ab=128,channels=2,samplerate=44100}:duplicate{dst=display,dst=rtp{sdp=http://rtspdestinationIP:Port}}";
     char *myarg1="--rtsp-tcp"; 
     char *myargs[2] = {myarg1, myarg0};
     /* Load the VLC engine */
     inst = libvlc_new (2, myargs);

     /* Create a new item */
     char *input="http://user:pass@CameraIP//axis-cgi//mjpg//video.cgi";
     m = libvlc_media_new_location (inst,input ); 

     /* Create a media player playing environement */
     mp = libvlc_media_player_new_from_media (m);

     /* No need to keep the media now */
     libvlc_media_release (m);


     /* play the media_player */
     libvlc_media_player_play (mp);

     Sleep (10000000); /* Let it play a bit */

     /* Stop playing */
     libvlc_media_player_stop (mp);

     /* Free the media_player */
     libvlc_media_player_release (mp);

     libvlc_release (inst);

     return 0;
 }

How to execute yosys passes from an LLVM pass?

I have been working with two programs llvm's opt and clifford wolf's yosys both have similar interfaces for passes.(they use shared libraries as optimization passes)

I want to use certain data structures and functions from yosys.h to build a design module(which is then written in verilog to file) based on the data generated by my llvm opt pass.

PROBLEM: I want to make use of functions,data from yosys.h in the pass for llvm-opt. How do i compile(EDIT: and also execute either on llvm-opt or on yosys or a seperate binary executable) such code? individually they can be compiled and executed as seperate passes.

COMPILE YOSYS PASS

gcc `yosys-config --cxxflags --ldlibs --ldflags` --shared yosyspass.cpp -o yosyspass.so

and execute it with

yosys -m yosyspass.so verilogfile.v

COMPILE LLVM PASS

gcc  `llvm-config --cxxflags --ldlibs` --shared llvmpass.ccp -o llvmpass.so

and execute it with

opt -load ./llvmpass.so -llvmpass Somefile.bc

but how to build code which has both components from llvm , yosys? and how to execute it?

How can i make this happen without changing source code of yosys too much? All of this is to avoid writing a verilog generation backend for my llvm-opt pass.

ONE OF MY SOLUTIONS:

Metaprogramming: i.e., generate the code which when compiled and run as a yosys pass gives me the result.(verilog design file based on llvm opt input)

Maybe i'm missing something fundamental in build shared libraries? I'm new to this sort of thing. any input is welcome.

This project(though unrelated) may be similar to Rotems C-to-Verilog and univ of toronto's legup HLS tool.

I observered some strange error, when I migrated my projects from VS2013. Here is simplified code of a newly created project to reproduce it:

A.cpp:

#include <iostream>

extern void foo();

int main()
{
    std::cout << "some text from main" << std::endl;
    foo();
}

B.cpp:

#include <iostream>

void foo()
{
    std::cout << "some text from foo" << std::endl;
}

The important thing to add is project has "Disable Language Extension" set to Yes (/Za). Without this setting, it is bulding properly.

The output is a long list of following errors:

1>B.obj : error LNK2005: "public: static bool const std::numeric_limits<short>::is_signed" (?is_signed@?$numeric_limits@F@std@@2_NB) already defined in A.obj
1>B.obj : error LNK2005: "public: static int const std::numeric_limits<short>::digits" (?digits@?$numeric_limits@F@std@@2HB) already defined in A.obj
1>B.obj : error LNK2005: "public: static int const std::numeric_limits<short>::digits10" (?digits10@?$numeric_limits@F@std@@2HB) already defined in A.obj
1>B.obj : error LNK2005: "public: static bool const std::numeric_limits<unsigned short>::is_signed" (?is_signed@?$numeric_limits@G@std@@2_NB) already defined in A.obj
1>B.obj : error LNK2005: "public: static int const std::numeric_limits<unsigned short>::digits" (?digits@?$numeric_limits@G@std@@2HB) already defined in A.obj
1>B.obj : error LNK2005: "public: static int const std::numeric_limits<unsigned short>::digits10" (?digits10@?$numeric_limits@G@std@@2HB) already defined in A.obj
1>B.obj : error LNK2005: "public: static bool const std::numeric_limits<char16_t>::is_signed" (?is_signed@?$numeric_limits@_S@std@@2_NB) already defined in A.obj
1>B.obj : error LNK2005: "public: static int const std::numeric_limits<char16_t>::digits" (?digits@?$numeric_limits@_S@std@@2HB) already defined in A.obj
...

This seems to indicate, that VS implementation of <iostream> header breaks One Definition Rule in some nasty way. Is it right, or am I missing something obvious?

ERROR : '__android_log_print' android studio

i've been working with NDK, OpenCV and android studio. But when i start debug my project, it shows error undefined '__android_log_print'

C:/Users/Jeems/Documents/android-ndk-r8d/toolchains/arm-linux-androideabi-4.6/prebuilt/windows/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: build/intermediates/ndk/obj/local/armeabi/objs/pulse/pt_fraunhofer_pulse_Pulse_Face.o: in function i::Java_pt_fraunhofer_pulse_Pulse_00024Face(double):src/main/jni/pt_fraunhofer_pulse_Pulse_Face.cpp:24: error: undefined reference to '__android_log_print'
C:/Users/Jeems/Documents/android-ndk-r8d/toolchains/arm-linux-androideabi-4.6/prebuilt/windows/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: build/intermediates/ndk/obj/local/armeabi/objs/pulse/pt_fraunhofer_pulse_Pulse_Face.o: in function i::Java_pt_fraunhofer_pulse_Pulse_00024Face(double):src/main/jni/pt_fraunhofer_pulse_Pulse_Face.cpp:42: error: undefined reference to '__android_log_print'
C:/Users/Jeems/Documents/android-ndk-r8d/toolchains/arm-linux-androideabi-4.6/prebuilt/windows/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: build/intermediates/ndk/obj/local/armeabi/objs/pulse/pt_fraunhofer_pulse_Pulse_Face.o: in function Java_pt_fraunhofer_pulse_Pulse_00024Face__1box:src/main/jni/pt_fraunhofer_pulse_Pulse_Face.cpp:54: error: undefined reference to '__android_log_print'
C:/Users/Jeems/Documents/android-ndk-r8d/toolchains/arm-linux-androideabi-4.6/prebuilt/windows/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: build/intermediates/ndk/obj/local/armeabi/objs/pulse/pt_fraunhofer_pulse_Pulse_Face.o: in function Java_pt_fraunhofer_pulse_Pulse_00024Face__1box:src/main/jni/pt_fraunhofer_pulse_Pulse_Face.cpp:74: error: undefined reference to '__android_log_print'
collect2: ld returned 1 exit status
make: *** [build/intermediates/ndk/obj/local/armeabi/libpulse.so] Error 1
:pulseandroid:ndkBuild FAILED
Error:Execution failed for task ':pulseandroid:ndkBuild'.
> Process 'command 'C:\Users\Jeems\Documents\android-ndk-r8d\ndk-build.cmd'' finished with non-zero exit value 2

Here is my android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

include C:\Users\Jeems\Documents\OpenCV-2.4.11-android-sdk\sdk\native\jni\OpenCV.mk

LOCAL_MODULE     := pulse
LOCAL_SRC_FILES  := pt_fraunhofer_pulse_Pulse_Face.cpp
LOCAL_SRC_FILES  += pt_fraunhofer_pulse_Pulse.cpp
LOCAL_SRC_FILES  += Pulse.cpp
LOCAL_SRC_FILES  += EvmGdownIIR.cpp
LOCAL_SRC_FILES  += ext/opencv.cpp
LOCAL_SRC_FILES  += profiler/profiler.cpp
LOCAL_C_INCLUDES += $(LOCAL_PATH)
LOCAL_C_INCLUDES += C:\Users\Jeems\Documents\OpenCV-2.4.11-android-sdk\sdk\native\jni\include\
LOCAL_LDLIBS     := -ldl -landroid -llog

include $(BUILD_SHARED_LIBRARY)

Convert string with unicode escape characters to UTF-8 with Qt

I am trying to convert string in unicode to utf-8.

qDebug prints string like this:

"Fault code soap:Client: \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0441 \u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u043E\u043C \u00AB16163341545811\u00BB \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D"

I tried using QTextCodec like this but it outputs same unreadable string:

QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QString readableStr = QString::fromUtf8(codec->fromUnicode(str));

What am I doing wrong?

Command Pattern: Where to create the Command items?

I've used the command pattern quite extensively, and it works well. However, what's usually not discussed is where the instances of the Commands are created.

The following examples illustrate this issue: A Document has a function setText() that sets the text. Depending on whether a Command should be created, a bool withUndo could be added:

class Document {
public:
    void setText(const std::string text, bool withUndo) {
        if (withUndo) {
            commandManager()->addAndExecute(new SetTextCommand(this, text));
        } else {
            m_text = text;
        }
    }
private:
    std::string m_text;
}

Here, the SetTextCommand would execute document->setText(text, false) to perform the real work.

This interface allows both: Directly modifying the data model (withUndo == false) and modification through the Command pattern.

It is obvious that both is needed, since /somewhere/ these Commands needs to be created.

However, it is rather obvious, that this API is bad, since every function that modifies the data model needs the extra bool withUndo.

From that follows the question: How to implement this in a clean way?

PS: I have ideas myself, but I feel this must be a solved problem with good solutions.