samedi 28 février 2015

Can I make a library from multiple targets?


I'm trying to learn cmake and have started converting an old make project over to cmake. Here is a simplified version of the directory structure I now have:



CMakeLists.txt
src/
CMakeLists.txt
main.cpp
core/
CMakeLists.txt
/sourcecode, other cmakes, etc.
test/
CMakeLists.txt
someTest.cpp


Currently, in my root CMakeLists.txt file I simply have this:



cmake_minimum_required(VERSION 2.8)
project(all)
add_subdirectory(src)
add_subdirectory(test)


What I wanted to do, was have a library created by core/CMakeLists.txt that can be used by both src/CMakeLists.txt to build the main executable, but also loaded by test/CMakeLists to build the unit tests.


So my src/core/CMakeLists.txt file currently looks sort of like this:



cmake_minimum_required(VERSION 2.8)

project(core)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wpedantic -Wreorder -DBOOST_TEST_DYN_LINK -DBOOST_LOG_DYN_LINK ")

#some other directories in my core code:
add_subdirectory(display)
add_subdirectory(training)
add_subdirectory(utility)

#some packages I use...
find_package(Boost 1.55.0
COMPONENTS
log
program_options
serialization
thread
system
filesystem
REQUIRED)

find_package(GLUT REQUIRED)
find_package(OpenGL REQUIRED)
find_package(Eigen3 REQUIRED)

include_directories(
${PROJECT_SOURCE_DIR}
${EIGEN3_INCLUDE_DIR})

target_link_libraries(core
display
training
utility
${Boost_LIBRARIES}
${OPENGL_LIBRARIES}
${GLUT_LIBRARY}
${OpenMP_LIBRARIES})


So the idea is that I now have a core target I can simply link against to run my tests, and everything should work. However, when I try to build main, for example, I get:



Cannot specify link libraries for target "core" which is not built by this
project.


I thought this might be because core doesn't have a add_library command, but if I add add_library(core) I get this error:



You have called ADD_LIBRARY for library core without any source files. This typically indicates a problem with your CMakeLists.txt file


But I don't want to add any source files; I just want this target to link the targets in the core directory and produce a target I can link against from test.


Clearly I'm missing some core knowledge here, either with cmake or the toolchain itself. Help is appreciated :)




C++ convert float to hex using only whole number math


I need to convert a whole number that should be considered a float into its hexadecimal equivalent.


For example:



Float To Hex


1 = 0x3f800000


2 = 0x40000000


12345 = 0x4640e400



It will always be whole numbers, never fractions such as 0.5. This could be done with memory assignment or a formatting function, but the situation its being used it, it has no memory access and no API calls at all.


I tried this idea, but it doesn't work at all http://ift.tt/1wyZvuW




CIN Taking Multiple Inputs


string one, two; cin>>one>>two;


I am using that code to take two inputs. Problem is that I want the second input to be optional. So when a user puts in inputs such as text1 without a second input and presses return the program should not expect another input from the user. Currently it is, and I need to press return on a blank line. Any way to achieve this scenario?


UPDATE: I was thinking of using a vector variable. Is there any way to capture all the input from the cin that way?




Calling C++ dll class from Visual Basic


So me and my friends have this project where I have a C++ class that needs to be called from Visual Basic. I've seen a few things about this but not much has helped. Does anybody know how to do this? I have a lot of experience in C++ but none in Visual Basic. My friends are the VB experts.


I am using visual studio but I also have gcc/g++ if that will be needed.




Merge two Mat-Objects in OpenCV


I wrote a little function in order to be able to "stick" the pixels of an image on top of another, but it somehow doesnt work: While the "shapes" of my "sticked" image is right, the colors are not. enter image description here


The example flower is the first image, and as a second image I had a black trapezoid png. As you can see, there are multiple problems: 1. The colors are shown weirdly. Actually there are no colors, just greyscale, and some weird stripes as overlay. 2. Alpha values are not respected. The white part of the overlay image is transparent in the png.


Here is my code:



void mergeMats(Mat mat1, Mat mat2, int x, int y){
//unsigned char * pixelPtr = (unsigned char *)mat2.data;
//unsigned char * pixelPtr2 = (unsigned char *)mat1.data;
//int cn = mat2.channels();
//int cn2 = mat2.channels();
//Scalar_<unsigned char> bgrPixel;

for (int i = 0; i < mat2.cols; i++){
for (int j = 0; j < mat2.rows; j++){
if (x + i < mat1.cols && y + j < mat1.rows){

Vec3b &intensity = mat1.at<Vec3b>(j+y, i+x);
Vec3b intensity2 = mat2.at<Vec3b>(j, i);
for (int k = 0; k < mat1.channels(); k++) {
intensity.val[k] = saturate_cast<uchar>(intensity2.val[k]);
}
//pixelPtr2[(i + x)*mat1.cols*cn2 + (j + y)*cn2 + 0] = pixelPtr[(i + x)*mat2.cols*cn + (j + y)*cn + 0];
//pixelPtr2[(i + x)*mat1.cols*cn2 + (j + y)*cn2 + 1] = pixelPtr[(i + x)*mat2.cols*cn + (j + y)*cn + 1];
//pixelPtr2[(i + x)*mat1.cols*cn2 + (j + y)*cn2 + 2] = pixelPtr[(i + x)*mat2.cols*cn + (j + y)*cn + 2];
}
}
}
}


The commented code was another approach, but had the same results. So, here are my questions: 1. How do I solve the 2 problems (1. the colors..., 2. alpha ...) 2. How is the pixel-array of any Mat-Object actually, well, organized? I guess it would be easier for me to manipulate those arrays if I knew whats in them.




I keep getting the error "The variable 'b' is being used without being initialized, and I'm not sure how to fix it



//Benjamin McKinney
//CSCI 2010-10
//Spring 2015
//PASS 3

//Programmed on Windows 8.1 using Visual C++ 2010 Express

//This program plays the game MasterMind

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

struct Player
{
string Name;
int HighScores[6];
bool CheatOn;
};

struct Board
{
int NumHoles;
int Holes[6];
};

struct Guess
{
int Count;
int NumHoles;
int Holes;
};

void printHighScores(string);
void readHighScore(string);
void updateHighScore(string, int);
string getPlayer();
int getBoard();
void playGame(string);
void menu(string);

int main()
{
Player p;
srand((unsigned int)time(0));

cout << "!!! Benjamin McKinney's Master-MasterMind!!!\n";
cout << "--------------------------------------------\n";

getPlayer();
menu(p.Name);

cout << "Goodbye, " << p.Name << endl;
printHighScores(p.Name);

cout << "----------------------------------------------\n";
cout << "!!! Benjamin McKinney's Master-MasterMind!!!\n";

system("PAUSE");
return 0;
}

void printHighScores(string name)
{
return;
}

void readHighScore(string)
{
return;
}

void updateHighScore(string, int)
{
return;
}

string getPlayer()
{
Player p;
cout << "What is your name?\n";
cin >> p.Name;
cout << "Welcome, " << p.Name << endl;
p.CheatOn = false;
readHighScore(p.Name);
return p.Name;
}

int getBoard()
{
Board b;

cout << "Enter the number of holes you would like: ";
cin >> b.NumHoles;

if(b.NumHoles > 6 || b.NumHoles < 1)
{
cout << "Error! You must pick a number between 1 and 6! Try again!\n";
}

for(int i=0;i<b.NumHoles;i++)
{
b.Holes[i] = rand() % 2 + 1;
}

return b.NumHoles;
}

void playGame(string)
{
Player p;
Board b;
Guess g;
getBoard();

g.Count=0;

for(int i=0;i<b.NumHoles;i++)
{
cout << "Enter your guess for the row\n";
if(p.CheatOn == true)
{
for(int a=0;a<(sizeof(b.Holes)-1);a++)
{
cout << b.Holes[a];
}
}
cout << "Enter your guess for hole " << i << ": ";
cin >> g.Holes;
g.Count++;
}

return;
}

void menu(string)
{
Player p;
char choice;

cout << "Please choose an option below:\n";
cout << "\t P)lay\n\t Q)uit\n\tChoice: ";
cin >> choice;

if(choice == 'P')
playGame(p.Name);
else
if(choice == 'Q')
return;
else`enter code here`
if(choice == 'C')
{
p.CheatOn = true;
playGame(p.Name);
}
}


Ignore the three HighScore functions, but otherwise I can't get this to work... "Run-Time Check Failure #3 - The variable 'b' is being used without being initialized." is the main issue that I'm having. If anyone can help me I would really appreciate it. Thanks!




system function on windows 7 failed with access denied error


I am writing a simple c++ app in visual studio 2012 on windows 7 wherein I am using the system command, strangely the system command fails with access denied error. For ex, I am trying to create a directory using system("mkdir C:\abc"), the command fails and the errno is set to EACCESS. Though I fail to create a new directory programmatically, I can very well create a new directory through the command prompt or through explorer. Also, the CreateDirectory Windows API works fine, it is the system function that is the issue - because no matter what command I pass to the system function, it fails with the same error EACCESS.


