jeudi 13 août 2015

Precompile C++ vendor Libraries (#include api.h)

First of all, I have to say, that I am an absolute beginner in c++ and all the compiler stuff that is going on for native development.

What I am actually trying to do, is to create a NodeJS binding, to wrap an existing library. The library itself has a api.h which I can include in my wrapper an use it to built my Wrapper methods. The problem which I have, is that the library itself is quite large:

  src/  
    vendor/
      libA/..
      libB/..
      libC/..
      api.h 
      api.cpp 
    addon.cpp (where I am including the "vendor/api.h")

so every time I am compiling my addon.cpp all the libraries have to be recompiled again and again, which sucks. So what is the best way to compile the api once and use it in my addon.cpp (I am not using any of the libs in my addon only the api.h!)

By the way I am working on a Ubuntu 14.04 and I am using Cmake to perform the compilation:

To compile my addon with all the libraries, I am defining all the SOURCE_FILES like this:

file(GLOB SOURCE_FILES
 "src/addon.cpp"
 "src/vendor/*.cpp" "src/vendor/*.h"
 "src/vendor/libA/*.c" "src/vendor/libA/*.h"
 "src/vendor/libB/*.cpp" "src/vendor/libB/*.h"
 "src/vendor/libC/*.c" "src/vendor/libC/*.h"
)

...
add_library(addon SHARED ${SOURCE_FILES})

To compile it, I am calling

cmake-js rebuild

cmake-js because it also loads some NodeJS required stuff, but the CMakeLists.txt file uses the normal cmake syntax

So any help would be really awesome, thanks!



via Chebli Mohamed

Installation of PyICU on Heroku

Anyone know how to install PyICU on Heroku?

Here is what I tried so far:

  1. Created a heroku-buildpack-multi application.

In .buildpacks

http://ift.tt/11oNluO
http://ift.tt/1pcK0Du

In Aptfile

libicu52
libicu-dev

Then heroku run bash

CPATH=$CPATH/app/.apt/usr/include/x86_64-linux-gnu
pip install PyICU

And it installs fine.

I need one way to do that during the application's upload phase (push).

I tried:

pip install --global-option=build_ext --global-option="-I/app/.apt/usr/lib/x86_64-linux-gnu" PyICU

and to create a .pydistutils.cfg file in my home directory as

[build_ext]
include_dirs=/app/.apt/usr/include/x86_64-linux-gnu

In both cases GCC fails to find the header files, but I can see the

-I/app/.apt/usr/lib/x86_64-linux-gnu

flag on the command line.

Used

`gcc -print-prog-name=cc1plus` -v

to find the differences in search paths before and after CPATH=$CPATH/app/.apt/usr/include/x86_64-linux-gnu

Before:

#include <...> search starts here:
/app/.apt/usr/include
.
/usr/include/c++/4.8
/usr/include/x86_64-linux-gnu/c++/4.8
/usr/include/c++/4.8/backward
/usr/lib/gcc/x86_64-linux-gnu/4.8/include
/usr/local/include
/usr/lib/gcc/x86_64-linux-gnu/4.8/include-fixed
/usr/include
End of search list.

After:

#include <...> search starts here:
/app/.apt/usr/include
/app/.apt/usr/include/x86_64-linux-gnu
/usr/include/c++/4.8
/usr/include/x86_64-linux-gnu/c++/4.8
/usr/include/c++/4.8/backward
/usr/lib/gcc/x86_64-linux-gnu/4.8/include
/usr/local/include
/usr/lib/gcc/x86_64-linux-gnu/4.8/include-fixed
/usr/include
End of search list.

But I'm not a C++ programmer and cannot find what is wrong. Any ideas?



via Chebli Mohamed

Can I convert bool in model to yes/no in a QComboBox

I have a database with a column value 0/1.

I use QSqlRelationalTableModel for showing data to widget.

Is it possible to show Yes for 1 and No for 0 in a QComoboBox? And also, when I select yes/no, it should save to DB as 1/0.

Can I do something with setData() and getData() functions? Could someone give a clue how to start?

UPDATE:

    mpCountryModel->setTable("CountryMaster");
    mpCountryModel->select();

    ui->comboBox->setModel(mpCountryModel);
    ui->comboBox->setModelColumn(5);

As in column 5 has value 0 or 1, the same will display 0 and 1, right?



via Chebli Mohamed

Using Qt’s signals and slots when the same signal can come from multiple places

Qt’s signal and slot mechanism works fine when you have events that occur in one component and need to be handled by one or more other components.

My situation is that an event can occur in either of two classes and it needs to be handled by each of those classes (as well as by a couple of others). For example, suppose that I’m writing a modal text editor. The mode can be changed by the user (by pressing a button on a toolbar) or by the application (when a new file is opened). I might have

// Toolbar.h

signals:
    void user_changed_mode(EditingMode new_mode);
    // connected to AppController::user_changed_mode

public slots:
    void mode_changed(EditingMode new_mode);

// AppController.h

signals:
    void mode_changed(EditingMode new_mode);
    // connected to Toolbar::mode_changed

public slots:
    void user_changed_mode(EditingMode new_mode);

It just seems awkward to me to have two signals that convey the same information but which have different names (and likewise for the slots). Is there a simple way to use the signals and slots mechanism when the same event can originate from multiple places?



via Chebli Mohamed

Calling a function with a same name as a parent class function pointer

I'm trying to get a variety of Nodes to run a defined execute function that is passed in to a constructor and stored (and called) from a function pointer variable.

class Node{
    std::string(*execute)();
};

Node::Node(std::string(*funcPointer)()){
    execute = funcPointer;
}

I also have several derived classes that all also have an execute funcion

class redNode : public Node{
    std::string execute();
};

std::string redNode::execute(){
    return "I'm red";
}

class blueNode : public Node{
    std::string execute();
};

std::string blueNode::execute(){
    return "I'm red";
}

Then, I want to call all of the Node's execute functions.

std::string myFunc(){
     return "my Func";
}

Node mynode = new Node(&myFunc);
//other instantiations here...

myRedNode.execute();
myBlueNode.execute();
myNode.execute();

However, trying to call .execute() of myRedNode or myBlueNode doesn't work because the execute variable that's a part of the parent class was never set and it seems to be calling that. Trying to then set the execute variable

myBlueNode.execute = &BlueNode::execute;

gives a error C2659: '=' function as left operand, even when I rename the function I'm setting the variable to.

How do I solve this problem? How do correctly call function with a same name as a parent class function pointer?



via Chebli Mohamed

GCC/G++ Dockerfile builds locally; fails in Hub

I recently submitted this Dockerfile to the Hub

FROM ubuntu:14.04
MAINTAINER Jeyan Oorjitham <jeyoor@gmx.com>
RUN apt-get update && apt-get install -y \
   build-essential \
   cmake \
   git \
   libncurses-dev
RUN git clone http://ift.tt/1MqWxol
RUN ["/bin/bash", "-c",  "cd avida; ./build_avida"]
CMD ["/bin/bash"]

It is intended to build Avida from source.

The build succeeds locally, but when I receive the following error from the Docker Hub.

[91mc++: internal compiler error: Killed (program cc1plus)
[0m
[91mPlease submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-4.8/README.Bugs> for instructions.
...
Linking CXX executable ../../../bin/apto-test
...
Built target apto-test
[91mmake[1]: *** [avida-core/CMakeFiles/avida-core.dir/all] Error 2
[0m
[91mmake: [0m
[91m*** [all] Error 2

Full output

The build seems to be failing around the time it tries to link together the test executable for Apto.

Some Googling led me to this thread which seems to point to a lack of memory when linking large binaries...

Could memory be the problem or am I missing something else? Is there any way for me to increase the memory allocated to the Docker Hub build?



via Chebli Mohamed

Is there any performance difference between accessing a hardcode array and a run time initialization array?

For example, I want to create a square root table using array SQRT[i] to optimize a game, but I don't know if there is performance difference between the following initialization when accessing the value of SQRT[i]:

  1. Hardcode array

    int SQRT[]={0,1,1,1,2,2,2,2,2,3,3,.......255,255,255}
    
    
  2. Generate value at run time

    int SQRT[65536];
    int main(){
        for(int i=0;i<65536;i++){
            SQRT[i]=sqrt(i);
        }
        //other code
        return 0;
    }
    
    

Some example of accessing them:

    if(SQRT[a*a+b*b]>something)
    ...

At start, I thought they should be the same, but I don't know if the program stores or access a hard-code array in different way. Also, I don't know if compiler will optimize the hard-code array to speed up the access time, is there performance difference between them when accessing the array?



via Chebli Mohamed

Script for multiplying by 2 and checking for digits

I am trying to make a script with C++ that multiplies permutations of 123567890 (no 4) by 2, and checks if the number is a permutation of 1234567890. I have made a script, but it doesn't work. Please check the script and tell me how to fix it.

#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <random>
#include <chrono>
using namespace std;


int main() {
    int myints[] = { 5, 6, 7, 8, 9, 0, 1, 2, 3 };
    int two[] = { 1, 2, 3, 5, 6, 7, 8, 9, 0 };
    int num = 1;
    string numString;
    int numList[] = { 0 };
    int counter = 0;
    int mult = 0;
    int zero = 0;
    string numTemp;

    do {
        stringstream buffer;
        buffer << myints[0] << ' ' << myints[1] << ' ' << myints[2] << ' ' << myints[3] << ' ' << myints[4] << ' ' << myints[5] << ' ' << myints[6] << ' ' << myints[7] << ' ' << myints[8] << '\n';
        cout << buffer.str();

        numString = buffer.str();
        num = stoi(numString);

        if (zero = num % 2) {
            do {
                numList[counter] = (num / (10 ^ counter) % 10);
                counter += 1;
            } while (counter != 9);
            do {
                num *= 2;
                mult += 1;
                numTemp = to_string(num);
                if (numTemp.find(1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 != std::string::npos)) {
                    cout << "Success" << ' ' << num << " x2^" << mult;
                    return 0;
                }
            } while (num < 10000000000);
        }

    } while (std::next_permutation(myints, myints + 9));

    return 0;
}

Thank you for your assistance



via Chebli Mohamed

placement new on a different size class

So I came across placement new recently and had a question regarding it. I do understand that placement new is used when you want to allocate an object on an already allocated memory.

Lets say I have a class called foo, which is 20bytes.

I'd do some operations with it, and then I'll call a placement new for a class called bar, which is 10 bytes.

What happens to the last 10 bytes that is not part of the new object. Does placement new partition only the amount of memory required, which is in this case 10bytes? Or does the pointer just carry around the extra 10 bytes until it is deallocated.

And another case, lets say I've first started of by allocating memory for class bar, which is 10 bytes. I'll then placement new class foo, which is 20 bytes. Will the compiler allocate more memory? Or do I have to make sure to allocate enough memory beforehand?



via Chebli Mohamed

c++ double free or corruption error in destructor of a class derived from multiple classes

I am trying to write a multiple step abstract class like Plant is the top abstract class, Tree & Fruit are abstract classes derived from it. Oak is a normal class derived from Tree, Strawberry is also normal class derived from Fruit and Apple is a normal class derived from both Tree and Fruit.

While testing them with a simple main, I get this error. Here is my main.cpp:

int main(int argc, char const *argv[])
{
    long c = 500000;
    float d = 27.8;
    long e = 3000;

    Apple apple1("applecuk", 1, 39, 400, 0, 2, 3, c, d, e);
    apple1.bilgi();
    cout << "-------------------------------------------------" << endl;
    apple1.eat();
    apple1.info();
    apple1.cut();

    cout << "-------------------------------------------------" << endl;

    Oak oak1("oakcan", 1, 5, 1000, 2);
    oak1.info();
    oak1.cut();

    cout << "-------------------------------------------------" << endl;

    long a = 100000;
    float b = 14.3;
    Strawberry strw1("strwcik", 3, 2, 3, a, b);
    strw1.info();
    strw1.eat();

    cout << "-------------------------------------------------" << endl;

return 0;
}

At first everything is ok. Then, after the last ------ part, the program is starting to destruct the objects from last one (strawberry) to the first one (apple). But after strawberry, Fruit and Plant; it gives this error.

I think the next destructor is can't be called because, it is already destroyed. But I am not sure. How can I fix that?



via Chebli Mohamed

Vim with Ack: Search for all #pragma not ending in once

Using Ack in vim I want to find all instance of #pragma that does not end in once within c++ related files. What is the regex I need to use?

#pragma\s+.*(?<!once)$ works in python and javascript but not sure how to get ack to accept it.

:Ack --cpp #pragma\s+.*(?<!once)$ produces the following error in vim:

E194: No alternate file name to substitute for '#'

Escaping the # with \\\ returns nothing. I have tried a few other modifications, but not getting what I want.



via Chebli Mohamed

Error code 2556,2040

I keep getting error code error C2556: 'int myArray::operator const' : overloaded function differs only by return type from 'int &myArray::operator const'

see declaration of 'myArray::operator []'

error C2040: 'myArray::operator []' : 'int (int) const' differs in levels of indirection from 'int &(int) const'

This is my myArray .cpp file

#include <iostream>
#include "myArray.h"

using namespace std;

myArray::myArray(int newSize)
{
    startIndex=0;
    size = newSize;
    PtrArray = new int[size];
    for(int i=0; i< size; i++)
        PtrArray[i] = 0;
}

myArray::myArray(int newStartIndex, int newSize)
{
    startIndex = -newStartIndex;
    size = newSize;
    PtrArray= new int [size + startIndex];

    for(int i=0; i< (size + startIndex); i++)
        PtrArray[i]= 0;
}

myArray::~myArray()
{
    delete [] PtrArray;
}

int &myArray::operator[] (int index)
{
    if ((index <-startIndex || index >= size))
    {
        cerr<<"Error: Index "<<index<<" is our of range"<<endl;
        system("pause");
        exit(1);
    }

    return PtrArray[index+startIndex];
}

int myArray:: operator[](int index) const
{
    if (index <-startIndex || index >= size)
    {
        cerr<<"Error:Index"<< index<<"isout of range"<<endl;
            system("pause");
            exit(2);
    }

    return PtrArray[index + startIndex];
}

This is my program .cpp code

#include <iostream>
#include "myArray.h"

using namespace std;

int main()
{
    myArray list(5);
    myArray myList(2,13);
    myArray yourList(-5,9);

    for(int i=0; i<5; i++)
        list[i]=i*i;

    for(int j=2; j<13; j++)
        myList[j]=j*j;

    for(int k=-5; k<9; k++)
        yourList[k]=k*k;

    cout<<"The elements stored in the first object list are:"<<endl;

    for(int i=0; i<5; i++)
    {
        cout<<"list["<<i<<"[\t\t="<<list[i]<<endl;
    }

    cout<<"The elements stored in the second object myList are:"<<endl;

    for(int j=2; j<13; j++)
    {
        cout<<"myList["<<j<<"]\t="<<myList[j]<<endl;
    }

    cout<<"The elements stored in the third object yourList are:"<<endl;

    for (int k=-5;k<9;k++)
    {
        cout<<"yourList["<<k<<"]\t"<<yourList[k]<<endl;
    }

    cin>>yourList[-13];
    system("pause");
    return 0;
}

This is my myArray header:

#ifndef H_myArray
#define H_Array
#include <iostream>

using namespace std;

class myArray
{
public:
    myArray(int);
    myArray(int,int const);
    ~myArray();

    int &operator[](int);
    int &operator[](int) const;

private:
    int startIndex;
    int size;
    int *PtrArray;


};

#endif



via Chebli Mohamed

C++ Crash (Compiler?)

I have a very simple program I'm starting up, but when I try to run it, it gets to "has an initial population of" then crashes every time. For context, I am using visual studio 2015 on windows 10.

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

/*Ideas for features to add
*----------------------------
*Trade, agriculture, traffic, tourism, housing, crime rate, language, religion
*/

string version = "1.0";
void main() {
    cout << "Welcome to Population Simulator v" + version + ".\n";
    cout << "In this game we will simulate a city and how the population numbers change over time.\n";
    //City initialization 
    cout << "Please input a name for your city: ";
    string name;
    cin >> name;
    cout << "Please input an initial population of the city (Recommended: 10,000): ";
    int population = 0;
    cin >> population;
    int initialPopulation = population;
    int initialWealth = population * 10000;
    int wealth = initialWealth;
    int year = 2000;
    cout << name + " has an initial population of ";
    cout << population + " and an initial net-worth of $" + wealth;
    cout << ".\n";


}
int weather() {
    return 0;
}
int NPG() { //natural population growth
    return 0;
}



via Chebli Mohamed

"clang: error: linker command failed with exit code 1" on "ld: symbol(s) not found for architecture x86_64"

Right, please bare with on this, it might be quite a long one, and one related issue was solved here (I think): CMake make[2]: *** No rule to make target `/path/to/uthash/utarray.h', needed by `HelloTest'. Stop.

I have been struggling for some days now to build a simple 'Hello World' programme which mixes C and C++, and pulls in various external libraries using CMake. For full disclosure it should be known that I am fairly new to C, C++ and CMake hence please be nice.

I am working in OS X Yosemite 10.10.4 (my googling seems to suggest this might be part of the problem). I am working out of the CLion IDE.

Alas, here we go, here is the programme I am trying to build:

#include <iostream>
#include "Simbody.h" \\Written in C++
extern "C"
{
    #include "project_in_C.h"
}

using namespace std;
using namespace SimTK;

int main(int argc, char** argv) {
    cout << "Hello, World!" << endl;
    return 0;
}

We have a physics library written in C++ a bespoke project written in C, for which the main header file is, lets call it; project_in_C.h.

Again; all I am trying to do is build a simple mixed C/C++ project.

Now, the above is executed using CMake, and the following CMakeLists.txt file:

cmake_minimum_required(VERSION 3.2)
project(HelloTest)

# Simbody
find_package(Simbody REQUIRED)
include_directories(${Simbody_INCLUDE_DIR})
link_directories(${Simbody_LIB_DIR})

# Project C Headers
set(PROJC_ROOT_DIR "/Users/usr/project-c")
set(PROJC_INCLUDE_DIR ${PROJC_ROOT_DIR}/src
                      ${PROJC_ROOT_DIR}/dir1
                      ${PROJC_ROOT_DIR}/dir2)
include_directories(${PROJC_INCLUDE_DIR})

# Check that it has found the most important header
find_path(projFound project_in_C.h PATHS "/Users/usr/project-c/src")
if(NOT projFound)
  message(FATAL_ERROR "Cannot find folder containing project_in_C.h")
endif()

# Project C Source [we want to avoid globbing]
set(PROJC_SOURCE ${PROJC_ROOT_DIR}/src/file1.c
                 ${PROJC_ROOT_DIR}/src/file2.c
                 ${PROJC_ROOT_DIR}/src/file3.c
                 ${PROJC_ROOT_DIR}/src/file4.c
                 ${PROJC_ROOT_DIR}/dir1/file5.c)
# Make library from source files
add_library(PROJC_LIBRARIES ${PROJC_SOURCE})

# Tie together
set(SOURCE_FILES main.cpp)
add_executable(HelloTest ${SOURCE_FILES})
target_link_libraries(HelloTest ${Simbody_LIBRARIES} ${PROJC_LIBRARIES})

So far so good, but here is where the truly mysterious problem arises. Upon build this is what I get in return:

/Applications/http://ift.tt/1Itdw3K --build /Users/usr/Library/Caches/clion10/cmake/generated/c1d0f54d/c1d0f54d/Debug --target all -- -j 2
Scanning dependencies of target HelloTest
[ 91%] Built target PROJC_LIBRARIES
[100%] Building CXX object CMakeFiles/http://ift.tt/1h8dMOb
Linking CXX executable HelloTest
Undefined symbols for architecture x86_64:
  "_program_execution_wrapper", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [HelloTest] Error 1
make[1]: *** [CMakeFiles/HelloTest.dir/all] Error 2
make: *** [all] Error 2

But what the flippin' dynamite does that actually mean?

It is kicking up a fuss with project_in_C.h where the section the error seems to be referring to is written as so:

int program_execution_wrapper(int argc, char **argv);

int __program(int argc, char **argv);
#define main main(int argc, char **argv) { return prog_exec_wrap(argc, argv); } int __program

As ever, any help greatly appreciated.



via Chebli Mohamed

Does QComboBox::count() include separators in the count?

If I do:

QComboBox *cb = ...; 

cb->clear();
cb->addItem(...);
cb->insertSeparator(1);
cb->addItem(...);

Is cb->count() going to return 2 or 3?



via Chebli Mohamed

UWP/WinRT: How to perform a UI task upon completion of an asynchronous operation in a model?

I'm following the MVVM pattern, and have a model called a DocumentStore. The class has a method as follows:

void DocumentStore::Open_Document(StorageFile^ file) {
    create_task(FileIO::ReadTextAsync(file))
        .then([this, file](String^ fileContents)
    {
        // Take the fileContents and add them to internal data structure
    });
}

My ViewModel is popping up a FileOpenPicker to get a file that it then feed as the argument into Open_Document.

I'd like to be able to perform an action after the task inside of Open_Document has completed, i.e. after the fileContents have been processed.

Is there a way for my Model to notify any interested listeners that a task is complete?

Or should my Model's Open_Document method actually be itself asynchronous? However, I need to process the data structure inside the task, and wouldn't that cause my method to be running inside a different thread context?

I'm working in C++/CX but will take any help I can get.



via Chebli Mohamed

How to enforce that given resource will always be removed first? c++

In my project I have a system of events. You can connect callback to event and everytime somewhere in the code this event is sent your callback(s) are called.

Upon connecting to event you get a token. As long as it is not destroyed the connection is active:

class A
{

    A()
    {
        event_connection = get_dispatcher().connect(event, std::bind(member_function, this));
    }
    void member_function()
    {
        dummy_instance++; //any action that uses this field
    }
    // changed from shared to unique to avoid confusion
    //std::shared_ptr<event_connection_token> event_connection;
    std::unique_ptr<event_connection_token> event_connection;
    dummy_type dummy_instance;
}

Now the problematic scenario: 1. Deconstruction of object of class A starts. 2. Field dummy_instance is destroyed 3. Now event occures 4. Callback is called because event_connection wasnt destroyed yet. 5. Callback tries to access deallocated memory and program crashes.

Therefor I need my event_connection_token always destroyed before any class members that callback is using. Now if I want 100 other programmers to use this event-callback system it would be unprofessional to expect them to always deallocate event_connection_token first in all classes they ever make. We finally come to the question

Q: How can I enforce that every client removes event_connection_token before anything else in client class gets destroyed?

Im looking for either: ...a clever design that will always make sure token is removed first without programmers even thinking about it. or ... a compile time / run-time check that will let programmer know that he needs to modify code so that token is removed first.

EDIT. The "duplicated question" does not address my problem. I know the order of destruction of objects, or even explicitly calling .reset() in destructor will fix my problem. That is however not the solution to my problem. The problem is I don't want to rely that every developer in the project will remember about this rule (as this event-callback system is to be used in many places in the code).

Thanks for all your help Marcin



via Chebli Mohamed

C++ Linking an already created application(Win 32 console) with an already created static library

Basically, I need to connect my static library with my application. I've tried a few ways but none of them are working and I'm getting very frustrated. I'm using Visual Studio.



via Chebli Mohamed

Some basic algebra questions in C++ [on hold]

I have a problem here. I have two functions. One leads to x a(), the other to y, b(). I have y^2 in the functions to make it more apparent. They are reciprocal of each other. All I need is a couple lines, one, maybe two amd possibly three to complete my program. Ws won't change when it goes into T(). As you see I have it reassigning in the final for loop. Unfortunately it's not respecting me right now :-P. What am I missing that is stopping this from changing? It's a compression routine that holds digits in a smaller container, like the ladder in the garage paradox, the user doesn't see this unless he goes and looks at the compressed file. But maybe 100 characters can fit in a float number when going these functions. Please help me with my program. Thank you.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;

constexpr float a(float y) { return 2*y/1024; }
constexpr float b(float y) { return 1024*y/2; } 
constexpr int T(float x) {
  for (int y=0;y<=255;y++)
    if (b(x/(y*y))==x*a(y))
     return y;
  return 0;
}
int main() {
int l,i;
float Si[10] = { 30,10,20,15,35,47,18,3,5};
float Ts=0, Ts1=0, Ts4=0, Ws=1, W=0; 
int Ts2=0, Ts3=0;
for (i=1;i<=9;i++) {
  Ws=a(Si[i-1]*Si[i-1]*Ws);
  printf("%f == %f \n", Si[i-1],Ws);
}
printf("\n");
for (int i=9;i>=1;i--) {
  int x=T(Ws);
  Ws=b(Ws/(x*x)); // right here, *** why doesn't Ws change?
  printf("%d %f \n",x, Ws);

}
  return 0;
}



via Chebli Mohamed

How can implement dynamic function call with C++11 and C++14?

Here is code that I hope explains what I want to achieve.

vector<int> ints;
vector<double> doubles;


struct Arg {
  enum Type {
    Int,
    Double
  };

  Type type;
  int index;
};

template <typename F> 
void Call(const F& f, const vector<Arg>& args) {
  // TODO: 
  //  - First assert that count and types or arguments of <f> agree with <args>.
  //  - Call "f(args)"
}

// Example:

void copy(int a, double& b) {
  b = a;
}

int test() {
  Call(copy, {{Int, 3}, {Double, 2}}); // copy(ints[3], double[2]);
}

Can this be done in C++11 ?
If yes, can the solution be simplified in C++14 ?



via Chebli Mohamed

Depth buffer as texture - "D3D11 ERROR: The Format is invalid when creating a View"

I am trying to use depth buffer as an texture for second pass in my shader.

According to official documentation ("Reading the Depth-Stencil Buffer as a Texture" paragraph), I've set D3D11_TEXTURE2D_DESC.Format to DXGI_FORMAT_R32_TYPELESS:

D3D11_TEXTURE2D_DESC descDepth;
ZeroMemory(&descDepth, sizeof(descDepth));
descDepth.Width = width;
descDepth.Height = height;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = DXGI_FORMAT_R24G8_TYPELESS; //normally it was DXGI_FORMAT_D24_UNORM_S8_UINT
descDepth.SampleDesc.Count = antiAliasing.getCount();
descDepth.SampleDesc.Quality = antiAliasing.getQuality();
descDepth.Usage = D3D11_USAGE_DEFAULT;
descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;

ID3D11Texture2D* depthStencil = NULL;
result = device->CreateTexture2D(&descDepth, NULL, &depthStencil);

The results succeeded. Then I tried to create shader resource view for my buffer:

D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
//setup the description of the shader resource view
shaderResourceViewDesc.Format = DXGI_FORMAT_R32_FLOAT;
shaderResourceViewDesc.ViewDimension = antiAliasing.isOn() ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;
shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
shaderResourceViewDesc.Texture2D.MipLevels = 1;

//create the shader resource view.
device->CreateShaderResourceView(depthStencil, &shaderResourceViewDesc, &depthStencilShaderResourceView);

Unfortunately, that generates an error:

D3D11 ERROR: ID3D11Device::CreateShaderResourceView: The Format (0x29, R32_FLOAT) is invalid, when creating a View; it is not a fully qualified Format castable from the Format of the Resource (0x2c, R24G8_TYPELESS). [ STATE_CREATION ERROR #127: CREATESHADERRESOURCEVIEW_INVALIDFORMAT] D3D11 ERROR: ID3D11Device::CreateShaderResourceView: Returning E_INVALIDARG, meaning invalid parameters were passed. [ STATE_CREATION ERROR #131: CREATESHADERRESOURCEVIEW_INVALIDARG_RETURN]

I was also trying with DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_D24_UNORM_S8_UINT and DXGI_FORMAT_R8G8B8A8_UNORM as shaderResourceViewDesc.Format.

Where is the problem? I was following the documentation and I do not see it.



via Chebli Mohamed

pointer to class objects initialization with class constructor?

// pointer to classes example
// runs with no problem
#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};


int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << '\n';
  cout << "*foo's area: " << foo->area() << '\n';
  cout << "*bar's area: " << bar->area() << '\n';
  cout << "baz[0]'s area:" << baz[0].area() << '\n';
  cout << "baz[1]'s area:" << baz[1].area() << '\n';       
  delete bar;
  delete[] baz;
  return 0;
}   

I am a bit (no pun intended) confused about this line of code here:

baz = new Rectangle[2] {{2,5}, {3,6}};

I've seen code like:

int *foo = new int[3] {1,2,3};

and I totally understand it. But what's the syntax of {{2,5}, {3,6}} here? How can array of class objects be initialized like this? I've searched many online c++ references but have no clue.



via Chebli Mohamed

Why does my program crash in Visual Studio?

I am attempting to write a program for my programming course that demonstrates the use of inheritance. I build the program successfully and click start without debugging. The black box shows up normally. However the program crashes. The program should display all the variables within each of the different classes. Anyway, here is the code:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class Person{
protected:
    string name;
    string address;
    string city;
    string state;
    int zip;
    int phoneNumber;
public:
    Person(){
        name = "JohnDoe";
        address = "1234ExampleDrive";
        city = "Orlando";
        state = "Florida";
        zip = 12345;
        phoneNumber = 1234567890;
    }

    void display();
};

class Student: public Person{
private:
    string grade;
    string course;
    float gpa;
public:
    Student(){
        grade = 'A';
        course = "Algebra";
        gpa = 3.8;
    }

    void display();
};

void Person::display(){
    cout<<name<<endl;
    cout<<address<<endl;
    cout<<city<<endl;
    cout<<state<<endl;
    cout<<zip<<endl;
    cout<<phoneNumber<<endl;
}

void Student::display(){
    display();
    cout<<grade<<endl;
    cout<<course<<endl;
    cout<<gpa<<endl;
}



int _tmain(int argc, _TCHAR* argv[])
{
    Student student1;
    student1.display();
    return 0;
}

Any help would be greatly appreciated, thanks.



via Chebli Mohamed

error: ‘cbegin’ was not declared in this scope

I am currently facing a problem with this code:

auto first_open(std::find(cbegin(line), cend(line), '<'));

This is the overall code:

class DLNA
{
public:
    std::string IPAddress;

    auto createMap()
    {
        std::cout << "opening file" << std::endl;
        std::ifstream myfile("newcontent.xml");

        std::cout << "checking file state" << std::endl;
        if (myfile.is_open())
        {
            std::cout << "file is open" << std::endl;

            std::map<std::string, val_t> varmap;
            varmap["IPAddress"] = &IPAddress;

            std::cout << "reference assigned" << std::endl;

            std::vector<std::string> lines;
            while(myfile.good())
            {
                std::string line;
            getline(myfile,line, '\r');
                lines.push_back(line);
            }

            std::cout << "lines size is: " << lines.size() << std::endl;

            for(const std::string& line : lines)
            {
                std::cout << "reading line:" << std::endl << line << std::endl;
            if((line.find("<") != std::string::npos) && (line.find(">")!= std::string::npos)) 
                {
                   std::cout << "brackets found" << std::endl;
                    auto first_open(std::find(cbegin(line), cend(line), '<'));
                 }
               }
           }
        }

Basically, line is just a line from a xml file and will look something like this:

<IPAddress> 123.45.67 </IPAddress>

I am compiling this program like this:

c++ -I boost_1_59_0 anothertry.cpp -o variant -std=c++1y

Any reason why this isn't working?

Thanks.



via Chebli Mohamed

HDF5 C++ : I need get Group list, Dataset list, Attribute list in HDF5 file

I need get Group list, Dataset list, Attribute list in HDF5 file... but I dont know list get function.

What is the function to get the list?

My library is HDFGROUP - hdf5-1.8.14.

thanks



via Chebli Mohamed

Reducing virtually duplicate template instantiations

I have a (generated) set of classes that look roughly like this when simplified:

class A {
public:
    static const int id = 0;
    typedef int value_type;
    void* data; // actually pointer to int
};
class B {
public:
    static const int id = 1;
    typedef float value_type;
    void* data; // actually pointer to float
};

There are altogether tens of these, with much fewer types. I need to create classes that calculate some derived values for all of these. Now the obvious solution would be using a template like this:

template<class T>
class Derived {
public:
    typename T::value_type value;
    void update(const void* data) {
        value = *static_cast<typename T::value_type*>(data);
        // do some calculations
    }
};

But this is going to instantiate a separate class for every single parameter class A, B, and so on; most of which will be identical. The other solution would be an obvious template class like this:

template<typename T>
class Derived2 {
public:
    T value;
    void update(const void* data) {
        value = *static_cast<T*>(data);
    }
};

This would be updating the code using this class manually if the schema that classes A, B, etc., are generated from changes. Is there a way to use the value_type typedefs to generate instantiations of Derived2<int>, Derived2<float> etc., or at least match the types of manually parametrized instantiations to types A, B, etc.?

This is an embedded system, so the target is reducing the amount of identical code, even if it leads to more convoluted C++ code. Replacing the void*s with actual types would lead to code explosion in other parts of the program, so it is not done.



via Chebli Mohamed

int pointer as argument in function valgrind error Invalid read of size 4

What is wrong in this simple code? It works, but valgrind shows errors. How should it look like?

What should be definition of int func(int*)?

main.cpp:

#include <iostream>
#include <stdio.h>
#include <cstdlib>

using namespace std;

int func(int* terminal);

int main()
{
    int* x = (int*)malloc(3);
    x[0]=1;
    x[1]=2;
    x[2]=3;

    func(x);

}

int func(int *terminal)
{
    cout<<(*terminal)<<endl;
    cout<<(*terminal+1)<<endl;
    cout<<(*terminal+2)<<endl;

    return 1;
}

valgrind log:

==2806== Invalid write of size 4
==2806==    at 0x80486A6: main (main.cpp:12)
==2806==  Address 0x434f028 is 0 bytes inside a block of size 3 alloc'd
==2806==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806==    by 0x804869D: main (main.cpp:11)
==2806== 
==2806== Invalid write of size 4
==2806==    at 0x80486B3: main (main.cpp:13)
==2806==  Address 0x434f02c is 1 bytes after a block of size 3 alloc'd
==2806==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806==    by 0x804869D: main (main.cpp:11)
==2806== 
==2806== Invalid write of size 4
==2806==    at 0x80486C0: main (main.cpp:14)
==2806==  Address 0x434f030 is 5 bytes after a block of size 3 alloc'd
==2806==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806==    by 0x804869D: main (main.cpp:11)
==2806== 
==2806== Invalid read of size 4
==2806==    at 0x80486F1: func(int*) (main.cpp:22)
==2806==    by 0x80486D1: main (main.cpp:16)
==2806==  Address 0x434f028 is 0 bytes inside a block of size 3 alloc'd
==2806==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806==    by 0x804869D: main (main.cpp:11)
==2806== 
1
==2806== Invalid read of size 4
==2806==    at 0x804871A: func(int*) (main.cpp:23)
==2806==    by 0x80486D1: main (main.cpp:16)
==2806==  Address 0x434f028 is 0 bytes inside a block of size 3 alloc'd
==2806==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806==    by 0x804869D: main (main.cpp:11)
==2806== 
2
==2806== Invalid read of size 4
==2806==    at 0x8048746: func(int*) (main.cpp:24)
==2806==    by 0x80486D1: main (main.cpp:16)
==2806==  Address 0x434f028 is 0 bytes inside a block of size 3 alloc'd
==2806==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806==    by 0x804869D: main (main.cpp:11)
==2806== 

Maybe I should go fishing instead of studying c++.



via Chebli Mohamed

c++ malloc.c:2905: __libc_malloc: Assertion

I have follow error, I don't have any idea what is it and how I can it solve

malloc.c:2905: __libc_malloc: Assertion `!victim || ((((mchunkptr)((char*)(victim) - 2*(sizeof(size_t)))))->size & 0x2) || ar_ptr == (((((mchunkptr)((char*)(victim) - 2*(sizeof(size_t)))))->size & 0x4) ? ((heap_info *) ((unsigned long) (((mchunkptr)((char*)(victim) - 2*(sizeof(size_t))))) & ~((2 * (4 * 1024 * 1024 * sizeof(long))) - 1)))->ar_ptr : &main_arena)' failed.

need you help!

Thank you!



via Chebli Mohamed

I am doing a project in Java with Android jni C++. I have a function in C++ with the following parameters:

C++ function: void rectify (vector <Point2f> & corners, Mat & img) {...}

In JAVA, call would be:

Mat image = Highgui.imread("img.png");
List <MatOfPoint> cornners =  new ArrayList<MatOfPoint>();;
Point b = new Point (real_x2, real_y2);
MatOfPoint ma = new MatOfPoint (b);
cornners.add(ma);
rectfy(image.getNativeObjAddr(), cornners)

public native void rectfy(long mat, "??" matofpoint);

With that, I wonder how will the function C++ jni:

JNIEXPORT void JNICALL Java_ImageProcessingActivity_rectfy (JNIEnv * jobject, ?? cornners, inputMatAddress jlong)



via Chebli Mohamed

Unzip buffer with large data length is crashing

This is the function I am using to unzip buffer.

string unzipBuffer(size_t decryptedLength, unsigned char * decryptedData)
{
    z_stream stream;
    stream.zalloc = Z_NULL;
    stream.zfree = Z_NULL;
    stream.avail_in = decryptedLength;
    stream.next_in = (Bytef *)decryptedData;
    stream.total_out = 0;
    stream.avail_out = 0;
    size_t dataLength = decryptedLength* 1.5;
    char c[dataLength];

    if (inflateInit2(&stream, 47) == Z_OK)
    {
        int status = Z_OK;
        while (status == Z_OK)
        {
            if (stream.total_out >= dataLength)
            {
                dataLength += decryptedLength * 0.5;
            }

            stream.next_out = (Bytef *)c + stream.total_out;

            stream.avail_out = (uint)(dataLength - stream.total_out);

            status = inflate (&stream, Z_SYNC_FLUSH);

        }
        if (inflateEnd(&stream) == Z_OK)
        {
            if (status == Z_STREAM_END)
            {
                dataLength = stream.total_out;
            }
        }
    }
    std::string decryptedContentStr(c, c + dataLength);
    return decryptedContentStr;
}

And it was working fine until today when I realized that it crashes with large data buffer (Ex: decryptedLength: 342792) on this line:

status = inflate (&stream, Z_SYNC_FLUSH);

after one or two iterations. Can anyone help me please?



via Chebli Mohamed

which is the best for GUI C++ Qt or C# or JAVA 2015 [on hold]

hi i want to ask you a question i had learn c++ and something about the framework Qt but the problem that now day the Qt is not used in the world of apps smartphone like C# or JAVA !! so do u leave c++ and Qt and start with C# or JAVA ?? please i need your Advice Thank you



via Chebli Mohamed

Sort a data structure and keep record of the original indices

Suppose I have code such as the following, to sort elements of a data structure in another data structure, but keep a record of their original indices:

std::vector<int> numbers = {..};
std::vector<std::pair<int, std::vector<int>::size_type>> temp;

for (std::vector<int>::size_type i = 0; i < numbers.size(); i++)
{
    temp.push_back({ numbers[i], i });
}

std::sort(temp.begin(), temp.end(), [](const auto& x, const auto& y) { return x.first < y.first; });

So far so good. But what I really want is to store the data and indices in different data structures:

std::vector<int> sorted;
std::vector<std::vector<int>::size_type> indices;

Such that the element at sorted[i] was at index indices[i] in the original data structure.

Other than rolling out my own sorting algorithm, or splitting the data structure after the fact, is there any easy trick using the standard library to do this?



via Chebli Mohamed

Referring to an object of a derived class from the base class of another (unrelated!) class in C++

If you can't understand the question title from the onset, it's not your fault - I couldn't think of a better description. Here is the explanation of the problem, which might be a bit lengthy, so apologies in advance.

In the initial version of my program, I had an Ecosystem class and an Individual class:

// Very simplified, for illustration purposes

class Ecosystem
{
    protected:
        // The int is just the ID of the individual.
        std::map<int, std::shared_ptr<Individual> > individuals;

    public:
        Ecosystem();
        void func(int _individual_id)
        {
            std::cout << "Individual's age: " 
                      << individuals[_individual_id]->get_age() 
                      << std::endl;
        }

        void routine(int _individual_id)
        {
            // Another function working via
            // the pointers in individuals.
        }        

        // More such functions...
};

class Individual
{
    protected:
        int age;

    public:
        Individual();
        inline int get_age() const
        {
            return age;
        }
};

The Ecosystem class contains dozens of functions, and I will add a lot more in the future.

I have now decided to split the Individual class into a base class and two derived classes, say TypeAIndividual and TypeBIndividual, because they each have members and attributes that the other one does not need (they also share a few members and attributes via the base class). So I have the base Individual class and two derived classes:

class TypeAIndividual : public Individual
{
    protected:
        // Data structures specific to individuals of type A

    public:
        TypeAIndividual();
};

class TypeBIndividual : public Individual
{
    protected:
        // Data structures specific to individuals of type B

    public:
        TypeBIndividual();
};

The problem is that the ecosystem now also needs to be split into TypeAEcosystem and TypeBEcosystem:

class Ecosystem
{
    protected:
        // Holding pointers to the base Individual class is pointless (pun not intended)
        // std::map<int, std::shared_ptr<Individual> > individuals;

    public:
        Ecosystem();
        // I want to keep func() in the base class
        // because it only accesses attributes and
        // members common to both classes derived
        // from Individual. 
        void func(int _individual_id)
        {
            // Hmmmm...
            // The pointers don't live in the Ecosystem class any more!
            std::cout << "Individual's age: " 
                      << individuals[_individual_id]->get_age() 
                      << std::endl; 
        }
        // OK to implement in each class
        // derived from Ecosystem.
        virtual void routine(int _individual_id) = 0;
};

class TypeAEcosystem : public Ecosystem
{    
    protected:
        // Pointers to individuals
        // of the corresponding type.
        std::map<int, std::shared_ptr<TypeAIndividual> > individuals;

    public:
        TypeAEcosystem();
        // Reimplementing routine() is OK
        // because it does things specific to
        // this individual type.
        virtual void routine (int _individual_id)
        {
            // Operate on data structures particular
            // to this type of individual.
        }

};

class TypeBEcosystem : public Ecosystem
{
    protected:
        // Pointers to individuals
        // of the corresponding type.
        std::map<int, std::shared_ptr<TypeBIndividual> > individuals;

    public:
        TypeBEcosystem();
        // Reimplementing routine() is OK
        // because it does things specific to
        // this individual type.
        virtual void routine (int _individual_id)
        {
            // Operate on data structures particular
            // to this type of individual.
        }
};

TypeAEcosystem and TypeBEcosystem both use void func(int _individual_id), which needs to access individuals of the corresponding type. But the base class Ecosystem doesn't contain pointers to individuals any more because the std::maps are in each derived class and not in the base class.

My question is: how can I access the appropriate type of individual (TypeAIndividual or TypeBIndividual) while avoiding implementing separate void func(int _individual_id) in each class derived from Ecosystem? In other words, is there a way to keep func() in the base class so that when I change it, I don't have to make changes to the derived classes? In the actual program, there are dozens of functions like func() which take just an int as a parameter. Also, some of those functions take individual IDs from other structures in the Ecosystem class, so I can't simply pass a pointer to TypeAIndividual or TypeBIndividual.

Things I have considered

  • Merging TypeAIndividual and TypeBIndividual back into a common Individual class with all the data structures necessary for both derived classes. This strikes me as a particularly clumsy way of doing things, but at least it will work.

  • Making func() & Co. virtual and implementing them in TypeAEcosystem and TypeBEcosystem. This means that if I want to make a change in any of the functions, I have to change both implementations (= a maintenance nightmare).

  • Having only one Ecosystem class which holds std::maps of the two types of individuals, like this:

    // Seems clunky...
    class Ecosystem
    {
        protected:
            // Note: The Ecosystem can contain 
            // one OR the other, but not both!
            // One map will always be empty.
        std::map<int, std::shared_ptr<TypeAIndividual> > type_a_individuals;
    
        std::map<int, std::shared_ptr<TypeBIndividual> > type_b_individuals;
    
        public:
            Ecosystem();
            void func(int _individual_id)
            {
                // Check what type of individuals we 
                // are working with and operate on the
                // appropriate container.
                if (type_a_individuals.size() > 0)
                {
                    std::cout << "Individual's age: " 
                              << type_a_individuals[_individual_id]->get_age() 
                              << std::endl; 
                }
                else
                {
                    std::cout << "Individual's age: " 
                              << type_b_individuals[_individual_id]->get_age() 
                              << std::endl; 
                }
            }
    };
    
    

This would require inserting a check in every function, which is almost as bad in terms of maintainability as having the functions in separate classes.

Note: Although I would very much like to avoid passing pointers around, I would consider upcasting and/or downcasting as appropriate (as a last resort...) if it solves the problem.

Any suggestions are welcome!


Edit 1

Thank you all for the fantastic responses! As suggested by both amit and Chris, and looked at my Ecosystem class and sure enough, it was too bulky. I moved member functions around into other classes and now I'm down to four or five essential functions in the Ecosystem class. The Ecosystem class resides in a library and provides an interface for conducting experiments with individuals, but I don't want users to be able to manipulate Individuals and other classes directly, so I can't do away with it completely.

I liked all suggestions, there are some ingenious solutions. That being said, the one proposed by Chris grabbed my attention immediately for being very neat and allowing me to have a single Ecosystem class rather than three separate classes (base and two derived). The type of individual can be specified in a config file, and I can spawn multiple ecosystems from different config files within the same experiment. This is the accepted answer.

Thank you again everyone for the constructive input!



via Chebli Mohamed

How can I explicitly instantiate a variadic template so the template types are constructed and tied into one callable?

I've made use of interesting composition components like this one:

callable composition

And I've successfully used this in a context where I dynamically instantiate various objects, and call a virtual function on them getCallable() which returns a std::bind of to a member function. I then use the composition concept in the link above with the operator * to compose all of them into one callable. This works fine and with a single function call I get a long chain of member function calls to my objects. I'm trying to achieve something similar but at compile time when I know what my call chain should be (two object A's followed by a B, say). Something like this:

template <class T...>
struct CallChain
{
    static ?someComposedType? get();
};

I want to have a few variations of fully static const structs like this:

struct ArgStructX
{
    static const int x = 8;
    static const bool y = false;
    static const float z = 17.6;
};

And a few callable classes like this:

struct CallableX
{
    CallableX(const ArgStructX&);
    void operator()();
};

And then I want to be able to say something like this (for example):

template class CallChain<CallableX, ArgStructX, CallableY, ArgStructY>; //explicit instantiate in some C file

typedef template CallChain<CallableX, ArgStructX, CallableY, ArgStructY> MyChain;
auto F = MyChain::get();

What I'm trying to achieve at the last line above is for that to create a CallableX by passing it an ArgStructX, a CallableY by passing it an ArgStructY, and then internally compose them (as per the link above, for example) and give me back the final callable. So then if I said F() it would be CallableY(CallableX()). If done compile time, there should be no indirection (as opposed to my dynamic approach) in the final call chain. How could I go about this?



via Chebli Mohamed

gcc 4.8.4 "pragma GCC diagnostic not applied"

Using g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4

In a pre-compiled-header I have the following:

63 #pragma GCC diagnostic push
64 #pragma GCC diagnostic ignored "-Wunused-variable"
65 #include <boost/filesystem.hpp>
66 #pragma GCC diagnostic pop

Now when I go to run our build system I get the following build error:

from <>../../../../Core_Pch.h:65,
    from <command-line>:0:
<>/../../../../external/include/BoostBase/boost/system/error_code.hpp: At global scope:
<>/../../../../external/include/BoostBase/boost/system/error_code.hpp:221:36: error: ‘boost::system::posix_category’ defined but not used [-Werror=unused-variable]
     static const error_category &  posix_category = generic_category();

There appears to be a possible bug already opened in gcc's bug tracker http://ift.tt/1s26oWk. However, I am wondering if anyone has this working? The bug eludes to the fact that the behaviour of the preprocessor used by the c lexer works differently than that used by the c++ lexer.



via Chebli Mohamed

I need to read data from a serial device and put it into a buffer to be consumed by another thread. Basically, I want to achieve this:

while(!exit){
    // read from fd and push into the vector<char> buffer
}

And do it the right way in C++. I know how to get this done in C, and I'd really appreciate it if someone could point me in the right direction.

From what I've found so far, people have been suggesting:

read(fd, &vector[0], vector.size());

But, I'm not convinced. Especially since modifying the &vector[0] directly doesn't update size() (or does it?) and seems like an indirect way to modify the underlying array. I'd like to avoid using open() and read() as well, if I could help, as they aren't really C++. Some form of istream would be awesome here!

Also, I couldn't find any examples of how to neatly "pop" the data from this vector when the data needs to be consumed from the other thread. I believe, and I'm certainly not 100% sure about this, that if there's only one writer thread and one reader thread for this vector, I wouldn't need any special code for thread safety. Please correct me if I'm wrong.

If it matters at all, the data in the vector is binary.



via Chebli Mohamed

Why the variables defined inside a for loop only exist inside of it?

I was reading C++ Primer from Stanley B. Lippman and at the part of flow control it shows an example of a for-loop like this one:

#include <iostream>

int main(void){
    int sum=0;
    for (int val=1; val <= 10; val++)
        sum +=val;
    std::cout << sum << std::endl; 
    return 0;

}

If I try std::cout << val; outside of the for-loop, the IDE gives me an erro. But I want to understand why it happens and how it is different from this code:

#include <iostream>

int main(void){
    int sum=0;
    int val;
    for ( val=1; val <= 10; val++)
        sum +=val;
    std::cout << sum << std::endl;
    std::cout << val; 
    return 0;

}

Where I can actually print the val value without any problem.

Does it have something to do with local variable considering the for-loop a function that we are using inside of the main?



via Chebli Mohamed

Pure interface and Curiously Recursive Template Pattern

I am a beginner of C++. I have learned that Interface Class should not have implementation because of diamond inheritance problem(=multiple inheritance with a same ancestor class cause same name problem.) And pure Interface Class should have only other pure Interface classes. Well, please assume a base class takes the derived class as template parameter; that is, Curiously Recursive Template Pattern(CRTP). Now we don't have same name member problem in multiple inheritance. If so, do we have any problem with Interface class with CRTP? Or do we have any other problem with it? I might made big misunderstanding. Please tell me your answer. Thank you very much.



via Chebli Mohamed

C++ std::list segmentation fault on clear and begin

I'm having a Segmentation Fault when I call .begin() or .clear() on a std::list.

I'm working on a list which has a simple goal: to store some GUI elements that have to be freshened up.

The list is as follows:

list<ControllableUI*> uiToRefresh;

The functions acting on it are:

void SynthEngine::addUIToRefresh(ControllableUI* ui){
    uiToRefresh.push_back(ui);
}

void SynthEngine::removeUIToRefresh(ControllableUI* ui){
    list<ControllableUI*>::iterator i;

    for(i=uiToRefresh.begin(); i != uiToRefresh.end();){
        if((*i) == ui){
            i = uiToRefresh.erase(i);
        }
        else {
            ++i;
        }
    }
}

void SynthEngine::refreshUI(){
    list<ControllableUI*>::iterator i;

    for(i=uiToRefresh.begin(); i != uiToRefresh.end();){
        (*i)->refresh();
        i = uiToRefresh.erase(i);
    }
}

I'm calling removeUIToRefresh() whenever a UI component is deleted, to be sure it wont be called and start a segmentation fault, but it is this call that sends this error:

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffefb4a700 (LWP 24071)]
0x00000000004a948e in std::list::begin (this=0x45a8) at /usr/include/c++/4.9/bits/stl_list.h:772 772 { return iterator(this->_M_impl._M_node._M_next); }

Are there some obvious reasons that can throw a segmentation fault using lists?



via Chebli Mohamed

casting a SDL_PixelFormatEnum from 'unit32' to 'const SDL_PixelFormat'

I've been trying to wrap my head around the basics of SDL and I'm stomped by what should seem simple.

SDL_MapRGB() requires 'const SDL_PixelFormat*' and I use a SDL_PixelFormatEnum for creating textures in my project which is 'unit32' and I can't find any way of converting it for use with SDL_MapRGB().

There's probably a an easier way then using SDL_MapRGB() but this problem would still confuse me as you can easily convert it the other way.

Irrelevant but if you wish to know the rest of the code then their you go.

#include <SDL.h>

SDL_Window *sdlWindow;
SDL_Renderer *sdlRenderer;

int main( int argc, char *args[] )
{
    int w = 640;
    int h = 480;
    Uint32 format = SDL_PIXELFORMAT_RGB888;
    SDL_CreateWindowAndRenderer(w, h, 0, &sdlWindow, &sdlRenderer);
    SDL_Texture *sdlTexture = SDL_CreateTexture(sdlRenderer, format, SDL_TEXTUREACCESS_STREAMING, w, h);
    extern uint32_t *pixels;

    for (int x = 0; x < w; x++) {
        for (int y = 0; y < h; y++) {
            pixels[x + y * w] = SDL_MapRGB(format, 255, 255, 255);
        }
    }

    SDL_UpdateTexture(sdlTexture, NULL, pixels, 640 * sizeof (Uint32));
    SDL_RenderClear(sdlRenderer);
    SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);
    SDL_RenderPresent(sdlRenderer);
    SDL_Delay(5000);

    SDL_Quit();
    return 0;
}

before you say it, I know this just makes a white screen.



via Chebli Mohamed

Boost ASIO streambuf

I am confused about the input sequence and output sequence in boost asio::streambuf classes.

According to the code examples (for sending data) in the documentation it seems that the buffer representing the input sequence is used for writting to socket and the one representing the output sequence is used for reading.

Example -

boost::asio::streambuf b;
std::ostream os(&b);
os << "Hello, World!\n";
// try sending some data in input sequence
size_t n = sock.send(b.data());
b.consume(n); // sent data is removed from input sequence

Now, is there a nomenclature problem?



via Chebli Mohamed

Failed to find method id of isCacheAvailable on Vungle android because it cannot read Vungle library

I'm using sdkbox Vungle v1.2.0.1 with cocos2d-x v3.2. I successfully integrate Vungle and run it on iOS. I use method sdkbox::PluginVungle::isCacheAvailable() to check if vungle video is available or not. But it cannot run on android, the log says INF: Failed to find method id of isCacheAvailable. I think this issue happens because it cannot read the Vungle sdk library on android.

I've done everything according to Vungle integration document and my Android.mk like this:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

$(call import-add-path,$(LOCAL_PATH)/../../cocos2d)
$(call import-add-path,$(LOCAL_PATH)/../../cocos2d/external)
$(call import-add-path,$(LOCAL_PATH)/../../cocos2d/cocos)
$(call import-add-path,$(LOCAL_PATH)/../../cocos2d/extensions)
$(call import-add-path,$(LOCAL_PATH))

LOCAL_MODULE := cocos2dcpp_shared

LOCAL_MODULE_FILENAME := libcocos2dcpp

FILE_LIST := $(wildcard $(LOCAL_PATH)/../../Classes/*.cpp)

LOCAL_SRC_FILES := cpp/main.cpp \
                   cpp/ProjectUtilsAndroid.cpp
LOCAL_SRC_FILES += $(FILE_LIST:$(LOCAL_PATH)/%=%)

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \
                    $(LOCAL_PATH)/../../cocos2d/extensions \
                    $(LOCAL_PATH)/../../cocos2d/external/rapidjson \
                    $(LOCAL_PATH)/../../cocos2d/cocos/editor-support/spine \
                    $(LOCAL_PATH)/../../cocos2d/cocos/ui \
                    $(LOCAL_PATH)/../../cocos2d/cocos/network \

LOCAL_CFLAGS += -Wno-psabi -D CLASSIC
LOCAL_CPPFLAGS += -std=c++11

LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static 
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static 
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static 
LOCAL_WHOLE_STATIC_LIBRARIES += spine_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_ui_static 
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static 

LOCAL_STATIC_LIBRARIES += android_native_app_glue
LOCAL_LDLIBS += -landroid
LOCAL_LDLIBS += -llog
LOCAL_STATIC_LIBRARIES += PluginVungle
LOCAL_STATIC_LIBRARIES += sdkbox

include $(BUILD_SHARED_LIBRARY)
$(call import-module,cocos/ui)
$(call import-module,cocos/network)
$(call import-module,extensions)
$(call import-module,editor-support/cocosbuilder)
$(call import-module,editor-support/spine)
$(call import-module,sdkbox) 
$(call import-module,pluginvungle)
$(call import-module,.)

Could you please help me figure out exactly which part am I missing? Any help would be appreciated. Thanks.



via Chebli Mohamed

Image Stitching Opencv

In an effort to produce an image stitching program, I have used this tutorial in order to write the following program:

void stitchImages(Mat imageOne, Mat imageTwo) { 
    namedWindow("Result", WINDOW_AUTOSIZE);
    Mat firstImageDescriptors, secondImageDescriptors;

    Mat imageOneGray, imageTwoGray;
    
    cvtColor(imageOne, imageOneGray, CV_RGB2GRAY);
    cvtColor(imageTwo, imageTwoGray, CV_RGB2GRAY);

    cv::Ptr<Feature2D> featureDetector = xfeatures2d::SURF::create();
    
    vector <KeyPoint> firstImageKeyPoints, secondImageKeyPoints;
    cout << "About to detect" << endl;
//    featureDetector->detect(imageOneGray, firstImageKeyPoints);
  //  featureDetector->detect(imageTwoGray, secondImageKeyPoints);

    DescriptorExtractor descriptorExtractor;
    cout << "About to extract" << endl;
 //   descriptorExtractor.compute(imageOneGray, firstImageKeyPoints, firstImageDescriptors);
   // descriptorExtractor.compute(imageTwoGray, secondImageKeyPoints, secondImageDescriptors);

    featureDetector->detectAndCompute(imageOne, Mat(), firstImageKeyPoints, firstImageDescriptors, false);
    featureDetector->detectAndCompute(imageTwo, Mat(), secondImageKeyPoints, secondImageDescriptors, false);

    cout << "About to Flann it up" << endl;

    FlannBasedMatcher matcher;
    vector <DMatch> matches;
    matcher.match(firstImageDescriptors, secondImageDescriptors, matches);


       double max_dist = 0; double min_dist = 100;

    for(int i = 0; i < imageOneGray.rows; i++) {

        double dist = matches[i].distance;
        
        if(dist < min_dist) min_dist = dist;
        if(dist > max_dist) max_dist = dist;

    }

    vector<DMatch> good_matches;

    for(int j = 0; j < imageOneGray.rows; j++) {

        if(matches[j].distance < 4*min_dist)
            good_matches.push_back(matches[j]);

    }
 Mat img_matches;
//drawMatches(imageOne, firstImageKeyPoints, imageTwo, secondImageKeyPoints, good_matches, img_matches);
 //   imshow("Result", img_matches);
  //  waitKey(0);


    vector <Point2f> imageOnePoints;
    vector <Point2f> imageTwoPoints;

    for(int k = 0; k < good_matches.size(); k++) {

        imageOnePoints.push_back(firstImageKeyPoints[good_matches[k].queryIdx].pt);
        imageTwoPoints.push_back(secondImageKeyPoints[good_matches[k].trainIdx].pt);

    }
   
    Mat homographyMatrix = findHomography(imageOnePoints, imageTwoPoints, 8);

    Mat finalImage;
    warpPerspective(imageOne, finalImage, homographyMatrix, Size(imageOne.cols + imageTwo.cols, imageOne.rows));
    imshow("Result", finalImage);
    waitKey(0);
    Mat half(finalImage, Rect(0, 0, imageTwo.cols, imageTwo.rows));

    imageTwo.copyTo(half);

    

    imshow("Result", finalImage);
     waitKey(0);

    //set work_megapix
    //set work_scale

    }

(Please ignore the commented out code and notes to self)

I am using OpenCV 3.0 while this one uses a version of 2.0 to the best of my knowledge, so I had to change some things. I originally tried to stitch to images together, but the program failed. I was finding a decent amount of matches (I checked), but for some reason the transformation using the homography matrix I feel is the most likely culprit. I thought to myself, "this tutorials seems to be for panoramas without camera rotation, and the images I took are meant for a rotated panorama, so I might as well try taking some images where the camera does not rotate". I tried to do so and the results ended up with one image being copied to one half of the final pano and the other half of the pano being a gray smear. At least when I messed around with the rotated images, the first half of the image looked like a rotated version of the first image, yet the part that would have made it a panorama and not a copy of the second image's left part was cut-off, so I am not sure if it was just part of the second image (I feel it was probably legitimately part of the first). I am sorry I cannot post images, the image files for the final panoramas are too big. Any help would be much appreciated though. Thank you,

                                             - Jacob

P.S. I had to insert my code as a javascript/css/html code snippet so it would format correctly, but it obviously won't run in the browser so don't try! Also, I know I have two imshows that are not commented out at the end. I have two to see the final image looks before and after the "second image" is copied to the panorama.



via Chebli Mohamed

C++: boost::asio : what's the maximum buffer size I can use for tcp sockets?

In this ssl client example, the default buffer size is 1K=1024 bytes. Are there any practical limitations on how much I could increase that? Would it work fine with no unforeseeable problems if I set the buffer to something like a 100 MB?

Notice that the buffer is not just the reserved size... It is also passed to read() and write(). At what size would these functions face problems due to size limitations? Does such a limitation exist? I can imagine that there is at least a defined limit for how much I can write().



via Chebli Mohamed

How to render elevated tiles/objects in an isometric tilemap, without any conditions

This question pretty much sums up the problem:

I want my tilemap to be dynamic in height, like in many other well known games (Age of Empires, Rollercoaster Tycoon, ...)

My problem now is, that I am not quite sure how to draw elevated tiles (or large buildings and other tall objects), which base tile(s) are outside the view, without checking the y-position or any other condition, because that would slow down the program the bigger the map gets. (You can find a picture of such a scenario if you follow the first link to the other question.)

If those tiles/objects are not elevated, it's pretty easy to loop over the visible ones, without any conditions. You just need the view.

I already got some ideas, but they seem too complex and if they really work is another question. I also don't want to influence your solutions with my thoughts, thats why I just want to know which ways you think/know there are to implement elevated tile rendering without checking any conditions.



via Chebli Mohamed

malloc error in Eigen using g++4.9.3

This issue appears only on g++4.9.3. Consider the minimal code:

#include <iostream>
#include <Eigen/dense>

int main()
{
    Eigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(2,2);
    std::cout << mat << std::endl;
}

I compiled it with -Og and -D_GLIBCXX_DEBUG (I needed both of these flag to trigger the error):

g++ -Og -D_GLIBCXX_DEBUG -I./eigen minimal.cpp

Running the program results in:

a.out(42247,0x7fff7cf9e300) malloc: * error for object 0x10c6ca3d0: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug Abort trap: 6

Valgrind spits out something along the lines:

==42296== Invalid free() / delete / delete[] / realloc()
==42296==    at 0x10000B957: free (vg_replace_malloc.c:480)
==42296==    by 0x100038594: std::basic_stringbuf<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >::pbackfail(int) (in /opt/local/lib/libgcc/libstdc++.6.dylib)
==42296==    by 0x1048056C7: ???
==42296==    by 0x27: ???
==42296==    by 0x1048053E7: ???
==42296==    by 0x100038CA1: std::basic_stringbuf<char, std::char_traits<char>, std::allocator<char> >::overflow(int) (in /opt/local/lib/libgcc/libstdc++.6.dylib)
==42296==    by 0x672A2E24: ???
==42296==    by 0x1000033E7: ??? (in ./a.out)
==42296==  Address 0x1000033d0 is in the Data segment of ./a.out
==42296==
(1,0) (0,0)
(0,0) (1,0)
==42296==
==42296== HEAP SUMMARY:
==42296==     in use at exit: 111,830 bytes in 436 blocks
==42296==   total heap usage: 523 allocs, 91 frees, 124,150 bytes allocated
==42296==
==42296== LEAK SUMMARY:
==42296==    definitely lost: 0 bytes in 0 blocks
==42296==    indirectly lost: 0 bytes in 0 blocks
==42296==      possibly lost: 0 bytes in 0 blocks
==42296==    still reachable: 76,948 bytes in 5 blocks
==42296==         suppressed: 34,882 bytes in 431 blocks

I am not sure what's happening. Does anyone know if this is a g++ related issue or an Eigen issue? I am using the latest Eigen 3.2.5 and g++4.9.3 from MacPorts on OS X Yosemite.

PS: The error does not appear if I compile with clang or with g++5.



via Chebli Mohamed

C++ Boost Library Undefined Reference On shm_open: DSO Missing From Command Line

I am writing an application which is to play the role of a subscriber in a DDS system. This subscriber will, upon receipt of data, write the value(s) to a shared memory location so that they can be read by another GUI application.

I have written a version of the application which compiles and runs A-OK on Windows, but I am now faced with creating a version to be run on Ubuntu. Being Windows native, this has proved to be troublesome for me.

To create the Ubuntu version, I have ported my codebase to a Ubuntu VM, and am now trying to compile it there, which is where I'm running into issues.

For the most part, everything compiles fine and the process is wonderfully similar to that on Windows. Unfortunately, the final statement to link all of my generated .o files is what fails. A bit of a description is below:

I'm using the boost interprocess library to write a header file that will provide the shared memory read/write operations. The .cpp which achieves this is as below: MemWriterH.cpp

#define BOOST_DATE_TIME_NO_LIB
#define CPP

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <stdio.h>
#include <MemWriterH.h>

using namespace boost::interprocess;

extern "C" int writeToSharedMemory(char *data)
{
    //Remove shared memory on construction and destruction
    struct shm_remove
    {
        shm_remove()
        {
            //shared_memory_object::remove("MySharedMemory");
        }
        ~shm_remove()
        {
            //shared_memory_object::remove("MySharedMemory");
        }
    }remover;

    //Create a shared memory object.
    shared_memory_object shm(open_or_create, "MySharedMemory", read_write);
    //Set size
    shm.truncate(1000);

    //Map the whole shared memory in this process
    mapped_region region(shm, read_write);

    //Write given data to the mapped region
    //std::memset(region.get_address(), 'h', region.get_size());
    std::memcpy(region.get_address(), data, region.get_size());

    return 0;
}

extern "C" void readFromSharedMemeory(char toWriteIn[])
{
    //Open already created shared memory object.
    shared_memory_object shm(open_only, "MySharedMemory", read_only);

    //Map the whole shared memory in this process
    mapped_region region(shm, read_only);

    //Read data from shared memory into parameter
    //char *mem = static_cast<char*>(region.get_address());

    std::memcpy(toWriteIn, region.get_address(), region.get_size());
    printf("Read data OK");
    printf("\n%s", toWriteIn);
}

And its accompanying header: MemWriterH.h

#ifdef CPP
    extern "C" int writeToSharedMemory(char *);
    extern "C" void readFromSharedMemeory(char *);
#else
    int writeToSharedMemory( char *);
    void readFromSharedMemeory(char* toWriteIn);
#endif

These are then compiled to a .o file using:

g++ -c -I/$HOME/workspace_c/HID_LDM_DDS/HID_LDM_DDS_INCLUDES/MEM_MAPPING/ *.cpp

Inside the application's main file, I have a #include which allows the functions above to be used.

While there are various other elements to this application (as seen below), these all seem to compile, build, and link fine.

This resulting MemWriterH.o file is then used in a final GCC statement which — I believe — links all the .o files together to produce the application's executable. This final statement is:

gcc HID_LDM_DDS_SUB.o $HOME/workspace_c/HID_LDM_DDS/HID_LDM_DDS_HELPER/HID_LDM_DDS_HELPER.o $HOME/workspace_c/HID_LDM_DDS/HID_LDM_DDS_INCLUDES/CheckStatus.o $HOME/workspace_c/HID_LDM_DDS/HID_LDM_DDS_INCLUDES/MEM_MAPPING/MemWriterH.o $HOME/workspace_c/HID_LDM_DDS/HID_LDM_DDS_IDL/LDMSacDcps.o $HOME/workspace_c/HID_LDM_DDS/HID_LDM_DDS_IDL/LDMSplDcps.o $OSPL_HOME/lib/libddskernel.so $OSPL_HOME/lib/libdcpssac.so

which, unfortunately, gives me the error:

/usr/bin/ld: /home/bob/workspace_c/HID_LDM_DDS/HID_LDM_DDS_INCLUDES/MEM_MAPPING/MemWriterH.o: undefined reference to symbol 'shm_open@@GLIBC_2.2'

/lib/i386-linux-gnu/librt.so.1: error adding symbols: DSO missing from command line collect2: error: ld returned 1 exit status

At which point, I feel completely lost. The .cpp compiles to a .o without complaint, so I'm not quite sure where else to go from here. What is a DSO, and how do I add it to the command line?



via Chebli Mohamed

Cancel blocking `poll`?

So, I've run into this issue where I have many threads calling poll on different file descriptors. When I want to add a new one, I need to cancel one of those polls, add a new one, and continue. That alone sounds bad, but also I can't even see how to do that.

Some relevant code:

struct pollfd fds[size];
for(int i = 0;i<size;i++) {
    struct pollfd fd;
    fd.fd = body[i];
    fd.events = POLLIN;
    fd.revents = 0;
    fds[i] = fd;
}
if(poll(&fds[0], (nfds_t)size, -1) < 0) return NULL;

(I'm using this through JNI also).

I figure I could set a really low delay on poll, and call it over and over, but I think that would begin to defeat the purpose.



via Chebli Mohamed

How to write data into a buffer and write the buffer into a binary file with a second thread?

I am getting data from a sensor(camera) and writing the data into a binary file. The problem is it takes lot of space on the disk. So, I used the compression from boost (zlib) and the space reduced a lot! The problem is the compression process is slow and lots of data is missing.

So, I want to implement two threads, with one getting the data from the camera and writing the data into a buffer. The second thread will take the front data of the buffer and write it into the binary file. And in this case, all the data will be present.

How do I implement this buffer? It needs to expand dynamically and pop_front. Shall I use std::deque, or does something better already exist?



via Chebli Mohamed

Convert uint16 to uint32? [duplicate]

unsigned int32(unsigned int16, unsigned int16) {

} I have for example 16bit variable 0000 0000 1100 1111 and 0000 0000 1000 1001

I want to copy 1111 bits to new variable, then 1001. After that 1100 and 1000. I'm asking this because i need to combine 2x16bit variables to one 32bit, using low byte of first, then low byte of second, then high byte of first and high byte of second, all that need to be stored in that order to 32bit variable.

It has to be like this ...1000 1100 1001 1111 (uint 32bit)

This has to be done using bitwise operators (&, <<, >>, |, etc.)



via Chebli Mohamed

samedi 1 août 2015

How do i use an AutoPostback functionality for a radsearchbox?

By default, some of the telerik radcontrols are having autopostback option, but for radsearchbox, the auto postback functionality was not available, is it possible to achieve that in code?

Adding Security Header Username and password in API

Iam a Beginner in C#.Now iam working on one API on which iam facing one Exception

"Soap Exception :No security Header Found".

I just tried to add

CBANK.Service cService = new CBANK.Service();
cService.ClientCredentials.UserName.UserName = "username";
cService.ClientCredentials.UserName.Password= "Password";

but i cant find Clientcredentials in my service.My Webconfig settings is

<bindings>
        <customBinding>
            <binding name="ServiceComPortBinding" receiveTimeout="02:00:00" sendTimeout="02:00:00" openTimeout="02:00:00" closeTimeout="02:12:00">
                <transactionFlow transactionProtocol="WSAtomicTransactionOctober2004"/>
                <security defaultAlgorithmSuite="Basic128" authenticationMode="UserNameForCertificate" requireDerivedKeys="false" securityHeaderLayout="Strict" includeTimestamp="true" keyEntropyMode="CombinedEntropy" messageProtectionOrder="SignBeforeEncrypt" messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10" requireSignatureConfirmation="false">
                    <localClientSettings cacheCookies="true" detectReplays="true" replayCacheSize="900000" maxClockSkew="01:00:00" maxCookieCachingTime="Infinite" replayWindow="01:00:00" sessionKeyRenewalInterval="10:00:00" sessionKeyRolloverInterval="01:0:00" reconnectTransportOnFailure="true" timestampValidityDuration="01:00:00" cookieRenewalThresholdPercentage="60"/>
                    <localServiceSettings detectReplays="true" issuedCookieLifetime="10:00:00" maxStatefulNegotiations="128" replayCacheSize="900000" maxClockSkew="01:00:00" negotiationTimeout="01:00:00" replayWindow="01:01:00" inactivityTimeout="01:00:00" sessionKeyRenewalInterval="15:00:00" sessionKeyRolloverInterval="01:00:00" reconnectTransportOnFailure="true" maxPendingSessions="128" maxCachedCookies="10000" timestampValidityDuration="01:00:00"/>
                    <secureConversationBootstrap/>
                </security>
                <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Soap11WSAddressing10" writeEncoding="utf-8">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
                </textMessageEncoding>
                <httpTransport manualAddressing="false" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true">
                    <extendedProtectionPolicy policyEnforcement="Never"/>
                </httpTransport>
            </binding>
        </customBinding>
    </bindings>

can somebody help me to solve this issue.

show Jquery Form Validation message Next to bootsrap Textbox

i have a form implemented using Bootstrap and now validating form using jquery validate plugin. validations are working fine but i want to show validation messages next to textbox field but currently it is showing below to my text box

here is my html code :

<div class="form-group">
  <div class="col-md-2">
   <label for="forTypeName" class="control-label">Trainer Name</label>
  </div>
  <div class="col-md-10">
    <input type="text" class="form-control" id="txtname" name="txtname">
  </div>
</div>

and my JS Code is

   var validator = $("#sjform").validate({
            rules: {
                txtname: "required"

            },
            messages: {
                txtname: "Required"
            },
            errorPlacement: function (error, element) {
            //    error.appendTo($(element).parent().next());
            error.insertAfter(element);
            },

            //highlight: function (element) {
            //    $(element).closest('.form-group').addClass('has-error');
            //},
            //unhighlight: function (element) {
            //    $(element).closest('.form-group').removeClass('has-error');
            //},
            highlight: function (element) {
                $(element).parent().removeClass('has-success').addClass('has-error');
            },
            unhighlight: function (element) {
                $(element).parent().removeClass('has-error').addClass('has-success');
            },
            errorElement: 'span',
            errorClass: 'help-block',
            submitHandler: function (form) {
                form.submit();
            }
        });

devs any help please.. thanks in advance

Explain IIS caching and webapi requests

Who can explain the behavior IIS cache and webapi requests.

We have: 1. IIS 7 2. WebApi (Ap.Net Framework 4.5, MVC, C#). 3. IIS Settings: Site -> Output caching -> Edit Feature Settings: "Enable cache" and "Enable kernel cache" -- are enabled.

Current request:

POST http://ift.tt/1IAuPT2 HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=utf-8
Content-Length: 32

{language":"en"}

With every request throughout the day, response time increases. (request and query parameters always the same ) So: -first response on current request is 10ms. -after 100 request - 5 sec. -after 1000 requests to api -response will >10 sec

These numbers are approximate. I was made measurements every hour during the working day. And response time for current request every time was more than previous.

After I disabled "Enable cache" and "Enable kernel cache" in IIS site settings, response time became normal.

update panel in master page and asyncpostbacktrigger in content page

I have a cart in master page that this cart is inside update panel.
In my content page I have a listview that in this listview exist linkbutton for add product to my cart.
I want to add product to cart using these linkbuttons without refresh, and cart is updated. I have this code in my content page:
`protected void Page_Init(object sender, EventArgs e) { UpdatePanel up = (this.Master.Master.FindControl("UpCart")) as UpdatePanel;

    AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
    trigger.ControlID = lvNewProducts.UniqueID;
    trigger.EventName = "ItemCommand";
    up.Triggers.Add(trigger);



}`

but my page is refreshed when I click in linkbutton.
Please help me!