mercredi 1 juillet 2015

Not able to understang this concept of handlers in c++

I was going through a piece of code where I came across something new.However I tried to write my own code for better understanding.

#include<iostream>

using namespace std;

class material
{
public:
material()
{
    cout<<"material() called"<<endl;
}

bool test_func()
{
    cout<<"Hello World"<<endl;

    return true;
}
};

class server
{
private:
material *mat;

public:
server()
{
    cout<<"server() called"<<endl;
}
material *matrl()
{
    return mat;
}
};

class Handler
{
public:
Handler()
{
    cout<<"Handler() called"<<endl;
}

server svr;

bool demo()
{
    bool ret;
    ret=svr.matrl()->test_func();

    return ret;
}
};

int main()
{
Handler h;
cout<<"returned by demo():"<<h.demo()<<endl;

return 0;
}

Even I am getting the desired output, which is:

server() called
Handler() called
Hello World
returned by demo():1

But I am not able to understand certain concepte over here,like

material *matrl()
{
    return mat;
}

and the call

ret=svr.matrl()->test_func();

How this is working and what concept is this.Can somebody help me with this???

When using IBO/EBO, program only works when I call glBindBuffer to bind the IBO/EBO AFTER creation of the VAO

For some reason, this program only works when I bind the IBO/EBO again, after I create the VAO. I read online, and multiple SO posts, that glBindBuffer only binds the current buffer, and that it does not attach it the the VAO. I thought the glVertexAttribPointer is the function that attached the data to the VAO.

float points[] = {

   -0.5f,  0.5f, 0.0f, // top left      = 0
    0.5f,  0.5f, 0.0f, // top right     = 1
    0.5f, -0.5f, 0.0f, // bottom right  = 2
   -0.5f, -0.5f, 0.0f, // bottom left   = 3

};

GLuint elements[] = {

    0, 1, 2,
    2, 3, 0,
};

// generate vbo (point buffer)
GLuint pb = 0;
glGenBuffers(1, &pb);
glBindBuffer(GL_ARRAY_BUFFER, pb);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);

// generate element buffer object (ibo/ebo)
GLuint ebo = 0;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

// generate vao
GLuint vao = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);


glBindBuffer(GL_ARRAY_BUFFER, pb);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);


glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); // when I bind buffer again, it works


glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);

If I did not have the second glBindBuffer, the program crashes. All I want to know is why I have to call glBindBuffer again, after I create the VAO, when calling glBindBuffer only makes the buffer the active buffer for other functions.

Pastebin (FULL CODE)

digital signature implementation in c++

this will be my first question here...soo plzz kndly help me...am in urgent need of this!

so i have to develop a c++ code for implementation of digital signatures. i understand the basic concept of it...but am kind of a noob wen it comes to c++ coding...sopoo can someone pllzz tell me step by step procedure of how to develop a code for digitaly signing a databse and den a code for verifying that previously signed database. sooo far wat i have done is: 1. created a databse using microsoft sql server 2. have found a library only for hashin which contains hashing function(m facing a problem here . the function sha256() requires to pass the databse as an arguement i dnt know how to do dat soo plzz if u can guide me through dis also) 3. i ll be provided with a doungle containing my private key for signing of the document. preferably i ll be using rsa signing.

sooo this wat i did and know abt dis project of mine...

i request to person answering to be exclusive and xplain in detail to how to approch and code dis in c++ as i a dnt possess ant thorogh knowledge of dis topic thank you!

How to fix the armadillo library to c++

I'm using a macbook to program some bits of code here and there. Recently I wanted to do something in C++ together with the armadillo library... but after installation and everything it doesn't seem to work...

For instance I can write arma::mat variable, etc but when I run this code in TextMate:

vec q = randu(5);

cout << normalise(q);

I get this error output:

"Undefined symbols for architecture x86_64: "_wrapper_dgesdd_", referenced from: void arma::lapack::gesdd(char*, int*, int*, double*, int*, double*, double*, int*, double*, int*, double*, int*, int*, int*) in test-56d704.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) rm: /var/folders/sh/vr2n15ln47j0k33yh1j0_tyw0000gn/T/test.cpp.Sfz5vezN: No such file or directory

The weird thing is that if I don't use the normalise or norm functions it compiles well..

I include the library as #include '/usr/local/include/armadillo'

Please help!

Edit: I've installed the armadillo package both trying with "brew install armadillo" but also with the steps mentioned in the README.txt if you download armadillo from their webpage. I'm at a total loss..

C++ can't implement default constructor

I have a class:

class Fraction {
    private:
        int x;
        int y;
    public:
    // Constructors
        Fraction(long x = 0, long y = 1);
        Fraction(const Fraction&)=default;//here is the problem
        virtual ~Fraction();
 };

And I'm trying to disable default C++ constructor for copy, to do my own. So, I declared it as a default. But, when I'm trying to implement it:

Fraction::Fraction(const Fraction&){}

Compiler throws some errors at me.