I have also noticed that this is machine specific, running the same program on a different machine is no issue.


Any ideas what could be going wrong on this unfortunate machine.


Things that I have already tried 1) Setting administrator privileges on the application 2) ran the system file checker - no problem detected 3) disable avast


Any help would be great. Thanks.




Calculate max even lengths of a string to be split


I know what I want but I have no idea if there's a technical name for this or how to go about calculating it.


Suppose I have a string:


ABCDEFGHI


This string can be split evenly into a "MAXIMUM" of 3 characters each sub-string.


Basically, I'm trying to find out how to split a string evenly into its maximum sub-lengths. A string of 25 characters can be evenly split into 5 parts consisting of 5 characters each. If I tried to split it into 4 or 6 pieces, I'd have an odd length string (a string with a size different from the others).



  • A string of 9 characters can be split into only 3 pieces of 3 characters each.

  • A string of 10 characters can be split into only 2 pieces of 5 characters each.

  • A string of 25 characters can be split into only 5 pieces of 5 characters each.

  • A string of 15 characters can be split into 3 pieces of 5 characters each OR 5 pieces of 3 characters each.

  • A string of 11 characters cannot be split because one string will always be larger than the other.


So how do I go about doing this? I've thought of using the square root but that doesn't work for a string of "10" characters. Works for 9 and 25 just fine.


Any ideas? Is there a technical name for such a thing? I thought of "Greatest Common Divisor", but I'm not so sure.




Python import_array makes it impossible to kill embedded python with ctrl-c


I'm trying to use Numpy in an embedded Python. I use Python 3.4 and boost::python with Boost 1.57. To prevent Python from setting a signal handler that would prevent me from kill my program with Ctrl+C, I use Py_InitializeEx(0).


Now the problem is, when I call import_array() to setup Numpy, this seems to add signal handlers and I'm not able to kill the program with Ctrl+C anymore.


Here is the sample program:



#include <boost/python.hpp>

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#define PY_ARRAY_UNIQUE_SYMBOL damaris_ARRAY_API
#include <numpy/arrayobject.h>

using namespace boost::python;

static void* init_numpy() {
import_array();
return NULL;
}

int main( int argc, char ** argv ) {
try {
Py_InitializeEx(0);

object main_module((
handle<>(borrowed(PyImport_AddModule("__main__")))));

object main_namespace = main_module.attr("__dict__");

init_numpy();

handle<> ignored(( PyRun_String( "print(\"Hello, World\")",
Py_file_input,
main_namespace.ptr(),
main_namespace.ptr() ) ));
while(1) {
sleep(1);
}
} catch( error_already_set ) {
PyErr_Print();
}
}


When commenting the "init_numpy" line in main, I can kill the program with Ctrl+C. How can I make it such that signals are not caught by Python while still using Numpy?




SDL2 + OpenGL crashing?


I followed a tutorial to set up SDL 2 with OpenGL, but when I ran the application, it immediately closed. I messed around with some values and found out that if I set the depth bits to 32, it works and stays open. Why would it support higher values but not lower values (like 16 and 24)? This is a problem, because I want my application to be able to run on other windows machines, but some only support 16 bit depth (I think?).



if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
return false;
}

SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); //Useless?
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

mainWindow = SDL_CreateWindow("OpenGL with SDL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, resolution.SCREEN_WIDTH, resolution.SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

if (!mainWindow) {
return false;
}

mainContext = SDL_GL_CreateContext(mainWindow);

SDL_GL_SetSwapInterval(1);


Can I at least automatically set it to something that is supported at runtime?


Edit


It also appears to work with 25-31.




C++ template for variable type declaration


I have a number of classes with differing members, all of which have operations of the following type



::basedata::Maindata maindata;
::basedata::Subdata subinfo("This goes into the subinfo vector");
subinfo.contexts(contextInfo);
maindata.subdata().push_back(subinfo);


Note that I am asking how to set up generalized templates to perform these actions. I cannot set up a special case for each type of maindata and subinfo. I also need to be able to see how to call the template from my main code. I have been able to set up a template if maindata.subdata() exists, but keep getting a compilation failure on a call to the template if it does not exist. That is create the template of the form



perform_Push(maindata.subdata(), subinfo);


so that it can be compiled whether or not maindata.subdata() exists or not.


I could accept templates that build so that the main code can show



bool retval
retval = hasmember(maindata, subdata);
if (retval)
{
buildmember(maindata.subdata, subinfo);
setAttributes(subinfo, data);
perform_Push(maindata.subdata(), subinfo)
}
else
{
// Perform alternate processing
}


As of now, the code inside the if would not compile when the templates being called should just be void.


While ::basedata::Maindata is always defined, ::basedata::Subdata may or may not be defined depending on the release of libraries that my code is being build with. subdata is defined as a vector belonging to maindata which therefore has the push_back() operation defined. There are too many types of subData to create a separate template for each type as T::Subdata within a template in any case.


That is, if subdata was the only case, I could create a specialization of the template T as ::maindata::subdata and a generic Template T.


I do not have any control of the include files or library that for this so that I cannot create a #define of a variable to test with the pre-compiler. Is there a good way of setting up a template that would allow this to work? I could use a template that returns a boolean true (success) or false (no such definition) and call the alternate processing at run time. I would not need to have an alternate template.


Basically, I am asking how to apply SFINAE to this particular situation.


I have managed to figure out what I need to do to set up the basic template


If I have the most basic operation



maindata.subdata().push_back(data)


I can define a template of the form,



<template class T, typename D>
auto doPush(D data) -> decltype(T.pushback(data), void())
{
T.push_back(data);
}


and the call would be



doPush<maindata.subdata()>(data);


However, the problem would be how to set it up when maindata does not yet have a member subdata.




C++ preprocessor test if class member exists


Is there an equivalent of #ifdef to test if a member exists in a class so that processing can be done without causing the code to fail the compiler. I have tried template operations but the particular problem has not succeeded.


For example



#if member baseclass.memberA()
baseclass.memberA().push_back(data);
#else
doAlternate(data);
#endif


Obviously the above is not valid, but I am trying to discover if something like this has been added to C++11


Note that in the initial setup, there will exist memberA, memberB, memberC, ... each of which will require the push_back. Other members will be added to the baseclass in the future, which is why I want to create a template so that all the cases will compile and process properly even if the current baseclass does not have some of the members (such as memberX). Otherwise, I can just put in the push_back() line with a very simple template.


This is actually the simplest case. There is also the case in which I create an instantiation of the subclass and then push it back into the subclass member.



// Instantiate an element of the Maindata class
::basedata::Maindata maindata;
//Instantiate an element of the Subdata class
::basedata::Subdata subinfo("This goes into the subinfo vector");
// Process some data that is part of the Subdata class
subinfo.contexts(contextInfo);
// Push the instantiated Subdata into the Subdata member of Maindata
maindata.subdata().push_back(subinfo);


Note that both Subdata and subdata() need to be set up so that the appropriate code is implemented. However, if ::basedata::Subdata exists then so will maindata.subdata().


I have already tried various methods using templates and the particular problem has not been solvable with the various answers received. Examples are template instantiation check for member existing in class, C++ class member check if not a template, C++ template for variable type declaration




Identify and correct the errors in the following code


This is a question from the book I am learning c++ from. It just says:


6.21- Identify and correct the errors int he following program:



void p(int i)

{
int i = 5;
cout << "i is " << i << endl;

}


I'm not sure what is wrong with this code. I think it probably has to do with the argument of p. When I try to build it in sublime text it says "error: redefinition of 'i'"


If it helps, we are learning about local, static and global variables.


Thanks!




Getting entire value from bitfields


I wish to create a Block struct for use in a voxel game I am building (just background context), however I have run into issues with my saving and loading.


I can either represent a block as a single Uint16 and shift the bits to get the different elements such as blockID and health, or I can use a bitfield such as the one below:



struct Block
{
Uint16 id : 8;
Uint16 health : 6;
Uint16 visible : 1;
Uint16 structural : 1;
}


With the first method, when I wish to save the Block data I can simply convert the value of the Uint16 into a hex value and write it to a file. With loading I can simply read and convert the number back, then go back to reading the individual bits with manual bit shifting.


My issue is that I cannot figure out how to get the whole value of the Uint16 I am using with the bitfields method, which means I cannot save the block data as a single hex value.


So, the question is how do I go about getting the actual single Uint16 stored inside my block struct that is made up from the different bit fields. If it is not possible then that is fine, as I have already stated my manual bit shifting approach works just fine. I just wanted to profile to see which method of storing and modifying data is faster really.


If I have missed out a key detail or there is any extra information you need to help me out here, by all means do ask.




CUDA SDK 6.5 - Samples/Common/inc/Helper_Math.h - Missing abs functionality


When I include Helper_Math.h file from the Samples/Commons directory and try to use abs(..) functionality, then I am getting compile errors.



phoad@phoad-ubuntu:~/development/obbcolgpu/build/obbcolgpu$ cmake --build .
[ 6%] Building CXX object CMakeFiles/http://ift.tt/1AVRSml
In file included from /home/phoad/development/obbcolgpu/src/../include/obbcol/Polynom.h:15:0,
from /home/phoad/development/obbcolgpu/src/../include/obbcol/RationalPolynom.h:4,
from /home/phoad/development/obbcolgpu/src/../include/obbcol/MotionMatrix.h:4,
from /home/phoad/development/obbcolgpu/src/MotionMatrix.cpp:1:
/usr/local/cuda-6.5/samples/common/inc/helper_math.h: In function ‘int2 abs(int2)’:
/usr/local/cuda-6.5/samples/common/inc/helper_math.h:1394:29: error: could not convert ‘v.int2::x’ from ‘int’ to ‘int2’
return make_int2(abs(v.x), abs(v.y));
^
/usr/local/cuda-6.5/samples/common/inc/helper_math.h:1394:39: error: could not convert ‘v.int2::y’ from ‘int’ to ‘int2’
return make_int2(abs(v.x), abs(v.y));
^
/usr/local/cuda-6.5/samples/common/inc/helper_math.h: In function ‘int3 abs(int3)’:
/usr/local/cuda-6.5/samples/common/inc/helper_math.h:1398:29: error: no matching function for call to ‘abs(int&)’
return make_int3(abs(v.x), abs(v.y), abs(v.z));


As seen, the library is unable to find "abs(int)" function.


I have manually updated the header to find the abs(int) function, but I am looking for a better solution..




Ambiguous base class conversion with a compressed pair


So I tried creating a compressed pair using the empty base optimization. I would like it such that if class a and b are empty then compressed_pair<a, b> is empty as well. So I defined my compressed pair something like this:



template <class First, class Second>
struct compressed_pair : First, Second
{
compressed_pair() {}
compressed_pair(const First& x, const Second & y)
: First(x), Second(y)
{}
First& first() { return *this; }
Second& second() { return *this; }
};


However, if one of the types inherit from the other it becomes ambiguous. For example, when I compile this program:



struct a
{};

struct b : a
{};

int main()
{
compressed_pair<a, b> p;
auto x = p.first();
}


I get this error from clang:



compressed_pair.cpp:8:30: error: ambiguous conversion from derived class 'compressed_pair<a, b>' to base class 'a':
struct compressed_pair<struct a, struct b> -> struct a
struct compressed_pair<struct a, struct b> -> struct b -> struct a
First& first() { return *this; }
^~~~~
compressed_pair.cpp:21:16: note: in instantiation of member function 'compressed_pair<a, b>::first' requested here
auto x = p.first();
^


So how can I avoid the ambiguous conversion and still have compressed_pair<a, b> be empty?




SHGetFolderPathW not working with japanese username


Im trying to create one file in %APPDATA% using SHGetFolderPathW function. This function I guess is getting chars in unicode. I'm working with Visual Studio 2010 little project. The following code work in english version of win 8 but not in japanese version (username is japanese):



#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <windows.h>
#include <Shlobj.h>
#include <tchar.h>
#include <string>



int _tmain(int argc, _TCHAR* argv[])
{
std::wstring output = L"";

WCHAR* folder = new WCHAR[2048];

SHGetFolderPathW(NULL, CSIDL_APPDATA,
NULL, SHGFP_TYPE_CURRENT, folder
);

std::wstring str1 = folder;
str1 += L"\\hola.txt";
std::wcout << str1 << std::endl;

std::string str(str1.begin(), str1.end());
std::cout << str << std::endl;

// Create file in folder
FILE * file;
char *path = new char[str.length()+1];
strcpy(path, str.c_str());
file = fopen (path, "w");
fputs ("Hello World",file);
fclose (file);

system("PAUSE");
return 0;
}


The code is showing good path in English version, but in japanese, this path isn't right. I wonder if I have any way to use SHGetFolderPath in all languages. I'm googling two days but not solution found.




What is the size of a socket send buffer in Windows?


Based on my understanding, each socket is associated with two buffers, a send buffer and a receive buffer, so when I call the send() function, what happens is that the data to send will be placed into the send buffer, and it is the responsibility of Windows now to send the content of this send buffer to the other end.


In a blocking socket, the send() function does not return until the entire data supplied to it has been placed into the send buffer.


So what is the size of the send buffer?


I performed the following test (sending 1 GB worth of data):



#include <stdio.h>

#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

#include <Windows.h>

int main()
{
// Initialize Winsock
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);

// Create socket
SOCKET s = socket(AF_INET, SOCK_STREAM, 0);

//----------------------

// Connect to 192.168.1.7:12345
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("192.168.1.7");
address.sin_port = htons(12345);
connect(s, (sockaddr*)&address, sizeof(address));

//----------------------

// Create 1 GB buffer ("AAAAAA...A")
char *buffer = new char[1073741824];
memset(buffer, 0x41, 1073741824);

// Send buffer
int i = send(s, buffer, 1073741824, 0);

printf("send() has returned\nReturn value: %d\nWSAGetLastError(): %d\n", i, WSAGetLastError());

//----------------------

getchar();
return 0;
}


Output:



send() has returned
Return value: 1073741824
WSAGetLastError(): 0


send() has returned immediately, does this means that the send buffer has a size of at least 1 GB?


This is some information about the test:



  • I am using a TCP blocking socket.

  • I have connected to a LAN machine.

  • Client Windows version: Windows 7 Ultimate 64-bit.

  • Server Windows version: Windows XP SP2 32-bit (installed on Virtual Box).




Edit: I have also attempted to connect to Google (173.194.116.18:80) and I got the same results.


Edit 2: I have discovered something strange, setting the send buffer to a value between 64 KB and 130 KB will make send() work as expected!



int send_buffer = 64 * 1024; // 64 KB
int send_buffer_sizeof = sizeof(int);
setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char*)send_buffer, send_buffer_sizeof);



How to derive from a variadic template class in C++


I have variadic template class which is just a wrapper for std::tuple :



template <typename ... Child>
class Tpl
{
public:
Tpl() {}
Tpl(Child ...args) : child(args...)
{}

template <typename T>
T& Get()
{
return std::get<T>(child);
}

template <typename T>
const T& GetConst()
{
return std::get<T>(child);
}
private:
std::tuple<Child ...> child;
};


How do I correctly derive a class from Tpl?



template <typename... Ts>
class SomeObject : public Tpl<Ts...>
{
public:
SomeObject(/*Types ... args*/) /*: child(args...)*/
{

}
private:
int num;
};


The compiler message just tells me:



syntax error: missing ',' before '<' in the line: class DbgGameObject : public Tpl<Ts...>



Segfault on accessing class type members


I'm trying to fix segfault error, and after 5 hours of trying different methods I can't find solution.


I have following class :



class CCharacter : public boost::enable_shared_from_this<CCharacter>//, private boost::noncopyable
{
public:
CCharacter(DWORD uid, std::string name, WORD level, BYTE job, BYTE face, WORD str, WORD agi, WORD vit, WORD dex, WORD ine, WORD status_points, float x, float y, WORD map_index, DWORD hp, DWORD mp, DWORD sp);
virtual ~CCharacter();

DWORD m_dwUID;

WORD m_btLevel;

BYTE m_btFace;

BYTE m_btJob;

WORD m_wStrength;
WORD m_wDexterity;
WORD m_wVitality;
WORD m_wAgility;
WORD m_wIntelligence;
WORD m_wStatusPoints;

float m_fltX, m_fltY;

WORD m_wMapIndex;

DWORD m_dwHealth;
DWORD m_dwMana;
DWORD m_dwStamina;

DWORD m_dwMaxHealth;
DWORD m_dwMaxMana;
DWORD m_dwMaxStamina;

DWORD m_dwAttack;
DWORD m_dwDefense;

std::map<DWORD, CItem*>& getEquipment()
{
return m_mapEquipedItems;
}

void setEquipment(std::map<DWORD, CItem*> val)
{
m_mapEquipedItems = val;
}

std::string getName()
{
return m_strName;
}

private:

std::string m_strName;

std::map<DWORD, CItem*> m_mapEquipedItems;


};


Every value is initialized in constructor by following way :



Character::CCharacter(DWORD uid, std::string name, WORD level, BYTE job, BYTE face, WORD str, WORD agi, WORD vit, WORD dex, WORD ine, WORD status_points, float x, float y, WORD map_index, DWORD hp, DWORD mp, DWORD sp) :
m_dwUID(uid), m_btLevel(level), m_btFace(face), m_btJob(job), m_wStrength(str), m_wDexterity(dex), m_wVitality(vit), m_wAgility(agi), m_wIntelligence(ine), m_wStatusPoints(status_points), m_fltX(x), m_fltY(y), m_wMapIndex(map_index),
m_dwHealth(hp), m_dwMana(mp), m_dwStamina(sp), m_strName(name), m_mapEquipedItems()