./src/Fraction.cpp:16:1: error: definition of explicitly-defaulted ‘Fraction::Fraction(const Fraction&)’ Fraction::Fraction(const Fraction&){ ^ In file included from ../src/Fraction.cpp:8:0: ../src/Fraction.h:22:2: error: ‘Fraction::Fraction(const Fraction&)’ explicitly defaulted here Fraction(const Fraction&)=default;

Is there any way to fix it? What I'm doing wrong, I found some articles about defaults, but nothing that can help me to fix these errors.

QString functions giving incorrect results on CentOS

I am using C++ Qt Library and following code is working perfectly on Windows but not working on CentOS :

if(line.startsWith("[", Qt::CaseInsensitive))
                        {
                            int index = line.indexOf(']', 0, Qt::CaseInsensitive);
                            QString subLine = line.mid(index+1);
                            subLine = subLine.trimmed();
                            tokenList = subLine.split("\t");
                        }
                        else
                        {
                            tokenList = line.split("\t");
                        }

I have a line [ x.x.x.x ] something ../dir/file.extension and i want to ignore the [x.x.x.x] part while breaking line into tokens. I ma using VC9 on windows to debug and its working fine.

Double-checking understanding of memory coalescing in CUDA

Suppose I define some arrays which are visible to the GPU:

double* doubleArr = new double[fieldLen];
float* floatArr = new float[fieldLen];
char* charArr = new char[fieldLen]

Now, I have the following CUDA thread:

void thread(){
  int o = getOffset(...);
  double d = doubleArr[threadIdx.x + o];
  float f = floatArr[threadIdx.x + o];
  char c = charArr[threadIdx.x + o];
}

I'm not quite sure whether I correctly interpret the documentation, and its very critical for my design: Will the memory accesses for double, float and char be nicely coalesced? (Guess: Yes, it will fit into sizeof(type) * blockSize.x / (transaction size) transactions, plus maybe one extra transaction at the upper and lower boundary.)

Furthermore, suppose I also have a struct:

struct char3{
  char a;
  char b;
  char c;
}

char3* char3Arr = new char3[fieldLen];

I guess this will be padded and aligned to 32 bit and then consume fieldLen*4 bytes in memory and coalesce the same way as a float?

What is wrong with this approach of copy and assignment? [duplicate]

This question already has an answer here:

#include <iostream>
#include <vld.h>

using namespace std;

class MyClass
{
private:
    int x;
    int y;
    int z;
private:
    void Copy(const MyClass & rhs) throw ()
    {
        x = rhs.x;
        y = rhs.y;
        z = rhs.z;
    }
public: 
    MyClass()
    {
        x = 0;
        y = 0;
        z = 0;
    }
    ~MyClass()
    {
        x = 0;
        y = 0;
        z = 0;
    }
    MyClass(const MyClass & rhs)
    {
        Copy(rhs);
    }
    MyClass & operator=(const MyClass & rhs)
    {
        Copy(rhs);

        return *this;
    }
    void Set(int a, int b, int c)
    {               
        x = a;
        y = b;
        z = c;
    }
    void Show(void) const 
    {
        cout<<x<<", "<<y<<", "<<z<<endl;
    }
};

int main()
{
    MyClass o1;
    o1.Set(10, 20, 30);
    o1.Show();

    MyClass o2(o1);

    o1 = o2;

    o1.Show();
}

Why is this std::unique_ptr being returned without a std::move statement

I am trying to familiarize my self with the std::unique_ptr and I understand that these pointers can only be moved. This is the code that I am trying out

struct foo
{
    int a;
};

std::unique_ptr<foo> GetPointer()
{
    std::unique_ptr<foo> f(new foo());
    return f;
}

int main()
{
    std::unique_ptr<foo> m = GetPointer();
}

I am using the flag -fno-elide-constructors to disable compiler optimization that reduces the copies made. My question is why is the f being returned ? It is an lvalue so I am assuming it cannot be moved. I was expecting to get an error because of return f and I was under the impression it should be return std::move(f)

What is my code missing. no match for 'operator<<' in 'std::cout << vals' [duplicate]

This question already has an answer here:

#include <iostream>
#include <iomanip>
#include <stdlib.h>

using namespace std;

struct twoVals
{
        int x;
    double y;
} number;

int main()
{
    number.x = 10;
    number.y = 20;

twoVals vals;
cout << vals << endl;

return 0;

}

Line 19: error: no match for 'operator<<' in 'std::cout << vals' compilation terminated due to -Wfatal-errors.

That is the error I get. How do I fix this? Is there anything else wrong with my code? Give examples.

Linker Error 2019 without touching the linker properties?

So I'm making a game, and it was working perfectly fine, so I started developing the next part of the game which is the chunking system and the generation (you might be able to tell from my previous posts) but then all of a sudden I got some random linker errors, even though I haven't touched anything in the linker and the game was working perfectly fine before. Here are the errors:

Error   3   error LNK2019: unresolved external symbol "public: class sf::Sprite __thiscall AbstractBlock::draw(void)" (?draw@AbstractBlock@@QAE?AVSprite@sf@@XZ) referenced in function _main   C:\(Insert personal stuff here)\Main.obj    Top Down Shooter
Error   4   error LNK2019: unresolved external symbol "public: void __thiscall AbstractBlock::destroy(class b2World *)" (?destroy@AbstractBlock@@QAEXPAVb2World@@@Z) referenced in function "public: int __thiscall Universe::saveGame(void)" (?saveGame@Universe@@QAEHXZ)  C:\(Insert personal stuff here)\Universe.obj    Top Down Shooter
Error   5   error LNK1120: 2 unresolved externals

They don't have line numbers and it appears the problem is in the Universe.obj and main.obj? I honestly don't know what those are, so instead I'm going to post both of the .cpp files in full:

Universe.cpp:

#include "Universe.h"

Universe::Universe(){

    world = new b2World(b2Vec2(0, 0));
    world->SetAllowSleeping(false);

    chunkManager = new ChunkManager(world);

    player = new Player(world);


}


Universe::~Universe()
{
}

int Universe::saveGame(){
    player->destroy(world);
    player = nullptr;


    std::list<AbstractBlock>::iterator i;

    for (i = getLoadedBlocks()->begin(); i != getLoadedBlocks()->end(); i++){
        i->destroy(world);
    }

    world = nullptr;
    return 1;
}

void Universe::spawnEntity(int x, int y, int entityID){

}

std::list<AbstractBlock>* Universe::getLoadedBlocks(){
    return chunkManager->getLoadedBlocks();
}

void Universe::update(){

    player->update();

    world->Step(1 / 60.f, 8, 3);
}

Player* Universe::getPlayer(){
    return player;
}

Main.cpp:

#include <iostream>
#include "Box2D\Box2D.h"
#include "SFML/Graphics.hpp"
#include "Universe.h"
#include "simplexnoise.h"

int main(){

    static int FPS = 1.f / 60.f;

    sf::RenderWindow window(sf::VideoMode(640, 480), "Top Down Shooter");
    sf::Event event;

    Universe universe;

    bool running = true;
    int distX;
    int distY;
    float angle;

    while (running){

        window.clear(sf::Color::White);

        while (window.pollEvent(event)){
            switch (event.type){
            case sf::Event::Closed:
                running = false;
                break;
            case sf::Event::KeyPressed:
                switch (event.key.code){
                case sf::Keyboard::Q:
                    running = false;
                    break;
                case sf::Keyboard::W:
                    universe.getPlayer()->setMoveUp(true);
                    break;
                case sf::Keyboard::A:
                    universe.getPlayer()->setMoveLeft(true);
                    break;
                case sf::Keyboard::D:
                    universe.getPlayer()->setMoveRight(true);
                    break;
                case sf::Keyboard::S:
                    universe.getPlayer()->setMoveDown(true);
                    break;
                }
                break;
            case sf::Event::KeyReleased:
                switch (event.key.code){
                case sf::Keyboard::W:
                    universe.getPlayer()->setMoveUp(false);
                    break;
                case sf::Keyboard::A:
                    universe.getPlayer()->setMoveLeft(false);
                    break;
                case sf::Keyboard::D:
                    universe.getPlayer()->setMoveRight(false);
                    break;
                case sf::Keyboard::S:
                    universe.getPlayer()->setMoveDown(false);
                    break;
                }
                break;

            }


        }

        distX = (sf::Mouse::getPosition().x - universe.getPlayer()->getXpos() - window.getPosition().x - 10);
        distY = (sf::Mouse::getPosition().y - universe.getPlayer()->getYpos() - window.getPosition().y - 30);
        if (distX != 0){
            angle = std::atan2f(distY, distX);
            universe.getPlayer()->setAngle(angle + (b2_pi / 2));
        }

        //Updating the universe
        universe.update();

        //Drawing Everything
        window.draw(universe.getPlayer()->draw());

        std::list<AbstractBlock>::iterator i;

        for (i = universe.getLoadedBlocks()->begin(); i != universe.getLoadedBlocks()->end(); i++){
            window.draw(i->draw());
        }




        window.display();


    }

    universe.saveGame();

    return 0;
}

So I was trying to figure out the problem on my own, and I thought it may have been the part where I use the iterator and the lists to draw all the current blocks in the universe. I thought this because both the Universe and main .cpp have these small for loops in them (which I just recently added). So I commented out those parts in each file and things got even weirder. Visual Studio 2013 then gave me errors when I ran my program and then would take me to xutility file! I have no idea why! I made sure to comment out the iterator part and tried again but the same thing happened! With those two lines of iterators commented out I'm not using iterators at all in my program! Why would it be taking me to there? Please help i'm so confused >.<

Defining a Discrete Probability Distribution in C++

I have been trying to create my own discrete distribution in Visual Studio (C++). I kept getting the same error. I then tried the example code from: http://ift.tt/1R6pjgK.

Again, the same error appeared with this example code.

The line of code (from the link) that is giving me an error is:

std::discrete_distribution second(init.begin(), init.end());

Particularly, init.begin() is underlined in red.

The 2 errors are as follows:

2 error C2661: 'std::discrete_distribution::discrete_distribution' : no overloaded function takes 2 arguments

3 IntelliSense: no instance of constructor "std::discrete_distribution<_Ty>::discrete_distribution [with _Ty=int]" matches the argument list argument types are: (std::_Array_iterator, std::_Array_iterator)

Why would my compiler not work? I am wondering if other people are getting the same errors? I also just updated my version of Visual Studio to make sure it wasn't an old bug

method binding in C++

class Shape {
    public:
        virtual void draw() = 0;
        virtual void area() { . . .}
        . . .
};

class Circle : public Shape {
    public:
        void draw() { . . . }
        . . .
};

class Rectangle : public Shape {
    public:
        void draw() { . . . }
        . . .
};

class Square : public Rectangle {
    public:
        void draw() { . . . }
        . . .
};

Rectangle* r = new Rectangle;
r->draw(); // (1)

r = new Square;
r->draw(); // (2)

Shape* sh = new Circle;
sh->area(); // (3)

Square* sq = new Square;
sq->draw(); // (4)

(1),(2) dynamic binding, there's no doubt i think

(3) Since any class derived from Shape don't override the method area, it's resolved to Shape::area() by compiler?

(4) No class derived from Sqaure class, sq can only reference Square type, it means static method binding occurs?

Is there anything wrong?? thanks in advance.

Universal references with functions

What is the type of "univ" in the code below?

template<typename T>
void func(T&& univ) {
    // ??
}

int sum(int a, int b) {
 return a+b;   
}

int main() {

    func(sum);

}

I didn't know that universal references also worked with functions. Is func(sum); equivalent to func(&sum); or is the rvalue reference binding itself to something else than a simple pointer?

String vector to 3D char vector

I'm new to C++ and this is my first attempt at a 3D vector. I'm trying to take an input file like this:

xxooo##xx
xoxxxoxoo
xxx#oxoo#
oxxxoxoox
xxoooo#xx
xxxo#o###
xxo#o#xxo
x##oxxoox
xxx##oxoo
xoxx#xooo

And turn it into a 3D char vector where each line is a 3x3 box with the first three characters being the first row, the next three the 2nd row, and the last three the 3rd row. For example the first row of the input should turn into this:

x x o
o o #
# x x

This is my attempt at a solution, but I feel that I've probably made several mistakes:

vector<vector<vector<char> > > makeBoard(vector<string> iflines)
{// Function to fill game boards from input strings

vector<vector<vector<char> > > charboard;

for (int i = 0; i != iflines.size(); i++) 
{   
    for (int j = 0; j < 9; j++)
    {
    charboard[i][j/3][j%3] = iflines[i][j];         
    }   
}
    return charboard;
}

Would someone please help me out here?

Invisible differences in XML files - breaking self-made XML parser

I have two programs that interact with an well-defined XML file. The first program (Model) reads it in, parses it, and uses content from the file to direct the running of a model. The second program (Controller) opens up and rewrites the XML file, allowing different settings to be run in the Model.

Model is written in C++, worked with in VS2010 and VS2012, has no GUI, and uses a home-made (is this the correct term?) XML parser that has worked for many years without fail - I just checked the SVN for revisions to the files that make it up - nothing since 2013. Controller is written in C#, in VS2012, with a GUI that has drop downs that set the content of the XML file, and uses the XmlDocument class to read in, edit, and print out the XML file .

Suddenly, the Controller no longer spits out XML files that can be read by Model. When Model tries to read the XML file, the first character it encounters it reads as '-17'. AS far as I have been able to tell this means that it doesn't recognize it as an UTF-8 character. This cause model to cout the error and then crash. Older XML file (which looks identical to the ones written by Controller) reads in fine.

Below are examples of the files - ignore the content inside the elements please.

Older file:

<?xml version="1.0" encoding="UTF-8" ?> 
<Config>
<Mode value="false" Id="Modeflag" />
<Timestep OutputTimestep="Hourly"  CalibrationTimestep="Daily" />
<InitialInput SubCatchmentNumber="1" ModelCalibration="true" SnowSimulation="false" VegSimulation="Method 1" CatchmentNumber="1" FractionalCatchmentArea="1" />
<InputResource Name="All" Location="C:\Hydro_Code\Hydro_Test_Files\Inputs\V5HarborBrookWeek_Rain" Id="Directory" />
<SimulationScheme SchemeForCatchmentNo="8" Infiltration="true" ChannelRouting="false" Saturation="true" TopographicIndex="true" KDecayWithSoilDepthExp="false" SoilTopoIndex="false" KDecayInPower="true" />
<SnowInput InputCatchmentNumber="1" TempIndexMethod_Hourly="false" RadiationTempIndex_With_SnowInterception="true" EnergyBudgetMethod_With_SnowInterception="false" />
<SnowInputResource Name="All" Location="C:\Hydro_Code\Hydro_Test_Files\Inputs\V5HarborBrookWeek_Rain" Id="SnowDirectory" />
<OutputDirectory Location="C:\Hydro_Code\Hydro_Test_Files\Inputs\V5HarborBrookWeek_Rain\Outputs" Name="Toronto_Output" />
</Config>

Newer file:

<?xml version="1.0" encoding="UTF-8" ?>
<Config>
  <Mode value="false" Id="Modeflag" />
  <Timestep OutputTimestep="Hourly" CalibrationTimestep="Hourly" />
  <InitialInput SubCatchmentNumber="1" ModelCalibration="true" SnowSimulation="false" VegSimulation="Method 1" CatchmentNumber="1" FractionalCatchmentArea="1" />
  <InputResource Name="All" Location="C:\AutoRun_Newest\AutoRun" Id="Directory" />
  <SimulationScheme SchemeForCatchmentNo="8" Infiltration="true" ChannelRouting="false" Saturation="true" TopographicIndex="true" KDecayWithSoilDepthExp="false" SoilTopoIndex="false" KDecayInPower="true" />
  <SnowInput InputCatchmentNumber="1" TempIndexMethod_Hourly="false" RadiationTempIndex_With_SnowInterception="true" EnergyBudgetMethod_With_SnowInterception="false" />
  <SnowInputResource Name="All" Location="C:\AutoRun_Newest\AutoRun" Id="SnowDirectory" />
  <OutputDirectory Location="C:\AutoRun_Newest\Inputs\Output_Timestamp_07012015215112" Name="Toronto_Output" />
</Config>

Adding or taking away the indentation (proper formatting by the XmlDocument class in C#) changes nothing about the behavior of Model.

These files are visually identical, and I can see no odd characters or spacing. What invisible objects/forces/characters or other settings could be causing this new bug?

Is there some background encoding that the XML document class enforces that is new to my home made parser?

Passing C++ character array to Fortran

I have been trying to pass a character array from C++ to a Fortran subroutine but it seems like Fortran does not receive characters properly. I have been searching the web to find a solution but proposed ideas seem to be too complicated. An interesting (and concise) solution was proposed by Steve at Intel Fortran Forum but I cannot get it work in my code. So, I appreciate any suggestion to help me out to resolve this issue.

The following function is my C++ routine that makes call to fortran subroutines:

extern "C" void __stdcall F_VALIDATE_XML(const char* buffer, int len);
void CUDMEditorDoc::OnValidateXML()
{
    CString fileName = "test.udm";
    const char* buffer = fileName.GetBuffer();
    int len = fileName.GetLength();
    F_VALIDATE_XML(buffer, len);
}

And here is the Fortran subroutine that is supposed to receive character array:

subroutine validate_xml(file_name, len)
!DEC$ ATTRIBUTES DECORATE, STDCALL, ALIAS:"F_VALIDATE_XML" :: validate_xml

use xml_reader_structure
use, intrinsic :: ISO_C_Binding

integer(C_INT), value, intent(in) :: len
character(len, kind=C_CHAR), intent(in) :: file_name

integer  :: i
i = 1
end subroutine validate_xml

In debug mode and when the program has stopped at line (i = 1), I hover mouse over file_name to see its contents but the Watch window says that it cannot find file_name symbol (although len is correctly passed). Also, if I watch file_name(1:8) in watch window, still I don't get the original character arrays. I believe there is something wrong with the way I pass parameters to Fortran but chances are Watch Window is not correct.

I appreciate any help that could shed some lights here. Thanks

Define an object in a .cpp file

Header file

class Universe
{
    public:
        Universe();
        ~Universe();

    private:
        ChunkManager chunkManager;
};

I want to initialize chunkManger without using the default constructor. However, the constructor I want to use takes an object. How do I make the chunkManager object to use the correct constructor in the .cpp file? So I want something like this:

Universe::Universe(){

    world = new b2World(b2Vec2(0, 0));
    world->SetAllowSleeping(false);

    //I want something like this because the constructor I want takes a World object
    chunkManager = new ChunkManager(world);

    player = new Player(world);
}

"Read" does not name a type

I have been writing a program which requires me to take input from the serial monitor in Arduino. However I'm having some problems. Here's my code. #include

int R1 = 20;
int R2_2 = 20;
int R4_7 = 20;
int R5_6 = 20;
int R7_5 = 20;
int R8_2 = 20;
int R10 = 20;
int R15 = 20;
int R22 = 20;
int R27 = 20;
int R33 = 20;
int R39 = 20;
int R47 = 20;
int R56 = 20;
int R68 = 20;
int R75 = 20;
int R82 = 20;
int R100 = 20;
int R120 = 20;
int R150 = 20;
int R180 = 20;
int R220 = 20;
int R270 = 20;
int R330 = 20;
int R390 = 20;
int R470 = 20;
int R510 = 20;
int R680 = 20;
int R820 = 20;
int R1k = 20;
int R1k5 = 20;
int R2k2 = 20;
int R3k3 = 20;
int R3k9 = 20;
int R4k7 = 20;
int R5k6 = 20;
int R6k8 = 20;
int R7k5 = 20;
int R8k2 = 20;
int R10k = 20;
int R15k = 20;
int R22k = 20;
int R33k = 20;
int R39k = 20;
int R47k = 20;
int R56k = 20;
int R68k = 20;
int R75k = 20;
int R82k = 20;
int R100k = 20;
int R150k = 20;
int R180k = 20;
int R220k = 20;
int R330k = 20;
int R470k = 20;
int R560k = 20;
int R680k = 20;
int R1m = 20;
int R1m5 = 20;
int R2m = 20;
int R3m3 = 20;
int R4m7 = 20;
int R5m6 = 20;
int R10m = 20;
int AClips = 11;
int Blue_LED = 50;
int RGB_LED = 1;
int Yellow_LED = 10;
int Red_LED = 16;
int Button = 102;
int Carbon_Film = 2;
int Ambient_Light_Sensor = 10;
int Laser_Diode = 9;
int photocell = 1;
int Piezo_Buzzer = 1;
int Relay = 1;
int Transistor_2N2222A = 1;
int Transistors = 0 + Transistor_2N2222A;
char searchedItem[200];

This next line is the line that was highlighted: read.Serial(searchedItem);

void setup() {
//setup code here, to run once:
Serial.begin(9600);
}

void loop() {
//loop code here, to run forever:
if (searchedItem == "Red LED"); {
if (searchedItem => 1); {
  Serial.println("\nFound!\nYou have ", Red_LED, "Red LEDs");
    }
  }
}

c++ sqlite3_prepare_v2 is not working

this is my first post so excuse me if I forget to add some information, or my english mistakes.

I m working in c++ with code:block(13.12) making a DLL of sqlite3 functions and using MinGW toolchain. (windows 7)

I was using sqlite3_exec function but i want to change to sqlite3_prepare_v2, sqlite_bind.., sqlite3_step, etc because I think it will be easy to get back the return params. However, after calling that new function from another program written also in c++, it crash giving me this error:

  Nombre del evento de problema:  APPCRASH
  Nombre de la aplicación:    SQL_try.exe
  Versión de la aplicación:   0.0.0.0
  Marca de tiempo de la aplicación:   5594a5af
  Nombre del módulo con errores:  sqlite3.dll
  Versión del módulo con errores: 3.8.10.2
  Marca de tiempo del módulo con errores: 555cd28a
  Código de excepción:    c0000005
  Desplazamiento de excepción:    0001ee21
  Versión del sistema operativo:  6.1.7601.2.1.0.768.3
  Id. de configuración regional:  3082
  Información adicional 1:    0a9e
  Información adicional 2:    0a9e372d3b4ad19135b953a78882e789`
  Información adicional 3:    0a9e
  Información adicional 4:    0a9e372d3b4ad19135b953a78882e789

I can not easily depurated it because I m not use to code:block and also I m calling the function from a DLL.

This is the function I m using, that i get it from this other post:[Proper use of callback function of sqlite3 in C++

string DLL_EXPORT readFromDB(sqlite3* db, int id)
{   string result;
    sqlite3_stmt *stmt;
     const char *sql="SELECT name FROM datos WHERE id = ?";
    int rc = sqlite3_prepare_v2(db, sql,-1 , &stmt, NULL);
    if (rc != SQLITE_OK)
        return string(sqlite3_errmsg(db));

    rc = sqlite3_bind_int(stmt, 1, id);    // Using parameters ("?") is not
    if (rc != SQLITE_OK) {                 // really necessary, but recommended
        string errmsg(sqlite3_errmsg(db)); // (especially for strings) to avoid
        sqlite3_finalize(stmt);            // formatting problems and SQL
        return errmsg;                      // injection attacks.
    }

    rc = sqlite3_step(stmt);
    if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
        string errmsg(sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return errmsg;
    }
    if (rc == SQLITE_DONE) {
        sqlite3_finalize(stmt);
        return string("customer not found");
    }

    result= string((char *)sqlite3_column_text(stmt, 0))+ " ";
   // *result=*result + string((char*)sqlite3_column_text(stmt, 1)) +" ";
    //*result=*result + string((char*)sqlite3_column_int(stmt, 2));

    sqlite3_finalize(stmt);
   return result;
}

I m calling the DLL function with:

mifunc5=(Myfunc5)GetProcAddress(  histDLL,"readFromDB");
   aString=(mifunc5)(db,1);

An I don't think that the problem is that the db is not loaded, beacuse the other functions works and i tryed to comment all except the sqlite3_prepare_v2 and sqlite3_finalize funtions, neither works.

Thank you very much for your attention. :)

CUDA Thrust - How can I write a function using multiple device vectors with different sizes?

I've been trying figure out how to perform a simple entropy calculation using four thrust device vectors.

I have four device vectors, representing two key-value pairs. The first pair of vectors contains the keys and the number of times that key appears. The second pair contains keys paired with the bins for calculating the entropy. In this second vector pair, keys appear multiple times, with each instance representing a different bin.

It looks something like this:

Device Vector Pair 1

KeyVal 6 8 9

Counts 1 3 2

Device Vector Pair 2

KeyVal 6 8 8 9 9

BinVal 1 1 2 1 1

What I'm planning on doing is to use the first vector pair to check if a key appears enough times to calculate the entropy. If the count is large enough, the second vector pair will be used to calculate the entropy with the bin values for that key. I will need to use all of the bin values for that particular key. For example, if I wanted to calculate the entropy for keys that have appeared at least 3 times, I would find in the first vector pair that KeyVal 8 is ready. Then, I would search the second pair for all instances of KeyVal 8, and calculate the entropy using their corresponding BinVals.

However, I have no clue how to make this part work. I've tried using thrust::for_each to find all the keys that appear enough times to be tested, but I don't think it's possible to search for the keys in the second vector pair and perform the calculation within the for_each function.

Does anyone have suggestions on other ways to accomplish this?

Thank you for your help.

c++ custom sorting a vector

Not going to go too deep into what I am doing because it is homework and I don't need it done for me but, I do need some help. I need to be able to specify what part of a vector<vector<string>> gets sorted first and under what parameters.

Currently what I am doing works perfectly by calling

sort ( v.begin(), v.end() );

If you write out my vectors they will look something like:

5 2 4 6 12 2 5

22 51 2 5 72 1

And I might need to sort it in descending order by the 2nd column and if the 2nd column is the same I would then sort by the next specified column.

called like ./sort 2,4

would sort by second column and then 4th.

I looked around and apart from writing my own sorting algorithm for this I don't know how I would customize the sort.

Reading and displaying UTF-8 encoded Chinese characters

I am trying to read Chinese characters from a UTF-8 encoded text file and storing them in variables. When I try to print them in console, it shows question marks in place of the characters.

    while(!fin.eof())
    {
        fin.get(c);
        appendCharacterToWord(currentWord, c);
    } 

(I am working in Windows and the code is in C++)

C++ equivalent array

The question can be found here:http://ift.tt/1R6kVOW

here's my function:

    #include<iostream>
    using namespace std;
    bool equivalent(int a[], int b[], int n)
    {
       int i=0, j=0, count =0;
        while (a[i]!=b[j])
       {

           count++;
           j++;
       }

     for(int i=0; i<=n; i++)
       if(a[i]%n==b[i+count]%n)
          return true;
       else return false;
    }

please advise, thanks in advance!

Why does this code not work properly to get factorial?

I have this code:

int f(int n) {
    if (n == 0) return 0;
    else return f(n-1)*n;
}

It returns 0 every time. What is going on here?

How to detect motion from already store webm video in c++

I want to detect motion in already existing video, The video is stored in the webm format. I have seen some demo of opencv but those samples is capturing the motion of the live webcam streaming.

Is there any library or api which capture the motion of the webm video file in c++?

please help me.

Visual Studio 2005 - LNK1112: module machine type 'IA64' conflicts with target machine type 'X86'

I recently got a Visual Studio project, and I'm trying to compile it in VS2005. After fixing it up, theres is one error that is preventing me from successfully compiling it.

nafxcwd.lib(nolib.obj) : fatal error LNK1112: module machine type 'IA64' conflicts with target machine type 'X86'

I'm running Windows XP, 32 bit compiling to x86.
What is the library it is looking for? I have searched for a x86 version but I haven't been able to come up with anything.

Can someone please shed some light on this?

Same operations taking different time

I am in the process of optimizing my code for my n-body simulator, and when profiling my code, have seen this:

enter image description here

These two lines,


float diffX = (pNode->CenterOfMassx - pBody->posX);
float diffY = (pNode->CenterOfMassy - pBody->posY);

Where pNode is a pointer to a object of type Node that I have defined, and contains (with other things) 2 floats, CenterOfMassx and CenterOfMassy

Where pBody is a pointer to a object of type Body that I have defined, and contains (with other things) 2 floats, posX and posY.


Should take the same amount of time, but do not. In fact the first line accounts for 0.46% of function samples, but the second accounts for 5.20%.

Now I can see the second line has 3 instructions, and the first only has one.

My question is why do these seemingly do the same thing but in practice to different things?

Incorrect time calculation with mktime to get UTC+8

I want to get the current time in Hong Kong (UTC+8), and my local time is UTC-5.

Using and running the following in VS2012:

#pragma warning(disable : 4996)
char buffer[10];
time_t rawtime;
time(&rawtime);
strftime(buffer, 10, "%H:%M:%S", localtime(&rawtime));
cout << "LocalTime=" << buffer << endl;
strftime(buffer, 10, "%H:%M:%S", gmtime(&rawtime));
cout << "GMTime=" << buffer << endl;
tm* r = gmtime(&rawtime);
r->tm_hour += 8; // Hong Kong time
mktime(r); // Normalize the struct
strftime(buffer, 10, "%H:%M:%S", r);
cout << "HongKongTime=" << buffer << endl;

Produces the following output:

LocalTime=22:51:47
GMTime=02:51:47
HongKongTime=11:51:47

So it's computing UTC correctly, but then adding 8 hours to that is actually producing a time that is UTC +9. What's going wrong?

And is there a more elegant/reliable way of getting UTC+8 than this kludge?

Libclang don't follow include statement

I'm trying to use Libclang to programatically analyse the Opencv library, but when I try to import the main header from Opencv opencv.hpp, libclang won't follow the path.

Previously, it was reading everything quite beautifully, but then I figured it was following my $PATH's headers, and I want it to follow these specifics ones.

opencv.hpp is a file containing lots of #include statements like so:

#include "core/core_c.h"
#include "core/core.hpp"
#include "flann/miniflann.hpp"
// ... and so on

but, when I try to open it with libclang, or either clang ./opencv.hpp, it won't follow:

clang ./Header_Example/opencv.hpp
./Header_Example/opencv.hpp:46:10: fatal error: 'core/core_c.h' file not found
#include "core/core_c.h"
         ^
1 error generated.

but I'm sure it is on the right directory (a bit of my tree output):

── Header_Example
│   ├── opencv.hpp
│   ├── opencv2
│   │   ├── # more directories
│   │   ├── core
│   │   │   ├── affine.hpp
│   │   │   ├── core.hpp
│   │   │   ├── core_c.h
│   │   │   ├── types_c.h
│   │   │   ├── version.hpp
│   │   │   └── wimage.hpp

maybe I'm not using the right clang parameters?

A bit of context: I want to analyse Opencv types, classes and functions, this info is present on the headers, so I don't think I would need the full library to read the code. When I tried to use the full library I found myself in trouble. I need to use the iOS compilation(?)version(?) of the library, hence I copy/pasted the headers from the compiled version into this working directory (sorry? :) )

EDIT 1: It may seem odd my directories having this opencv2/, but if I remove the headers from inside of it, clang will complain 'bout why aren't they there: fatal error: 'opencv2/core/types_c.h' file not found

How can I build Rust code with a C++/Qt/CMake project?

I have an existing C++/Qt project built with CMake. I'd like to start adding Rust code which I can invoke from inside the main C++ codebase.

What's the right way to structure the project?

Current project structure:

./CMakeLists.txt
./subproject-foo/CMakeLists.txt
./subproject-foo/src/...
./subproject-bar/CmakeLists.txt
./subproject-bar/src/...
./common/CMakeLists.txt
./common/src/...

I'd like to add a common-rust/... directory with similar structure.

How can I incorporate this into the project?

Type trait for copying cv reference qualifiers

Writing library-like code in C++ I found there is particular need in copy_cv_reference_t type trait:

struct A;
struct B;

static_assert(std::is_same< copy_cv_reference_t<          A         , B >,          B          >{});
static_assert(std::is_same< copy_cv_reference_t<          A const   , B >,          B const    >{});
static_assert(std::is_same< copy_cv_reference_t< volatile A         , B >, volatile B          >{});
static_assert(std::is_same< copy_cv_reference_t< volatile A const   , B >, volatile B const    >{});
static_assert(std::is_same< copy_cv_reference_t<          A        &, B >,          B        & >{});
static_assert(std::is_same< copy_cv_reference_t<          A const  &, B >,          B const  & >{});
static_assert(std::is_same< copy_cv_reference_t< volatile A        &, B >, volatile B        & >{});
static_assert(std::is_same< copy_cv_reference_t< volatile A const  &, B >, volatile B const  & >{});
static_assert(std::is_same< copy_cv_reference_t<          A       &&, B >,          B       && >{});
static_assert(std::is_same< copy_cv_reference_t<          A const &&, B >,          B const && >{});
static_assert(std::is_same< copy_cv_reference_t< volatile A       &&, B >, volatile B       && >{});
static_assert(std::is_same< copy_cv_reference_t< volatile A const &&, B >, volatile B const && >{});

I invent it for myself using two approaches: via means of id of type qualifiers and via SFINAE only.

#include <type_traits>

#if 1
enum class type_qual_id
{
    value,
    const_value,
    lref,
    const_lref,
    rref,
    const_rref,
    volatile_value,
    volatile_const_value,
    volatile_lref,
    volatile_const_lref,
    volatile_rref,
    volatile_const_rref,
};

template< type_qual_id tqid, typename type > struct add_type_qualifier;
template< typename to > struct add_type_qualifier< type_qual_id::value               , to > { using type =          to         ; };
template< typename to > struct add_type_qualifier< type_qual_id::const_value         , to > { using type =          to const   ; };
template< typename to > struct add_type_qualifier< type_qual_id::lref                , to > { using type =          to       & ; };
template< typename to > struct add_type_qualifier< type_qual_id::const_lref          , to > { using type =          to const & ; };
template< typename to > struct add_type_qualifier< type_qual_id::rref                , to > { using type =          to       &&; };
template< typename to > struct add_type_qualifier< type_qual_id::const_rref          , to > { using type =          to const &&; };
template< typename to > struct add_type_qualifier< type_qual_id::volatile_value      , to > { using type = volatile to         ; };
template< typename to > struct add_type_qualifier< type_qual_id::volatile_const_value, to > { using type = volatile to const   ; };
template< typename to > struct add_type_qualifier< type_qual_id::volatile_lref       , to > { using type = volatile to       & ; };
template< typename to > struct add_type_qualifier< type_qual_id::volatile_const_lref , to > { using type = volatile to const & ; };
template< typename to > struct add_type_qualifier< type_qual_id::volatile_rref       , to > { using type = volatile to       &&; };
template< typename to > struct add_type_qualifier< type_qual_id::volatile_const_rref , to > { using type = volatile to const &&; };

template< type_qual_id tqid, typename to >
using add_qualifier_t = typename add_type_qualifier< tqid, to >::type;

template< typename type > constexpr type_qual_id get_type_qualifier_id                           = type_qual_id::value               ;
template< typename type > constexpr type_qual_id get_type_qualifier_id<          type const    > = type_qual_id::const_value         ;
template< typename type > constexpr type_qual_id get_type_qualifier_id<          type       &  > = type_qual_id::lref                ;
template< typename type > constexpr type_qual_id get_type_qualifier_id<          type const &  > = type_qual_id::const_lref          ;
template< typename type > constexpr type_qual_id get_type_qualifier_id<          type       && > = type_qual_id::rref                ;
template< typename type > constexpr type_qual_id get_type_qualifier_id<          type const && > = type_qual_id::const_rref          ;
template< typename type > constexpr type_qual_id get_type_qualifier_id< volatile type          > = type_qual_id::volatile_value      ;
template< typename type > constexpr type_qual_id get_type_qualifier_id< volatile type const    > = type_qual_id::volatile_const_value;
template< typename type > constexpr type_qual_id get_type_qualifier_id< volatile type       &  > = type_qual_id::volatile_lref       ;
template< typename type > constexpr type_qual_id get_type_qualifier_id< volatile type const &  > = type_qual_id::volatile_const_lref ;
template< typename type > constexpr type_qual_id get_type_qualifier_id< volatile type       && > = type_qual_id::volatile_rref       ;
template< typename type > constexpr type_qual_id get_type_qualifier_id< volatile type const && > = type_qual_id::volatile_const_rref ;

template< typename from, typename to >
using copy_cv_reference_t = add_qualifier_t< get_type_qualifier_id< from >, to >;

#else
#include <type_traits>

template< typename from, typename to >
struct copy_cv
{

    using type = to;

};

template< typename from, typename to >
struct copy_cv< from const, to >
    : copy_cv< from, to const >
{

};

template< typename from, typename to >
struct copy_cv< volatile from, to >
    : copy_cv< from, volatile to >
{

};

template< typename from, typename to >
struct copy_cv< volatile from const, to >
    : copy_cv< from, volatile to const >
{

};

template< typename from, typename to >
struct copy_reference 
{

    using type = to;

};

template< typename from, typename to >
struct copy_reference< from &, to >
    : copy_reference< from, to & >
{

};

template< typename from, typename to >
struct copy_reference< from &&, to >
    : copy_reference< from, to && >
{

};

template< typename from, typename to >
using copy_cv_reference_t = typename copy_reference< from, typename copy_cv< std::remove_reference_t< from >, to >::type >::type;

#endif

First approach looks slightly more artificial, but provides a "type qualifiers id" as additional side and latter can be useful in some situations. Second approach is inherently two-step one. It could has downsides. In addition, it involve std::remove_reference_t to reveal the cv-qualified type.

On the one hand, I know standard allows for implementations to have an "intrinsic" type traits. On the other hand, there is no the type trait currently in contemporary C++ standard.

What is the best implementation of copy_cv_reference_t type trait? Not only between above two. Are there better approaches to implement it? Is there corresponding proposal?

What about naming? What about order of ids?

Allocating an array in a templated class

The template I'm using is

template<typename T, size_type MAX_DIM = 500>

I am trying to figure out how to allocate correctly. The variable T ** array_ is declared in the constructor. This is what I have right now, but I've tried a few different kinds of syntax to no avail.

array_=new value_type*[dim1_];
    for ( long i = 0u; i < dim1_; i++)
        array_[i] = new value_type[dim2_];

JNI: Bitmap from unsigned char* always null

I would like to pass an image (via jni) from C++ to an android application. I am starting from an unsigned char* array. This array is not corrupted whatsoever; I am even able to save it into a ppm file and display it properly on my laptop.

Then, I convert it to a jByteArray by using this function:

jbyteArray imgByte=as_byte_array(env,imgRaw,img.getRawImageSize());
...
jbyteArray as_byte_array(JNIEnv *env, unsigned char* buf, int len) {
    jbyteArray array = env->NewByteArray (len);
    env->SetByteArrayRegion (array, 0, len, reinterpret_cast<jbyte*>(buf));
    return array;
}

Afterward, I send this jByteArray to the java side. This variable has been properly populated, as I can see by printing its hex values on LogCat:

07-01 18:02:45.941    7017-8238/com.myapp.myapp W/C++ side﹕  798a95798b9677889371838d6b7d8664757e5d6e7860717b5e...
07-01 18:02:46.941    7017-8238/com.myapp.myapp W/Java side﹕ 798a95798b9677889371838d6b7d8664757e5d6e7860717b5e...

The final step would be to show it on an ImageView. To this end, I do the following code (taken from another question on SO):

public void setImageViewWithByteArray(final ImageView view, byte[] data) {
    final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (bitmap==null) {
                Log.e(TAG,"Bitmap is NULL!");
                view.setImageResource(R.drawable.abc_btn_radio_material);
            }
            else {
                view.setImageBitmap(bitmap);
            }
        }
    });
}

but the bitmap variable is always null. What am I doing wrong? Is there a way to debug decodeByteArray?

How to change the value of each elmement in vector using iterator in C++

I wrote the follow program to initialize a vector of Person. But the id of the person objects does not change. This really confuse me. Can somebody give me an explanation?

#include <iostream>
#include <vector>
#include <string>
#include "Person.h"

using namespace std;
int main()
{
    vector<Person>* pv = new vector<Person>(5,Person(0));
    int i = 0;
    for(Person person : *pv)
    {
    person.id = i++;
    }

    for(Person person : *pv)
    {
      cout<< person.id << endl;
    }

    return 0;
}

with person.h like this #include

class Person
{
 public:
  int id;
  std::string name;
  Person(int d);
};

Traversing a binary search tree

I've implmented a basic binary search tree. Here's my node

 #ifndef NODE_H
    #define NODE_H

    template<typename T> class node{

        template<typename E> friend class bst;

        public:
            node():data(0), left(NULL), right(NULL){}
            node(T data):data(data),left(NULL), right(NULL){}   

        private:
            T data;
            node<T>* left;
            node<T>* right;
    };

#endif

And here's my bst.

#ifndef BST_H
#define BST_H

template<typename T> class bst{
    public:
        bst():root(NULL), nodes(0){}
        bst(node<T>* root):root(root), nodes(0){}

        void insert(node<T>* root, const T& data){

            if(root == NULL){
                node<T>* root = new node<T>();
                root->data = data;
                nodes++;
                return;
            }else if(data <= root->data) {
                insert(root->left, data);

            }else if(data >= root->data){
                insert(root->right, data);

            }
        }

        void preorder(node<T>* root){
            if(root == NULL) return;
            std::cout<< root->data<<'\n';

            preorder(root->left);
            preorder(root->right);
        }
    private:
        node<T>* root;
        int nodes;
};
#endif

Here's the calling function

int main(){

    node<int>* root = new node<int>(17);
    bst<int>* t = new bst<int>(root);


    t->insert(root,21);
    t->insert(root,12);
    t->insert(root, 9);

    t->preorder(root);

    delete t;
}

The output is simply 17, which is the root. I feel somehow my insert method hasn't worked right, since the preorder is a pretty standard implementation. Can somebody help me as to what is going wrong here.

How do I limit my output to 40 characters per line without truncating a word in the string?

I am working on an assignment and I have pretty much figured it all out but keep in mind I am not allowed to use arrays nor streams for this program. I must input string data from a file and display 40 characters per line of the data in the file without cutting off any of the words. This part of the problem has stumped me. I am also stumped on how to figure out how to capitalize the first letter of a word if it has symbols attached to the front. I was thinking that the 40 characters per line would work best in my void function for print_text and the capitalization should go in format_text. I have tried my best and was able to successfully capitalize the first letter and make the last letters of each word lower case, but I cannot figure out how to do it if the word has symbols in front (ex. **running)

What I have so far

#include <iostream>
#include <string>
#include <cctype>
#include <iomanip>
using namespace std;
void get_text(string&);
void format_text(string&);
void print_text(string);
int alphacount(string);
double charcount(string);
int consonantcount(string);
int sentencecount(string);
int main()

 {
  string filetext; // Text data input from file                                                                                                                                                                        
  int letters = 0; // amount of letters input from file                                                                                                                                                                
  int words = 0; // amount of words input from file                                                                                                                                                                    
  int sentences = 0; // amount of sentences input from file                                                                                                                                                            
  int consonants = 0;// amount of consonants input from file                                                                                                                                                           
  double amtchar  = 0.0;// amount of characters in file                                                                                                                                                                
  double average = 0.0; // average length of words in file                                                                                                                                                             
  cout << fixed << setprecision (3);
  get_text(filetext); // reads text in file                                                                                                                                                                            
  while (cin)
    {
      words++;
      sentences = sentencecount(filetext) + sentences;
      letters = alphacount(filetext) + letters;
      amtchar = charcount(filetext) + amtchar;
      consonants = ( consonants +   consonantcount(filetext));
      average = amtchar/ words;
      format_text(filetext);// formats text in file correctly                                                                                                                                                          
      print_text(filetext);// outputs data from file                                                                                                                                                                   
      get_text(filetext);
    }

  cout << "# of words: " << words << endl;
  cout << "# of sentences; " << sentences  << endl;
  cout << "# of letters: " << letters << endl;
  cout << "# of consonants: " << consonants << endl;
  cout << "Average word length: " << average << endl;
  return 0;
}

void get_text(string& ftext)
// Given a string of data from a file the function reads the strings and passes                                                                                                                                        
// them back to the calling function.                                                                                                                                                                                  
{
  cin >> ftext;
}

void print_text(string ftext)
// Given the string of text from the file the function displays the contents                                                                                                                                           
// of the file on screen.                                                                                                                                                                                              
{
  cout << setw(40) << ftext << endl;
}

void format_text(string& ftext)
  // Give the string of text from the file the function displays the contents                                                                                                                                          
  // so that the first letter of each word is capitalized and each follow word                                                                                                                                         
  // is lower case.                                                                                                                                                                                                    
{
  int wlength;// length of the word inputted from the file                                                                                                                                                             
  wlength = ftext.length();
  if (isalpha(ftext[0]))
  ftext[0] = toupper(ftext[0]);
  for ( int i=1; i < wlength; i++)
    ftext[i] = tolower(ftext[i]);

}

int alphacount(string filetext)
// will count the amount of alphabetical letters in the data file                                                                                                                                                      
{
  int lettertotal = 0; // total amount of letters in the datafile                                                                                                                                                      
  for (int i = 0; i < filetext.length(); i++)
      if ( isalpha(filetext[i]))
         lettertotal++;
         return lettertotal;
}


double charcount(string filetext)
// will calculate the amount of characters within the file and return to                                                                                                                                               
// main file                                                                                                                                                                                                           
{
  int numofchars = 0;// number of characters within file                                                                                                                                                               
  int sum = 0;// variable to determine exact amount of characters                                                                                                                                                      
  for (int i = 0; i < filetext.length(); i++)
    {
    if ( filetext != " ")
      numofchars++;

    }
  sum = sum + numofchars;
  return sum;
}

int consonantcount(string filetext)
// will determine amount of consonants  within the datafile and return to                                                                                                                                              
// main function                                                                                                                                                                                                       
{

char letter; // each alphabetical character in data file                                                                                                                                                             
  int vowelcounter=0;// number of vowels within data file                                                                                                                                                              
  int constotal = 0;// number of consonants within data file                                                                                                                                                           
  for (int i = 0; i < filetext.length(); i++)
    {
      letter = toupper(filetext[i]);
      switch(letter)
        {
          case 'a':
          case 'e':
          case 'i':
          case 'o':
          case 'u':
        case 'A':
        case 'E':
        case 'I':
        case 'O':
        case 'U':
            vowelcounter++;
          break;
        }
      if  ( isalpha(filetext[i]))
        constotal++;
    }
  constotal = constotal - vowelcounter;
  return constotal;
}


int sentencecount(string filetext)
// Will count the number of sentences within the data file and return to the                                                                                                                                           
// main function                                                                                                                                                                                                       
{
  int sentcount = 0; // amount of sentences within file                                                                                                                                                                
  for (int i = 0; i < filetext.length(); i++)
    {
      if (filetext[i] == '.' || filetext[i] == '?' || filetext[i] == '!')
        sentcount++;
    }
  return sentcount;
}

Halide hangs during Normalized Cross Correlation

I'm trying to implement normalized cross correlation in Halide.

The code below builds, and Halide JIT compilation doesn't throw any errors. However, Halide seems to hang after JIT compilation. No matter how many trace_* calls I put on different Funcs, only one trace ever prints (on Func output):

Begin realization normxcorr.0(0, 2028, 0, 2028)
Produce normxcorr.0(0, 2028, 0, 2028)

Any advice at all would be helpful.

This algorithm is meant to be equivalent to CV_TM_CCOEFF_NORMED in OpenCV, and normxcorr2 in MATLAB:

void normxcorr( Halide::ImageParam input,
                Halide::ImageParam kernel,
                Halide::Param<pixel_t> kernel_mean,
                Halide::Param<pixel_t> kernel_var,
                Halide::Func& output )
{
    Halide::Var x, y;
    Halide::RDom rk( kernel );

    // reduction domain for cumulative sums
    Halide::RDom ri( 1, input.width() - kernel.width() - 1, 
                     1, input.height() - kernel.height() - 1 );

    Halide::Func input_32( "input32" ),
             bounded_input( "bounded_input"),
             kernel_32( "kernel32" ),
             knorm( "knorm" ),
             conv( "conv" ),
             normxcorr( "normxcorr_internal" ),
             sq_sum_x( "sq_sum_x" ),
             sq_sum_x_local( "sq_sum_x_local" ),
             sq_sum_y( "sq_sum_y" ),
             sq_sum_y_local( "sq_sum_y_local" ),
             sum_x( "sum_x" ),
             sum_x_local( "sum_x_local" ),
             sum_y( "sum_y" ),
             sum_y_local( "sum_y_local" ),
             win_var( "win_var" ),
             win_mean( "win_mean" );

    Halide::Expr ksize = kernel.width() * kernel.height();

    // accessing outside the input image always returns 0
    bounded_input( x, y ) = Halide::BoundaryConditions::constant_exterior( input, 0 )( x, y );

    // cast to 32-bit to make room for multiplication
    input_32( x, y ) = Halide::cast<int32_t>( bounded_input( x, y ) );
    kernel_32( x, y ) = Halide::cast<int32_t>( kernel( x, y ) );

    // cumulative sum along each row
    sum_x( x, y ) = input_32( x, y );
    sum_x( ri.x, ri.y ) += sum_x( ri.x - 1, ri.y );

    // sum of 1 x W strips
    // (W is the width of the kernel)
    sum_x_local( x, y ) = sum_x( x + kernel.width() - 1, y );
    sum_x_local( x, y ) -= sum_x( x - 1, y );

    // cumulative sums of the 1 x W strips along each column
    sum_y( x, y ) = sum_x_local( x, y );
    sum_y( ri.x, ri.y ) += sum_y( ri.x, ri.y - 1);

    // sums up H strips (as above) to get the sum of an H x W rectangle
    // (H is the height of the kernel)
    sum_y_local( x, y ) = sum_y( x, y + kernel.height() - 1 );
    sum_y_local( x, y ) -= sum_y( x, y - 1 );

    // same as above, just with squared image values
    sq_sum_x( x, y ) = input_32( x, y ) * input_32( x, y );
    sq_sum_x( ri.x, ri.y ) += sq_sum_x( ri.x - 1, ri.y );

    sq_sum_x_local( x, y ) = sq_sum_x( x + kernel.width() - 1, y );
    sq_sum_x_local( x, y ) -= sq_sum_x( x - 1, y );

    sq_sum_y( x, y ) = sq_sum_x_local( x, y );
    sq_sum_y( ri.x, ri.y ) += sq_sum_y( ri.x, ri.y - 1);

    sq_sum_y_local( x, y ) = sq_sum_y( x, y + kernel.height() - 1 );
    sq_sum_y_local( x, y ) -= sq_sum_y( x, y - 1 );

    // the mean value of each window
    win_mean( x, y ) = sum_y_local( x, y ) / ksize;

    // the variance of each window
    win_var( x, y ) =  sq_sum_y_local( x, y ) / ksize;
    win_var( x, y) -= win_mean( x, y ) * win_mean( x, y );

    // partially normalize the kernel
    // (we'll divide by std. dev. at the end)
    knorm( x, y ) = kernel_32( x, y ) - kernel_mean;

    // convolve kernel and the input
    conv( x, y ) = Halide::sum( knorm( rk.x, rk.y ) * input_32( x + rk.x, y + rk.y ) );

    // calculate normxcorr, except scaled to 0 to 254 (for an 8-bit image)
    normxcorr( x, y ) = conv( x, y ) * 127 / Halide::sqrt( kernel_var * win_var( x, y ) ) + 127;

    // after scaling pixel values, it's safe to cast down to 8-bit
    output( x, y ) = Halide::cast<pixel_t>( normxcorr( x, y ) );
}

Any better ways to do calculations using each 2 elements in a vector

I have a very time consuming function, which needs to so some calculation using each 2 elements in a std::vector. The way I am doing now is,

std::vector<int> vec;
for (auto it = vec.begin(); it != vec.end(); ++ it)
  for (auto it2 = vec.begin(); it2 != vec.end(); ++ it2)
    if (it2 != it)
      f(*it, *it2) // the function

I am wondering if there are any other better ways to do this, because this process cost too much time.

Besides, I have tried to use OpenMP to parallelize the outer loop, it works fine when I use std::vector, but if I do similar things with std::map, it returns a segmentation fault.

Thanks.

C++ array to Halide Image (and back)

I'm getting started with Halide, and whilst I've grasped the basic tenets of its design, I'm struggling with the particulars (read: magic) required to efficiently schedule computations.

I've posted below a MWE of using Halide to copy an array from one location to another. I had assumed this would compile down to only a handful of instructions and take less than a microsecond to run. Instead, it produces 4000 lines of assembly and takes 40ms to run! Clearly, therefore, I have a significant hole in my understanding.

  1. What is the canonical way of wrapping an existing array in a Halide::Image?
  2. How should the function copy be scheduled to perform the copy efficiently?

Minimal working example

#include <Halide.h>

using namespace Halide;

void _copy(uint8_t* in_ptr, uint8_t* out_ptr, const int M, const int N) {

    Image<uint8_t> in(Buffer(UInt(8), N, M, 0, 0, in_ptr));
    Image<uint8_t> out(Buffer(UInt(8), N, M, 0, 0, out_ptr));

    Var x,y;
    Func copy;
    copy(x,y) = in(x,y);
    copy.realize(out);
}

int main(void) {
    uint8_t in[10000], out[10000];
    _copy(in, out, 100, 100);
}

Compilation Flags

clang++ -O3 -march=native -std=c++11 -Iinclude -Lbin -lHalide copy.cpp

QPixmap load segmentation fault

I am creating a Qt Console Application on windows 7. I am using Qt 5.3. And currently I have error that make me frustration because of it. Already check on the stackoverflow, but no answers help me.

My problem was when creating a Qpixmap I got error segmentation fault and I don't have any other error information about it.

Here my code :

QString filePath = (directory + xmlReader.attributes().value("relativepath").toString());
QFile _file(filePath);
if (!_file.exists())
{
    qWarning() << "Error : file " << filePath << " does not exist";
    return false;
}

QImageReader imageReader(filePath);
QImage mainImage = imageReader.read();
if(mainImage.isNull())
{
    qWarning() << "Error read image : " << filePath;
    qWarning() << imageReader.errorString();
    return false;
}
QPixmap mainPixmap(QPixmap::fromImage(mainImage));

On the last line of those code that generate the segmentation fault error on my machine. Is there anything i can do to debug this error?

Store pointer to map key

std::map<Key,Value> mymap;
(void)mymap[Key(...)]; // create value if not there
typename std::map<Key,Value>::iterator it = mymap.find(key);
it->second.pkey = &it->first; // store a pointer to the actual key

Is this safe? In other words, is map allowed to copy the key around during insert/erase operations, which would invalidate Value::pkey?

Any C++98 vs C++11 differences on this?

Protocol Buffer: How to print the contents of a field of type 'byte' as hex string?

Is there a way to specify that the Printer class prints fields of type byte as hex string instead of as a byte array (in C++)? (For reference, see the photo and program in this answer - notice the output is a byte array).

C++ and Java Learn Online for Free. Anybody knows a good and efficient website?

I am wondering if you could suggest some websites that offer free lesson in C++ or Java. I cannot afford going into school and such to learn more. Thanks in advance guys!

Is it possible to define a Stan model in terms of an arbitrary posterior function?

Is it possible to define a Stan model in terms of an arbitrary posterior function?

I'm thinking something like MCMCPack's MCMCmetrop1R() functionality where the user defines an arbitrary posterior function. I would be fine with digging into the C++ API to do this if there's a good example of how to go about it.

Running external executable in Qt using QProcess

I'm trying to run an external executable (code below) in Qt as a separate process.

test.c:

#include <stdio.h>
int main () {
    FILE *f;
    f = fopen("a.txt", "w");
    fprintf(f, "1\n");
    fclose(f);
    return 1;
}

and in Qt I have:

QProcess* process = new QProcess();
QString program = "/Users/myUser/Desktop/a.out";
process->execute(program);

I've read up on the differences between execute(), start(), and startDetached() and to my understanding I want to use execute() because I want the process running the external executable to finish before continuing execution in the main process. However I've tried all three expecting to find a file a.txt containing the text "1" in it, but it doesn't exist. Any help or suggestions as to why it's not working? Thanks!

Transform and accumulate with C++11

Coming from Python I wonder if C++ nowadays has some good functional things there are in Python.

Currently I am trying to figure out how to produce a sum of some elements using indexes instead. For example with Python I would:

a = [ ... ]
b = [ ... ]

sum(map(lambda i: a[i] * 2 - b[i + 1], range(len(a)))

So here I generate a new array where each element is determined by some index arithmetic.

In STL there are transform and accumulate, but they take iterators as arguments. This would be OK if only on each step I needed to change a concrete element. Here I need to use index.

Also with transform I have to specify the array I need to put the results to. Is there a way the resulting array could be generated on the fly and then returned? Something like Python's map does.

Because in such case it's really easier to write a simple for-loop.

i find it difficult to only allow numbers tried different methods and failed can anyone show me how its done

include

void main(void){

You are required to write a c program to find how many numbers are greater than the entered value between 1 and a user entered upper limit. for example, if you enter the value 15 as the upper limit and 7 as your number, then the program must give the output as 8.

The program output must be as shown below.

Enter an upper limit : 15 Enter a number between 1 and 15 : 7 ==> there are 8 numbers greater than 7 Do you want to check more values? (y/n)

if typed Y, clear the screen and prompt user to re-enter the upper limit and a number, and if typed n, end the program.

}

// can anyone help me in completing this? with the correct error messages and allowing only numbers to be input!

indirection requires pointer operand and expected expression errors

I keep getting errors similar to these:

pitstop.cpp:36:23: error: indirection requires pointer operand

        ('double' invalid)

         cost = UNLEADED * gallons;

                          ^ ~~~~~~~

pitstop.cpp:40:14: error: expected expression

                    cost = SUPER * gallons;                               ^


#include <iostream>
#include <iomanip>
using namespace std;

#define UNLEADED 3.45;
#define SUPER {UNLEADED + 0.10};
#define PREMIUM {SUPER + 0.10};

/* 
    Author: Zach Stow
    Date: 
    Homework 
    Objective:
*/

double cost, gallons;
string gasType, finish, stop;

int main()
{
    for(;;)

    {

        cout <<"Hi, welcome to Pitstop.\n"; 
        cout <<"Enter the type of gas you need:";
        cin >> gasType; 
        cout << endl;

        cout <<"Enter the amount of gallons you need:";
        cin >> gallons;
        cout << endl;

        if(gasType == "finish" || gasType == "stop")break;

        else if(gasType == "UNLEADED")
        {
            cost = UNLEADED * gallons;
        }
        else if(gasType == "SUPER")
        {
            cost = SUPER * gallons;
        }   
        else if(gasType == "PREMIUM")
        {
            cost = PREMIUM * gallons;
        }

    }   
    cout <<"You need to pay:$" << cost << endl;

    return(0);

}

Make template function for nested container

I'm trying to make a generic test function that takes a container such as list, set or vector, and returns nested container: list of lists, set of sets, vector of vectors. Non-generic functions look like this:

vector<vector<string>> test(vector<string>& in_container)
{
    vector<vector<string>> out_continer;

    // out_continer will be filed using values from in_container

    return out_continer;
}

list<list<int>> test(list<int>& in_container)
{
    list<list<int>> out_continer;

    // out_continer will be filed using values from in_container

    return out_continer;
}

set<set<float>> test(set<float>& in_container)
{
    set<set<float>> out_continer;

    // out_continer will be filed using values from in_container

    return out_continer;
}

But I dont know how to make one template test function that would be equivalent to these separate test examples.