Character class is allocated from begining as shared_pointer and is stored in std container.


Problem occurs when i want use class-type memebers.


I receive SEGFAULT only when i use for example getName() method, or directly get m_strName if it is public.


Same with m_mapEquipedItems.


I use it in following context :



CPacket * generateCharacterPacket(std::vector<SPCHARACTER> characters)

{
CPacket * pkt = new CPacket(characters.size() * 653 + 11, 3, 4, true);

// result
pkt->setByte(0x01, 0);

// reason
pkt->setByte(0x01, 1);


...



DWORD counter = 0;

for(std::vector<SPCHARACTER>::iterator iter = characters.begin(); iter != characters.end();iter++)
{
pkt->write((*iter)->getName(), 3 + 653 * counter); // segfault

if((*iter)->m_btJob == 2)
{
pkt->write((BYTE)2, 40 + 3 + 653 * counter);
pkt->write((BYTE)2, 48 + 3 + 653 * counter);
}
else
{
pkt->write((BYTE)1, 40 + 3 + 653 * counter);
pkt->write((*iter)->m_btJob, 48 + 3 + 653 * counter);
}

pkt->write(std::string("0000000000000000"), 17 + 3 + 653 * counter);

pkt->write((BYTE)1, 34 + 3 + 653 * counter);
pkt->write((BYTE)(*iter)->m_btFace, 42 + 3 + 653 * counter);
pkt->write((BYTE)1, 44 + 3 + 653 * counter);
pkt->write((BYTE)2, 52 + 3 + 653 * counter);
pkt->setByte((unsigned BYTE)(*iter)->m_btLevel, 54 + 3 + 653 * counter);



pkt->write((float)(*iter)->m_fltX, 68 + 3 + 653 * counter);
pkt->write((float)(*iter)->m_fltY, 72 + 3 + 653 * counter);

pkt->write((DWORD)(*iter)->m_dwHealth, 56 + 3 + 653 * counter);
pkt->write((DWORD)(*iter)->m_dwMana, 60 + 3 + 653 * counter);

pkt->setWord((*iter)->m_wStrength, 576 + 3 + 653 * counter);
pkt->setWord((*iter)->m_wDexterity, 578 + 3 + 653 * counter);
pkt->setWord((*iter)->m_wVitality, 580 + 3 + 653 * counter);
pkt->setWord((*iter)->m_wAgility, 582 + 3 + 653 * counter);
pkt->setWord((*iter)->m_wIntelligence, 584 + 3 + 653 * counter);

std::map<DWORD, CItem*> equipment = (*iter)->getEquipment(); // SEGFAULT
std::map<DWORD, CItem*>::iterator iter2;

for(iter2 = equipment.begin(); iter2 != equipment.end();iter2++)
pkt->setDword(iter2->second->getItemData()->m_dwVnum, iter2->first * 12 + 116 + 3 + 653 * counter);


counter++;
}


return pkt;
}


Where is the problem ? DWORDS, WORDS are accessed without problem, but accessing any class type member provides segfault.




Coalesced memory access to 2d array with CUDA


I'm working on a piece of CUDA C++ code and need each thread to, essentially, access a 2D array in global memory by BOTH row-major AND column-major. Specifically, I need each thread-block to:



  • generate it's own 1-d array (let's say, gridDim # of elements)

  • Write these to global memory

  • Read the n-th element of each written array, where n is block ID.


The way I see it, only the write OR the read can be coalesced, and the other will be accessing a separate cache line for each element (and perform terribly). I've read that texture memory has a 2-d caching mechanism, but don't know if it can be used to improve this situation.


BTW I am using a GTX 770, so its a GK104 Kepler card with compute capability 3.0.


Any help or advice would be greatly appreciated! Thanks.




Is there a central repository of visual studio c++ widgets (components) like Torry.net for Delphi?


I have been spoiled with delphi because you can find almost any component (widget) you need at a central website called Torry.


Is there any central location to find all sorts of MFC or win32 gui components for Visual Studio? Or how about activex or com components? I do not mean .NET components or CLR components, but rather win32, mfc, activex, COM, etc. Where would people get their components for older versions of visual studio when there was no such thing as .NET or CLR widgets...? Even if there were .NET widgets available on some site, would`t there also be older components for mfc or win32 or com or activex in a subsection of the website? where are these central websites, or do they not exist?


The closest I could find was codeproject dot com which contains some code snippets and examples but they still do not offer a component repository like torry for delphi.


Since visual studio is more popular than delphi, it would make sense if there were more components and gui widgets available than for delphi. Where are they all located? Are they mostly scattered across different websites as activex controls, mfc controls, COM components, win32 examples, etc. available individually with no central widget repo?




Iterate on files of a folder, with specific condition


Using this solution with dirent.h, I'm trying to iterate on specific files of the current folder (those which have .wav extension and begin with 3 digits) with the following code :


(Important note: as I use MSVC++ 2010, it seems that I cannot use #include <regex>, and that I cannot use this as well because no C++11 support)



DIR *dir;
struct dirent *ent;
if ((dir = opendir (".")) != NULL) {
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
//if substr(ent->d_name, 0, 3) ... // what to do here to
// check if those 3 first char are digits?
// int i = susbtr(ent->d_name, 0, 3).strtoi(); // error here! how to parse
// the 3 first char (digits) as int?

// if susbtr(ent->d_name, strlen(ent->d_name)-3) != "wav" // ...

}
closedir (dir);
} else {
perror ("");
return EXIT_FAILURE;
}


How to perform these tests with MSVC++2010 in which C+11 support is not fully present?




HDF5 write to dataset one by one instance of data


I am wondering how can I write to HDF5 dataset not a whole array of object, but rather in a loop writing one by one? Because in my situation I would need to copy the data to a buffer, which as you can guess is big, that is why I am using HDF5.




how can a void function be called to the main, if there are no returns?


I wanted to create a function that retrieves all the information from previous functions within the same Class, and prints the values that were returned in the format of a bunch of cout statements, there is nothing for me to return in this PrintStatement() function, so I would create a void function, correct? My issue is in the int main(), I cannot cout a void function.


this is my account header file, and the function piece from my account.cpp file.



class Account {

public:
//Object constructor
Account(char firstName[], char lastName[], char sinNumber[], double balance, int accountType, int transactions);

//Object operations
double DepositAmt(double amount);
double WithdrawAmt(double amount);
void PrintStatement();
double getFinalBalance(double fbal);
string getAccountType();
double getTransactions (double Deposit, double Withdraw);

private:
//Object properties
char firstName[255];
char lastName[255];
char sinNumber[255];
double balance;
int accountType;
int transactions;
};


void Account::PrintStatement()
{

cout << "First Name: " << firstName << endl;
cout << "Last Name: " << lastName << endl;
cout << "SIN Number: " << sinNumber << endl;
cout << "Account Type: " << accountType << endl;
cout << "Final Balance: " << balance << endl;
cout << "Transactions: " << transactions << endl;


};


the global variables have already been initialized.


What I've tried:


I originally tried to cout << account.PrintStatement() << endl; however I get an error C2679 (binary '<<' : no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion)


I thought maybe changing things to apply to a string function instead would work, but instead I get a bunch of int conversion errors etc.


I'm unsure of what to do.


I am required to put these in a function just to be clear.


I tried using this question http://ift.tt/1DnkUJZ to help me, it made sense that the poster was using a reference, but I do not have that. Is there another way?




Is There a Standard Algorithm to Iterate Over a Range?


I need to call a lambda with every int in a range. Is there a standard algorithm that does this?


Ideally something equivalent:



for(auto i = 13; i < 42; ++i)[](int i){/*do something*/}(i);



Destructor/Constructor hotspot during CPU profiling?


I did a CPU profiling of my game ("ExampleGame") and I got some strange results:


profiling


For some reason in the top 5 the hotspots from my code is constructor and destructor of vectors. It is wierd considering the destructor has no side effects, and the constructor just initializes the members (all simple floats)


I had imagined matrix multiplication would be the definate hotspot, considering it is much more heavy.


I am running a debug build though. Is it some debug environment stuff causing this result?


The math library is GLM and the profiler is AMD Code XL




"Unable to start program The system cannot find the file specified" In Visual Studio 2013


Recently I've been getting this error in Visual Studio 2013 edition ever since I installed the glew and SDL 2.0.3 development libraries.


"Unable to start program 'C:\Users\Student\documents\visual studio 2013\Projects\Graphics\Debug\Graphics .exe'.


The system cannot find the file specified."


So obviously my program's .exe file is missing from the debug folder. It somehow deleted itself from the computer, and I even looked in my recycling bin, nothing there. I think it's also worth mentioning that I'm getting build errors as well.


I was learning from a tutorial on YouTube and didn't have this problem until this point of the video


http://ift.tt/1AHgkJ8


I followed all of his instructions in his previous tutorials and even installed SDL and glew exactly how he did, and for some reason this error pops up. Anyone know how to fix this?




How can I write a switch statement with strings in C++?


I'm working on a small project on Dev-C++. I'm trying to make a bot to ask you some questions, but I can't use the switch statetments with the strings. Every time I try to do so it shows error! I also tried to change the srings to normal int variables but when I the code runs all at once after answering the first question! Does anyone knows how to fix any of these situations?


Here is my code:



// #include "stdafx";

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

using namespace std;

int main()

{


string comida;

string nome;

string idade;

string pais;


cout << "Ola, o meu nome e Aleksandar. Qual e o teu nome?" << endl; //Ask for nome
cin >> nome; //Recieve variable nome


cout << "Es de que pais, " << nome << "?" << endl; //Ask for pais
cin >> pais; //Receive pais

cout << pais << " e um pais bonito. " << "Eu sou de Portugal!" << endl;


cout << "Quantos anos tens " << nome << "?" << endl; //Ask for idade
cin >> idade; //Receive variable idade

switch(idade){
case 21:
cout << "O meu irmao tambem tem " << idade << "!" << endl;

break;

}
cout << "Eu tenho 28" << endl;


cout << "Qual e a tua comida preferida?" << endl; //Ask for comida
cin >> comida; //Receive variable comida

cout << "Tambem gosto muito de " << comida << ". Mas gosto mesmo e de Vatruchka!" << endl;

cout << "Xau " << nome << "!" << endl;

return 0;


}



Clang -Wweak-vtables and pure abstract class


With regard to previous questions on this topic:


This a follow up of the question that I've asked recently: clang: no out-of-line virtual method definitions (pure abstract C++ class) and which was marked as duplicate of this question: What is the meaning of clang's -Wweak-vtables?. I don't think that that answered my question, so here I'm focusing on the very thing that puzzles me and that hasn't been answered yet.


My scenario:


I'm trying to compile the following simple C++ code using Clang-3.5:


test.h:



class A
{
public:
A();
virtual ~A() = 0;
};


test.cc



#include "test.h"

A::A() {;}
A::~A() {;}


The command that I use for compiling this (Linux, uname -r: 3.16.0-4-amd64):



$clang-3.5 -Wweak-vtables -std=c++11 -c test.cc


And the error that I get:



./test.h:1:7: warning: 'A' has no out-of-line virtual method definitions; its vtable will be emitted in every translation unit [-Wweak-vtables]


The above code builds fine, when class A is not pure abstract:


test2.h:



class A
{
public:
A();
virtual ~A();
};


test2.cc



#include "test2.h"

A::A() {;}
A::~A() {;}


My question


What's so special about pure abstract classes that the above code triggers warnings in Clang?




Pointer to pointer allocation then iteration causes segmentation fault


I'm having issues with the following code. I'm pretty sure it's correct. I'm trying to allocate memory to a pointer in a function, then write data to the allocated memory in that same function with a for loop. But when the counter reaches 2 on the for loop, it causes a segmentation fault, or I try to set a bunch of values in a loop or read from it.


Yes, I have researched this on StackOverflow, but I didn't find the following answers too helpful. * How can I allocate memory and return it (via a pointer-parameter) to the calling function?



#include <cassert>
#include <cstdlib>
#include <cstdio>

typedef unsigned char uint8_t;

void allocMem(uint8_t **i){
*i = new uint8_t[10];
for(int j = 0; j < 10; j++){
printf("%d\n", *i[j]);
//*i[j] = j * 2;
}
}

int main(){
uint8_t *i = 0;
allocMem(&i);
assert(i != NULL);
delete[] i;
}



Importing a list of files in a subdirectory into an array


I am working on a program which requires me to, at multiple points, import the contents of a subdirectory of my C++ Project, into a vector<string>. Assuming the project directory is called root\ and the directory I want to scan is root\userFiles. This folder only contains additional files and no further subfolders.


However the trick is I am restricted, I cannot use any of the boost, dirent.h header files. Just the basic ones.


One solution I was able to come up with was the use of the command system( "dir /b * > userFiles/fileList.txt" ); and then filter the results in by reading that file and importing it into the vector.


My issue is how do I "cd" to that folder, run that command while still in that folder, and then exit back to the root folder..


I have tried using the system("chdir userFiles/")command but I am still getting all the files in the root folder.


Any help would be appreciated.




Is C++ static same as static in C?


I am struggling with the static keyword in CPP.


After my experiments I found:



  1. static member is not inside the class. I calculated the size of the class before and after I add a static member, I found they are the same. One explanation that occurred to me is, perhaps the class name become the namespace (scope of this static member)? and that member is outside the class?

  2. Function is not inside the class, the have a implicit argument like the object pointer. however why the size of the class will be one but not 0 if there is no field inside the class but have a bunch of function? but is the pointer also give the function a scope that allow the function to access to the private member or the function its self have the class namespace.

  3. We could use both class name and object to access the static field and function, why we could do that. if the class name is the name space to the static function, why we could use an object to access it? is the object itself have the class namespace?

  4. Then i try to declare and define a static member inside class, and of course it fail, but i want to know why? why we could not initial it inside class?


XD English is not my mother language, sorry for my grammar mistake XD.




Boost Graphs. Equivalent technique to Inheritance


I am pretty new to Boost Graphs and perhaps there is a solution to my problem.


I have a function that performs certain computation on a graph. It expects graphs with a particular properties, e.g. it expects that all edges will have a numerical weight value and all vertices will have a numerical field (lets call it a color, it will be preset to some meaningful value prior to call to my function).


Imagine that I have a set of different graph types, all of them have numeric weight property on a link and all their vertices have a numeric color, however they also have other properties for vertices and edges. My question is how can I use my function for all of these graph types?



  1. Naturally to me it seems like an inheritance, if boost graphs would be classes then my function could operate on a base classes, and I could pass in pointer to a child classes etc.

  2. Initially I've been trying to declare my function to take in a template graph argument, but soon I realized that it doesn't work (or I couldn't figure out how to do it properly).


Thanks!




Converting single threaded program to multithreaded


I am doing a HW assignment (so please don't provide solution code) and I'm stuck on how to convert single threaded code to multithreaded code. I have written some code to solve my problem however I'm not sure how I can convert the code to a multithreaded program without access to the SlidingPuzzleState s member functions. I would appreciate a nudge in the right direction as I'm at loss as to how to split the work up among the threads ands do the work without access to the functions in the SlidingPuzzleState. I have the following code:



/** Worker Thread:
* Work queue: will send a starting location from which we do workSize work
* dataLock: a lock used when writing to the BFS data
* data: the depths for the BFS data
* seenStates: a counter to mark how many states have had their depths updated
* depth: the current depth in the BFS
*/
void WorkerThread(SharedLList<uint32_t> *workQueue, std::mutex *dataLock, uint8_t *data, uint32_t *seenStates, int depth)
{
//I need to implement this so I can send the work to the threads
}
void DoBFS(int numThreads)
{
std::cout << "Running with " << numThreads << " threads\n";
// By default, starts at goal state
SlidingPuzzleState s;
LList<int> moves;
SharedLList<uint32_t> workQueue;
std::mutex lock;
std::thread **threads = new std::thread*[numThreads];

uint8_t *stateDepths = new uint8_t[s.GetMaxRank()];

// set all values to 255
memset(stateDepths, 255, s.GetMaxRank());
uint32_t seenStates = 1;
stateDepths[s.Rank()] = 0;
int currDepth = 0;


std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed
std::cout.precision(2);

while (seenStates != s.GetMaxRank())
{


for (int x = 0; x < s.GetMaxRank(); x++)
{
if (stateDepths[x] == currDepth)
{
s.Unrank(x);
s.GetMoves(moves);
while (moves.IsEmpty() == false)
{
s.ApplyMove(moves.PeekFront());
uint32_t rank = s.Rank();
s.UndoMove(moves.PeekFront());
moves.RemoveFront();

if (stateDepths[rank] == 255)
{
stateDepths[rank] = currDepth+1;
seenStates++;
}
}
}
}
}


The code I have tried is (in the BFS while loop):



for (int i = 0; i < numThreads; i++)
{
threads[i] = new std::thread(WorkerThread, &workQueue, &lock, &stateDepths, currDepth);
}

for(int i = 0; i < s.GetMaxRank(); i++)
{
if (stateDepths[i] == currDepth)
{
workQueue.AddBack(i); //Without access to the ranking functions in my thread function I'm not sure how this is even useful to me.
}
}

for (int x = 0; x < numThreads; x++)
{
threads[x]->join();
delete threads[x];
}



Queueing of slots in QT


Couldn't seem to find an answer in the documentation, however I'm not entirely sure I was looking in the right places. I have a signal connected to a slot, for example with my QIODevice connect(port, SIGNAL(readyRead()), SLOT(handleReadyRead())); If the signal readyRead() is emitted twice in quick succession, say before the slot has finished processing, will the slot be called concurrently or queued and run one after the other?




Boost Graph accessing properties through vertex_descriptor


I have my custom vertex and edge properties



namespace boost {
enum vertex_diagonal_t{vertex_diagonal = 999};
BOOST_INSTALL_PROPERTY(vertex, diagonal);
}
namespace boost {
enum edge_dominance_t{edge_dominance = 998};
BOOST_INSTALL_PROPERTY(edge, dominance);
}


I create my adjacency list with boost::property



typedef boost::adjacency_list<
boost::listS,
boost::vecS,
boost::bidirectionalS,
boost::property<boost::vertex_diagonal_t, const khut::diagonal*>,
boost::property<boost::edge_dominance_t, float>
> diagonal_dominance_graph;
typedef boost::property_map<diagonal_dominance_graph, boost::vertex_diagonal_t>::type diagonal_map_type;
typedef boost::property_map<diagonal_dominance_graph, boost::edge_dominance_t>::type dominance_map_type;


Now I want to loop through my own containers and add vertex



diagonal_dominance_graph graph;
for(storage_type::const_iterator i = repo_begining.begin(); i != repo_begining.end(); ++i){
diagonal_dominance_graph::vertex_descriptor dia_vertex = boost::add_vertex(graph);

//>> ?? HOW CAN I write Properties to dia_vertex HERE ?

//boost::property<boost::vertex_diagonal_t, const khut::diagonal*> p;
//boost::put(p, dia_vertex);

}


What I am not getting is How can I set properties of a vertex through vertex_descriptor. may be I am missing a simple function.


Please I don't need anything that makes BGL even more complex, or something that cleans and restructures the types in my example. I just need to know how to read/write properties through a vertex_descriptor or edge_descriptor




How can I edit a value stored at an address through C++?


I need to be able to edit two regions of memory that are pointed to by two addresses stored in the ECX & EAX registers.


I'm doing this by placing a Code Cave in the clients original Executable that jumps to my Prepare_Encrypt() function.


My general idea is that Prepare_Encrypt() would get the addresses and should somehow be able to use them to create a pointer to the data in C++.


Once the pointer has been created I would create a For Loop that would preform an XOR operation on each character value in the pointer.


I'm new to using inline assembly so I would really like to get this working the way I want.


I figured creating a char* and using a MOV operation would work, but it doesn't. Does anyone have any ideas of how to get this to work?


Here is my current Prepare_Encrypt() function and my current Encrypt() function.



char* data_1;
char* data_2;

void Encrypt()
{
for(var i = 0; i < sizeof(data_1); i++)
{
data_1[i] ^= 200;
}

for(var i = 0; i < sizeof(data_2); i++)
{
data_2[i] ^= 125;
}
}

_declspec(naked) void Prepare_Encrypt()
{
// Save program state.
__asm
{
MOV ECX, ESI
MOV DWORD PTR SS : [ESP+0x1C], EAX
PUSHAD
PUSHFD

// Get Current Data From Memory
MOV data_1, ECX
MOV data_2, EAX
}

Encrypt();

// Restore the program state and return to original code.
__asm
{
POPFD
POPAD
JMP SendJMPTo
}
}



code that count first two prime number with difference of 100 in C++


Can anyone help me with this code please. I need a program that counts first two prime numbers with difference of 100 in C++ language Only using 'for' structure.


I mean a program that returns 2 prime numbers like x and y that x-y = 100.


Good luck




static function error LNK2001: unresolved external symbol "private: static int B::s_nValue" [duplicate]



This question already has an answer here:





#pragma once
class B
{
private:
static int s_nValue;

public:
B();
~B();

static int GetValue() { return s_nValue; }

static void SetValue(int value){ s_nValue = value; }

};

int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
B::SetValue(5);

std::cout << B::GetValue();

cin>> i;

return 0;
}


I'm trying to master the use of static functions. In this case, SetValue() and GetValue() are defined in class B. They are called without an object definition in main. This should work, but I'm getting an unresolved external symbol error 2001. The precompiled headers option is turned off.


How can I get rid of this error?


Using MS Visual Studio 2012




How to test MPI program


I have question about testing MPI program. I wrote FW algorithm with Open MPI. The program works fine and correct, but problem is that it takes more time than my sequential program (I have tried to test it on only one computer). Does someone have idea why that happens ? Thanks




std::find_if for custom objects returns bad iterator when vector has at least 1 element


So I have a vector of objects of type Player. If I try to use std::find_if on that vector and use a lambda expression that return true only if the name if the player is a name I want to check against, it will work the first time if the vector is empty (as in the iterator is nullptr), but once I add a Player object in the vector, the find_if will return an iterator filled with random, bad data.


My code:



auto player = find_if(m_playerList.begin(), m_playerList.end(), [name](Player& p)
{
return p.Name == name;
});

if (player._Ptr != nullptr)
{
// Do stuff
}

else
{
Player newPlayer;
newPlayer.Name = name;
m_playerList.push_back(newPlayer);
}


So in the first iteration of this function, the player is nullptr, because the vector didn't contain any elements. In the second iteration, if I search by the same name, it finds it in the vector, however if I search by a different name, it returns an object with mangled, random data and the check "if (player._Ptr != nullptr)" passes.


Question is, what causes this? Am I checking the "player" object properly to figure out if the find_if actually found a valid object in the vector?




Scope resolution :: vs this ->


I am trying to understand pointers and scope in OOP with C++. Is there any difference at all between:



class Class
{
public:
void setVal (int value) {
this -> value = value;
}
int getVal();
private:
int value;
};


and this:



class Class
{
public:
void setVal (int value) {
Class::value = value;
}
int getVal();
private:
int value;
};



Finding position of the element in array


How can I find position of the element inside an array? I have following piece of code where I need to test if the element is at some position, however it is not working as expected. I need your help about it.




Why won't _sleep(1000) compile in Xcode?


I have a program that is supposed to count down from 10 to 0, and every time it counts down it's supposed to wait one second then flush the output using cin.flush(). The professor demonstrated this in class and it worked perfectly, however, when I get home Xcode gives me an error saying that _sleep(1000) is the use of an undeclared identifier '_sleep' -- which is not supposed to be the case as I imported the special commands and it's only supposed to use _sleep in windows compilers.


In short, this needs to compile in both windows and mac compilers, which I am supposed to do by these compiler definitions. But for some reason Xcode keeps trying to tell me it's wrong.



#ifdef GPP
#include <unistd.h>
#else
#include <cstdlib>
#endif


int main()
{
for (int timer = 10; timer >= 0; timer--)
{
cout << timer;
cout.flush();

//compiler functions
#ifdef GPP
Sleep(1); //One second to sleep on GPP compilers
#else
_sleep(1000);//On windows 1000ms sleep time
#endif

cout << '\r';
}
}



Adding into unordered map containing vector value


Let's say I have an unordered map defined as this:



unordered_map<string, vector<Obj*>> map // I defined some Obj class


If I were to add an element into the map, I would have to do something like:



pair<string, vector<Obj*>> newEntry(myString, myVector);
map.insert(newEntry);


But I just want to add an element into the vector, what can I do? Do I have to pull out the vector and add to it before inserting it again? What is the best way to do this?




In Visual Studio C++ what is the equivalent of a delphi TPanel or alTop, alClient for organizing controls?


I am trying to figure out what people use in visual studio c++ to organize their controls and align them. In delphi a TPanel is used and there is alignment features which are extremely useful. In visual studio c++ is the only way to organize your controls by writing lots of code to resize everything at run time?


A TPanel in delphi allows you to align left, right, client, top, bottom, and put controls in it with the panel as the parent control. I can not figure out how one does this in visual c++ unless you write a lot of code which kind of defeats the purpose if a visual development environment.


I suppose visual studio is not RAD so you can not compare it directly to delphi, but how do people organize their controls on dialogs without writing a lot of code in visual studio... are there some third party controls out there that emulate delphis TPanel? And does visual studio c++ have a way of emulating delphi`s altop, alClient, alRight, etc. like seen in delphi TPanels?




why error when i have big input


if n is for example 1.000.000 compiler stops working. Why? Long int dont help.



#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <fstream>


using namespace std;


int main() { ofstream fout; ifstream fin;



fin.open("share.in");
fout.open("share.out");

int n;
fin>>n;
int array1[n];
for(int i=0; i<n; i++)
{
fin >> array1[i];
}


int suma=0, sumb=0, sumc=0, a=1, b=1, c=n-2, a1=0, b1=0, c1=0, apotelesma=1000000000, mikroterhdiafora=1000000000;

while(c>0)
{
while(a1<a)
{
suma+=array1[a1];
a1++;
}
while(b1<b)
{
sumb+=array1[(a1+b1)];
b1++;
}
while(c1<c)
{
sumc+=array1[(a1+b1+c1)];
c1++;
}



if(max(abs(suma-sumb),max(abs(sumb-sumc),abs(sumc-suma)))<=mikroterhdiafora)
{
mikroterhdiafora=min(mikroterhdiafora, max(abs(suma-sumb),max(abs(sumb-sumc),abs(sumc-suma))));
apotelesma=min(apotelesma, max(suma,max(sumb,sumc)));
}



suma=0;
sumb=0;
sumc=0;

a1=0;
b1=0;
c1=0;

c--;
b++;


if(c==0)
{
++a;
b=1;
c=n-a-1;
}
}


fout<<apotelesma;


fin.close();
fout.close();

return 0;
}



Unnecessary class redefinition for FLTK


For some reason, the MSVC compiler gives the numeric definition of Fl_Button in the FLTK header file 'Enumerations.h' more precedence than a class of the same name. The following code failed to compile:



Fl_Button *confirm = new Fl_Button(0,0, 200, 50, "Hello world"));


Although, I have solved the problem by casting Fl_Button to its inherited class:



class Fl_Button_t : Fl_Button {};
Fl_Button_t *confirm = (Fl_Button_t*)(new Fl_Button(0,0, 200, 50, "Hello world"));


Is there a better approach for sorting out this name clash in the FLTK headers?




Inserting any number of types into a pack of template arguments


InsertTypes<Pack, P<Ts...>, Is...>::type is Pack with the types Ts... inserted in positions Is..., respectively. For example,



InsertTypes<Pack<int, double, char, long, int>, Pack<short, float, std::string>, 2,4,1>::type,


is



Pack<int, std::string, double, short, char, long, float, int


(short inserted between double and char, float inserted between long and int, and std::string inserted between int and double).


My method: Sort the Is... in reverse order first (from largest to smallest), and apply Insert for each type in Ts... and each int in Is... Why reverse sort the Is...? Because if they are not in that order, inserting a type will bump the positions off by one and mess up the other insertions. But there is a flaw in my plan, which I'll explain shortly. First let me provide the helper functions I've written, which I tested to work correctly on their own:


Insert<T, P<Types...>, N>::type is the pack P<Types...> with T inserted in position N.



template <typename, typename, typename, int> struct InsertHelper;

template <typename T, template <typename...> class P, typename First, typename... Rest, typename... Accumulated>
struct InsertHelper<T, P<First, Rest...>, P<Accumulated...>, 0> {
using type = P<Accumulated..., T, First, Rest...>;
};

template <typename T, template <typename...> class P, typename First, typename... Rest, typename... Accumulated, int N>
struct InsertHelper<T, P<First, Rest...>, P<Accumulated...>, N> : InsertHelper<T, P<Rest...>, P<Accumulated..., First>, N-1> {};

template <typename, typename, int> struct Insert;

template <typename T, template <typename...> class P, typename... Types, int N>
struct Insert<T, P<Types...>, N> : InsertHelper<T, P<Types...>, P<>, N> {};


Now ReverseSortIntSequence (using quicksort):



template <int, typename> struct PrependInt;

template <int N, template <int...> class Z, int... Is>
struct PrependInt<N, Z<Is...>> {
using type = Z<N, Is...>;
};

template <template<int> class, typename> struct FilterInts;

template <template<int> class F, template <int...> class Z, int I, int... Is>
struct FilterInts<F, Z<I, Is...>> {
using type = typename std::conditional<F<I>::value,
typename PrependInt<I, typename FilterInts<F, Z<Is...>>::type>::type,
typename FilterInts<F, Z<Is...>>::type
>::type;
};

template <template<int> class F, template <int...> class Z>
struct FilterInts<F, Z<>> {
using type = Z<>;
};

template <typename, typename> struct MergeIntSequences;

template <template <int...> class Z, int... Is, int... Js>
struct MergeIntSequences<Z<Is...>, Z<Js...>> {
using type = Z<Is..., Js...>;
};

template <typename> struct ReverseSortIntSequence;

template <template <int...> class Z, int N, int... Is>
struct ReverseSortIntSequence<Z<N, Is...>> {
template<int I> struct less_than : std::integral_constant<bool, (I >= N)> {};
template <int I> struct more_than : std::integral_constant<bool, (I < N)> {};
using subsequence_less_than_N = typename FilterInts<less_than, Z<Is...>>::type;
using subsequence_more_than_N = typename FilterInts<more_than, Z<Is...>>::type;
using type = typename MergeIntSequences<typename ReverseSortIntSequence<subsequence_less_than_N>::type,
typename PrependInt<N, typename ReverseSortIntSequence<subsequence_more_than_N>::type>::type
>::type;
};

template<template <int...> class Z>
struct ReverseSortIntSequence<Z<>> {
using type = Z<>;
};


Now InsertTypes itself:



template <typename, typename, typename> struct InsertTypesHelper;

template <typename Pack, template <typename...> class P, template <int...> class Z>
struct InsertTypesHelper<Pack, P<>, Z<>> {
using type = Pack;
};

template <typename Pack, template <typename...> class P, typename First, typename... Rest, template <int...> class Z, int N, int... Ns>
struct InsertTypesHelper<Pack, P<First, Rest...>, Z<N, Ns...>> : InsertTypesHelper<typename Insert<First, Pack, N>::type, P<Rest...>, Z<Ns...>> {};

template <typename, typename, int...> struct InsertTypes;

template <typename Pack, template <typename...> class P, typename... Types, int... Is>
struct InsertTypes<Pack, P<Types...>, Is...> : InsertTypesHelper<Pack, P<Types...>, typename ReverseSortIntSequence<index_sequence<Is...>>::type> {};


Now, my tests:



int main() {
std::cout << std::is_same<
typename ReverseSortIntSequence<index_sequence<5,10,8,4,0,2,1,2,7,8,3>>::type,
index_sequence<10,8,8,7,5,4,3,2,2,1,0>
>::value << std::endl; // true

std::cout << std::is_same<
InsertTypesHelper<Pack<int, double, char, long, int>, Pack<float, short, std::string>, index_sequence<4,2,1>>::type,
Pack<int, std::string, double, short, char, long, float, int>
>::value << std::endl; // true (*)

std::cout << std::is_same<
typename ReverseSortIntSequence<index_sequence<2,4,1>>::type,
index_sequence<4,2,1>
>::value << std::endl; // true (**)

std::cout << std::is_same<
InsertTypes<Pack<int, double, char, long, int>, Pack<short, float, std::string>, 2,4,1>::type,
Pack<int, std::string, double, short, char, long, float, int>
>::value << std::endl; // false (rats!)
}


I get false above because despite (*) and (**) being true above, we must have Pack<short, float, std::string> permuted in the same way 2,4,1 is permuted in order to get that in reverse sorted order. I could proceed with this fix, but now it is getting overboard. I will still go ahead with that, but I seriously suspect there is a better method altogether, probably fairly short too.


Any good ideas here? I thought of extracting the pairs of types that the indices determine (the inserted types will go between the pairs), but this won't work if there are duplicate types in the original pack (and also because of the types being inserted too).


Update: I finished the permutation helper discussed above, and now everything is working correctly. But there must be a better and shorter solution than all this mess.



template <int, typename> struct NthType;

template <int N, template <typename...> class P, typename First, typename... Rest>
struct NthType<N, P<First, Rest...>> : NthType<N-1, P<Rest...>> {};

template <template <typename...> class P, typename First, typename... Rest>
struct NthType<0, P<First, Rest...>> {
using type = First;
};

template <int, int, typename> struct FindIndexOfIntHelper;

template <int N, int FindMe, template <int...> class Z, int... Rest>
struct FindIndexOfIntHelper<N, FindMe, Z<FindMe, Rest...>> : std::integral_constant<int, N> {};

template <int N, int FindMe, template <int...> class Z>
struct FindIndexOfIntHelper<N, FindMe, Z<>> : std::integral_constant<int, -1> {}; // Not found.

template <int N, int FindMe, template <int...> class Z, int First, int... Rest>
struct FindIndexOfIntHelper<N, FindMe, Z<First, Rest...>> : FindIndexOfIntHelper<N+1, FindMe, Z<Rest...>> {};

template <int FindMe, typename Pack>
using FindIndexOfInt = FindIndexOfIntHelper<0, FindMe, Pack>;

template <typename, typename, typename, typename> struct PermutePackHelper;

template <typename Pack, template <typename...> class P, typename... Accumulated, typename IndicesPack, template <int...> class Z>
struct PermutePackHelper<Pack, P<Accumulated...>, IndicesPack, Z<>> {
using type = P<Accumulated...>;
};

template <typename Pack, template <typename...> class P, typename... Accumulated, typename IndicesPack, template <int...> class Z, int I, int... Is>
struct PermutePackHelper<Pack, P<Accumulated...>, IndicesPack, Z<I, Is...>> :
PermutePackHelper<Pack, P<Accumulated..., typename NthType<FindIndexOfInt<I, IndicesPack>::value, Pack>::type>,
IndicesPack, Z<Is...>> {};

template <typename, typename, typename> struct PermutePack;

template <template <typename...> class P, typename... Types, template <int...> class Z, int... Is, int... Js>
struct PermutePack<P<Types...>, Z<Is...>, Z<Js...>> : PermutePackHelper<P<Types...>, P<>, Z<Is...>, Z<Js...>> {};



vendredi 27 février 2015

How to implement std::tuple efficiently such that a tuple of empty types is itself an empty type?


I am implementing std::tuple and I want it to be as efficient in both object size and compile time as possible. I am following the suggestions given here and here.


To improve compile-time performance, the implementation does not use recursive inheritance and instead uses multiple inheritance with the tuple_leaf trick. Additionally it uses the empty base class optimization when possible to reduce the size of the type.


To ensure that the empty base class optimization is always applied, my implementation of tuple itself derives from a base class instead of storing the implementation inside a member variable. However, this causes problems with nested tuples because the tuple_leaf technique works through conversion to a base class. Nested tuples cause ambiguity because the same type of tuple_leaf may occur more than once in the derivation chain.


A program illustrating a simplification of the problem is posted below. Is there a simple way to disambiguate the conversion and allow the program to compile and execute without throwing the assert? I have considered detecting the nested tuple case and encoding the multidimensional position of each tuple_leaf within its type somehow, but that seems complex and would probably degrade compile-time performance.



#include <type_traits>
#include <cassert>

template<int i, class T, bool = std::is_empty<T>::value>
struct tuple_leaf
{
tuple_leaf(T x) : val(x) {}

T& get() { return val; }

T val;
};


template<int i, class T>
struct tuple_leaf<i,T,true> : private T
{
tuple_leaf(T x) : T(x) {}

T& get() { return *this; }
};


template<int i, class T1, class T2>
struct type_at
{
using type = T1;
};


template<class T1, class T2>
struct type_at<1,T1,T2>
{
using type = T2;
};


template<class T1, class T2>
struct tuple_base : tuple_leaf<0,T1>, tuple_leaf<1,T2>
{
tuple_base(T1 a, T2 b) : tuple_leaf<0,T1>(a), tuple_leaf<1,T2>(b) {}

template<int i>
tuple_leaf<i,typename type_at<i,T1,T2>::type> get_leaf()
{
// XXX how to disambiguate this conversion?
return *this;
}
};


// XXX deriving from tuple_base rather than creating
// making tuple_base a member is the root of the issue
template<class T1, class T2>
struct my_tuple : tuple_base<T1,T2>
{
my_tuple(T1 a, T2 b) : tuple_base<T1,T2>(a, b) {}
};

template<int i, class T1, class T2>
typename type_at<i,T1,T2>::type& get(my_tuple<T1,T2>& t)
{
return (t.template get_leaf<i>()).get();
}

template<class T1,class T2>
my_tuple<T1,T2> make_tuple(T1 a, T2 b)
{
return my_tuple<T1,T2>(a,b);
}

struct empty {};

int main()
{
auto tuple = make_tuple(empty(), make_tuple(empty(),empty()));

assert((std::is_empty<decltype(tuple)>::value));

get<0>(tuple);

return 0;
}


The compiler output:



$ clang-3.5 -std=c++11 repro.cpp
repro.cpp:47:12: error: ambiguous conversion from derived class 'tuple_base<empty, my_tuple<empty, empty> >' to base class 'tuple_leaf<0, empty, true>':
struct tuple_base<struct empty, struct my_tuple<struct empty, struct empty> > -> tuple_leaf<0, struct empty>
struct tuple_base<struct empty, struct my_tuple<struct empty, struct empty> > -> tuple_leaf<1, struct my_tuple<struct empty, struct empty> > -> struct my_tuple<struct empty, struct empty> -> tuple_base<struct empty, struct empty> -> tuple_leaf<0, struct empty>
return *this;
^~~~~
repro.cpp:63:22: note: in instantiation of function template specialization 'tuple_base<empty, my_tuple<empty, empty> >::get_leaf<0>' requested here

return (t.template get_leaf<i>()).get();
^
repro.cpp:80:3: note: in instantiation of function template specialization 'get<0, empty, my_tuple<empty, empty> >' requested here
get<0>(tuple);
^
1 error generated.



How to use "loop" parallel processing by using GCD (grand central Dispatch )


I have programmed C++ under visual studio environment. there to do parallel processing i used openMP but OS X isn't supporting for openMP so i like to move GCD Apple . By using GCD how do i optimise the following loop ( here i want to do the thing what openMP does by using apple GCD) please help me to do that. thank you for any advance.



#pragma omp parallel for private(j)
for(i = 1; i <= I; i++){
for(j = 1; j <= J; j++){
if(max(1, m-Alpha+i0) <= i && i <= min(m+Alpha+i0, I) && max(1, n-Alpha+j0) <= j && j <= min(n+Alpha+j0, J)){
// cout << i << ", " << j << endl;
_AccmCalc(i, j, m, n);
}
}



code::block Process terminated with status 255 (0 minute(s), 24 second(s))


I use win7 and while working on glut project with given example main CPP it tries to proceess a windows appears and suddenly it says "Windows has stopped working" And code::block display -Process terminated with status 255 (0 minute(s), 24 second(s)) Plz help me am usiing freeglut with libfreeglut.a to link libraries.




Can I empty-base optimize mutable data?


I have a class template which looked like this:



template<typename T, typename Mutex, typename SomePolicy>
class my_class {
public:
T f() const {
resource_lock a_lock(some_mutex);
return some_policy.some_operation(some_data);
}
private:
T some_data;
mutable Mutex some_mutex;
SomePolicy some_policy;
};


If not used concurrently, we have a dummy mutex type which has all the member functions as inlined empty functions and no data. There are policies that have per-instance data and those that do not have any data.


This is library code and it turns out that this class template gets used in application code where the extra bytes matter which are needed for the data members some_mutex and some_policy even when they are empty classes. So I want to make use of the empty base optimization. For the policy, this is easy:



template<typename T, typename Mutex, typename SomePolicy>
class my_class {
public:
T f() const {
resource_lock a_lock(the_data.some_mutex);
return the_data.some_operation(the_data.some_data);
}
private:
struct data : SomePolicy {
T some_data;
mutable Mutex some_mutex;
};
data the_data;
};


However, given that some_mutex is mutable, I don't know how to make it a base class without making the_data, and thus all data, mutable, thereby completely taking over the compiler's responsibility to protect me from silly constness mistakes.


Is there a way to make a turn a mutable data member into a base of a non-mutable data member's class?




error: ‘time’ cannot be used as a function


I am trying to write a small function that will eventually store the current date and time in a text file. I am in Linux using g++ and keep getting a strange error.


Function(so far):



#include <ctime>
#include <time.h>
void write_updateTime(double time){
char buffer[80]={};
time_t rawt;
string local;
struct tm * timeinfo;
time(&rawt);
timeinfo = localtime(&rawt);

sprintf(buffer, "%s", asctime(timeinfo));
}


Error:


ApplicationModule.cpp:79:12: error: ‘time’ cannot be used as a function time(&rawt);


I have searched all over, and all the examples I have found use the time function this way. I have as well as


Any thoughts?




LPWSTR comparison


How do I properly deal with the if statement in this example:



int n_args = 0;
int i;
LPWSTR *args = CommandLineToArgvW(GetCommandLineW(), &n_args);
if (args)
{
if (n_args >= 2)
{
for (i = 1; i < n_args; i++)
{
std::cout << args[i] << "\n";
if (args[i] == L"/D") // <-- here
{
std::cout << "Condition met\n";
}
}
}
}


The first std::cout shows that the command line parameter has been passed, but the following if statement fails.




Free drawing using gdi - Issue with alpha color


I let user to draw on a form. I start when my app get the mouse down even. I end when it gets the mouse up event. I draw on mousemove event.


I.E in mouse down event i get the StartPoint. Then in mousemove i check, if mouse is still down then i draw according to the mouse position. I draw using DrawLine function. I save the previous point and draw to the new point i get in mousemove. lets say mouse moved from P1(x1,y1),P2(x2,y2),P3(x3,y3) then i have line from P1 to P2 to P3. Everything works as it should. Problem starts when i draw with transparent color (i.e Alpha is 100 for example). When i do that, P2 get painted twice. first time when line is drawn from p1 to p2 and second time when line drawn from p2 to p3.


When Alpha is 255 you do not see it since p2 color will not change when you over write it. It stays the pen color. When you overwrite with alpha that is not equal to 255 then on each overwrite the color become darker with looks as small dots inside the line.


I have attached screenshot so you will see the problem: http://ift.tt/1DjLAet Any solution to make lines with no dot in it? do not forget that there can be many points in the line and it is free drawing so line is not Straight. Each dot you see in the line was created on each call to mousemove.