mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is a huge design issue. I will try my best to keep it brief. I will go from worse to best options, in my humble opinion (from experience in making a few simple computer games and having incrementally implemented a better solution each time).

Global variables are horrible.. even POD-types. Try to avoid them at all costs. They are a very very last resort. Philosophically, the motivation is that in OOP, you want objects to encapsulate the state of the application. This way you implement each class such that they maintain a valid and working state (except in error-states, where they should be duly reported or logged). If you have global variables, your application has a state that is independent of its objects and it becomes a nightmare to keep it stable because now all classes have to be implemented to preserve some ill-defined application state. Now, global _constants_ are much different. If you need a bunch of values like some physical constants (e.g. gravity or Plank's constant) or mathematical constants (e.g. Pi or e), they don't define the state of the application since they don't change, so you can safely use global constants to store those values (but make sure they are POD though). To avoid name-clashing, split them up into their most suited namespaces.

Singletons are not nice and should be avoided. But for some purposes, they are really the only solution. As for the implementation, there have been a few prior posts with suggestions, …

jonsca commented: Excellent +6
kerp commented: Great post +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

An HMM is just a model, not an algorithm. What is the task you want to accomplish? Feature detection, object tracking, mapping, compression, etc. ?

Your best bet when it comes to vision stuff is OpenCV. If this library does not have the algorithm or method you want, chances are that you will have a hard time finding a good implementation of it elsewhere. You might not find HMM mentioned too much anywhere there because, for many methods, it is, implicitly, the underlying model and thus it is not even worth mentioning.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Line 21 should be:

return sum (num->next, s*10+num->value); //value, not data.

Other than that, I think it should work and do what it is supposed to do. Please give specific errors that the code produces.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Fundamentally, a running application is made of data and processes to manipulate that data. A program to solve a problem is made of sub-programs to solve the sub-problems. OOP is just merging those two realities by bundling data and the related functions in one entity (an object) that serves to solve a sub-problem using _only_ the data relevant to this sub-problem. That is the one thing to understand correctly, the rest (encapsulation, abstraction, polymorphism, and various idioms) is accessory.

1. How is the code re-usable in OOP ?
It very often happens that sub-problems come back again and again in application development. If classes are programmed well, methods use only the data members of the object used to solve the sub-problem. Code is re-usable because if the sub-problem is properly abstracted in the code, the code can be reused to solve the same sub-problem in different application contexts. Of course, bad OOP is not re-usable, and good procedural programming is just as modular. But one could argue that good procedural programming is often just a basic form of OOP and no longer (pure) procedural programming. Remember that OOP is a paradigm that is only facilitated by C++ or Java, but can be done in (any) language like C or fortran. Finally, you will find that most aspects of OOP that are usually emphasised, like encapsulation, abstraction, polymorphism, and a plethora of idioms, are usually all aimed, in one way or another, at promoting independence between classes and objects …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your question is too vague and I think arkoenig and firstPerson's answers are quite good instructions for the "generic" small-code performance testing and optimization.

Overall, people usually talk about three levels of optimization: macro-, micro-, and nano-optimization. You want to proceed through them in that order. Macro-optimization is about defining the software architecture that properly splits memory and processing, this is done before you program a single line of code! This is like the first and second step that arkoenig posted. It is by far the most important because it is the hardest to fix and the hardest to measure. You have to really make sure you understand the problem you are trying to solve and that you are able to divide the problem into subproblems that are as independent from each other as possible. When your input/outputs are well attributed and thought-out for each subproblem, and that you managed to get a good, clean separation of memory between the subproblems (memory locality is a big factor in running speed), then the software architecture (what classes or functions you will make and in which libraries they will be put) follows quite naturally. If you screw up at this stage, you are in trouble, because down the line, if you find it to be inefficient, you might have to start the whole thing from scratch.

The second step is micro-optimization. Once you have coded all your functions and classes in the most straight-forward way that works correctly, then you …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are several options for this problem (which is quite usual in numerical simulation code.. where to put the simulation parameters?). I could suggest two that seem to stick out for me:

1) Make a POD-style class (e.g. C-struct) that has all the parameters:

struct SimulationSettings {
  a, b, c;
};

Then have the class A take a const reference to a SimulationSettings structure and hold this reference as a data member. This way, you can associate all the instances of A to a single set of SimulationSettings. To speed things up a bit, try to reduce the use of the simulation parameters or make a more local copy of it (increase memory usage to reduce time taken at dereferencing). In my own experience, I don't think you will have to worry about this too much at the computational level (do the profiling, as suggested). The nice feature of this solution is that you are not directly tying the implementation of class A to the implementation of class SIMULATION (as you would if you had a pointer or reference to SIMULATION in the class A).

2) It might not be appropriate for all settings and stuff, but have you considered using template parameters? For example:

template <double a, double b, double c>
class A {
  A();
};

template <double a, double b, double c>
class SIMULATION {
  vector< A<a,b,c> > array;
};

This way, you have ZERO run-time overhead (memory or time). The drawback is that …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Please don't do what AD suggested (sorry AD..)! That is dangerous, unstable, and bad style. Unless the classes are all POD classes without virtual methods, this saving method will crash when you try to load the file again.

What you are trying to do is called serialization. There are several ways to do it, from the crudest to the most sophisticated. One, most sophisticated method, would be that of the Boost.Serialization library. While the crudest method (that also requires the least amount of C++ skill) is to simply have a save and load method in each of your classes:

#include <fstream>
using std::ofstream;
using std::ifstream;

class A
{
   // blabla
  public:
    void save(ofstream& outfile) const {
      outfile.write(&data_member1,sizeof(data_member1));
      //.. and so on for all data members.
    };
    void load(ifstream& infile) {
      infile.read(&data_member1,sizeof(data_member1));
      //.. and so on for all data members (same order as in the save method).
    };
};

class B
{
   // blabla
  public:
    //.. save & load, as for A
};

class C
{
   // blabla
  public:
    //.. save & load, as for A
};

int main()
{
   A a;
   B b;
   C c;

   // now save the data
    ofstream file_ptr; // Declares a file pointer.
    file_ptr.open(“house.dat”, ios::out); // Creates the file.
    if (!file_ptr)
    { cout << “Error opening file.\n”; }
    else
    {
    // Rest of output commands go here.
       a.save(file_ptr);
       b.save(file_ptr);
       c.save(file_ptr);
          
    }
}

In the above implementation, if you have any data members which are of a class, then you would call its …

jonsca commented: Nice post. +6
gerard4143 commented: Very interesting point Mike..Oops forgot about the vtables and vdestuctors +4
Ancient Dragon commented: Correct +34
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here is how it should work:

void expand() {
        int oldlen = actual_len;
        actual_len += increment;
        DynamicType* temp = new DynamicType[actual_len];
        DynamicType* temp_begin = temp;
        data = data_begin;
        for (int i = 0; i < oldlen; i++) {
            temp->what_type = data->what_type;
            if (temp->what_type == temp->is_int)
                temp->integer = data->integer;
            else if (temp->what_type == temp->is_string)
                temp->string = data->string;
            temp++;
            data++;
        }
        delete[] data_begin; //notice this line has changed
        data = temp;
        data_end = temp;
        data_begin = temp_begin;
    }

Since you are allocating an array, you should use the delete[] operator (not just "delete"). Also, since you have been incrementing data up to the end of the "oldlen", you need to delete the original pointer, i.e. "data_begin".

Note: typically, these dynamic arrays are implemented by doubling the capacity every time you need an expansion (not using a fixed increment). Algorithmically, it makes no sense to use a fixed increment for the capacity because it's not scalable. If your program ends up needing 18 elements in the array, you will require 2 memory re-allocations and copy (instead of 18 if you keep only the exact number of elements needed). However, if your program needs one million elements, then you will require 100,000 reallocations (that is only a 90% improvement). If you grow the array size by a factor of 2 each time you need more space, you end-up needing at most 20 reallocations, that's much better!

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>each one has its own version of a "project system"
This is why I emphasized the importance of IDEs being well integrated to build systems. Personally, I use cmake to manage the builds (release, debug, and all the configurations). By using a build system that is independent of the IDE, you get the benefit of not having to tweak the configurations for each IDE and/or OS you are building your project on. There are other build systems besides cmake that are either for one platform or cross-platform, but I find that cmake is the easiest to use. When using an IDE, you can (if the IDE integrates cmake) import the cmake configuration and have the IDE rely on that system instead of its own "project system", this makes it a lot easier to use multiple IDEs and to program for different platforms.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You should get rid of lines 9 to 13 in sql.h. Do not import namespaces in a header file! You are polluting the name space and you run into the risk of name clashes. When someone includes your header file in their project, all of a sudden, they have imported five huge namespaces without knowing it... that is very bad.

Other than that, as David said, "worked" is undefined, because it is not declared anywhere that I can see in the code you posted. Usually, compilation error messages are accurate, if it says "undeclared", look for the declaration of it, if you can't find it, you have a problem. Using a variable that you haven't declared is usually either a sign of misunderstanding of the scope of the variables you declare, or just some vestige of successive coding trial-and-error that left trash variables around (either declared but not used or used but not declared)... or a sign that you have no idea what you are doing (hopefully you are not in the latter case).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

From OpenGL: "If a non-zero named buffer object is bound to the GL_ARRAY_BUFFER target (see glBindBuffer) while a vertex array is specified, pointer is treated as a byte offset into the buffer object's data store."

So the value "2*sizeof(GLfloat)" is correct, but the type is wrong (it's just an awkward way to allow you to pass an actual pointer instead of a byte offset). To fix it:

glVertexPointer(3, GL_FLOAT, 5*sizeof(GLfloat), reinterpret_cast<GLvoid*>(2*sizeof(GLfloat)));
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Hey David! I know you solved it, but if you want a more generic solution, I can suggest something. This case is a very good example of when traits can be very useful.

Consider this:

//define a type trait for images:
template <class T>
struct image_trait {
  typedef typename T::Pointer Pointer;
  struct PixelType {
    typedef typename T::PixelType::Type Type;
    static T::PixelType::Type Zero() { return T::PixelType::Zero(); };
  };
};

//specialize the trait for a primitive image (like unsigned char*)
template <>
struct image_trait<unsigned char*> {
  typedef unsigned char** Pointer;
  struct PixelType {
    typedef char Type;
    static char Zero() { return 0; };
  };
};

//then, you can have one function template that will work for all image types that have an appropriate image_trait (either the generic one or a specialization)
template <class T>
void CreateBlankPatch(typename image_trait<T>::Pointer patch, unsigned int sideLength)
{
  CreateConstantPatch(patch, typename image_trait<T>::PixelType::Zero(), sideLength);
}

This is how STL implements a lot of things. Like for iterators, all the STL algorithms can also work for pointer instead because, internally, they always go through a iterator_trait template to know the value type, reference type, etc., and a few specialization for pointers (like T*) make the STL algorithms compatible with them (or any other custom iterator you could come up with, as long as you provide a valid iterator_trait for it).

StuXYZ commented: Short simple post on Traits: Thx +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Basically, a constant (like "const int some_constant_value = 42;"), whether it is at global scope, namespace scope, or a static data member, has to be assigned to a value that can be resolved at compile-time regardless of when it is initialized.

So, this excludes any variable that is not also a constant. It only allows literal values or other constants, and simple arithmetic operations on literal values and/or other constants. And also #defines, but those are evil.

In the example you gave, since a vector (I'm assuming not a static array) only has a size that can be know at run-time, because it has to be initialized (i.e. created) before it has a known size, and objects only get created at run-time. So, in order to have another array or vector whose size depends on the size of that other vector, it will have to be created at run-time (as firstPerson suggested, using dynamically allocated memory).

If you are talking about the special case where you have a static array (fixed-size, known at compile-time) and you simply want to create another static array of the same size, but you don't want to use a global constant for it, there is a little trick that can be used, but it is not so pretty:

int array1[10]; //say you have this static array, with a "magic number" for its size.

//you can use the sizeof() operator to get the total size in bytes of a _static_ array (only …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here is what my eagle eye has found:

At line 17 of holding.cpp
At line 26 of book.h
At line 30 of record.h

In all those cases, you have the same misplaced parenthesis:

//you wrote:
title = new char[strlen(Hold.getTitle() + 1)];
//when it should be:
title = new char[strlen(Hold.getTitle()) + 1]; //notice the displaced closing parenthesis.

That would certainly explain the fact that it crashes not all the time, because this just introduces a few bytes of misalignment (writing memory where it shouldn't) and often it's not enough to cause a crash.

Save yourself all that trouble with copying C-strings, by using the C++ string class instead, like you do already in main().

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Isn't glBegin depracted?
You're right. I have to admit that my knowledge of OpenGL dates back a few years (version 2.0 was the latest I had worked with). I had just assumed that you meant deprecated as in being undesirable. glBegin/glEnd style commands have always been "ugly" and slow, and rarely useful because VBO (or just "vertex buffers" as they used to be called) are much more generic and once you use them, there is no point for glBegin/glEnd structures anymore. So, you're right, you shouldn't use the second example I posted, because it appears that display lists are also deprecated (and nothing equivalent exists anymore, which is a shame because they were nice and very fast if the hardware supported it well).

>>So the memory leak might be a natural growth of the heap?
>> ... going 4 K per second and after a while it stops. Is this supposed to happen?
Ok, so, the "heap" is the entity from the OS that dynamically allocates memory (new/delete, malloc/free). To do that, it manages a chunk(s) of RAM that the OS gives to the heap dedicated to your application. The more you request memory from the heap, the more the heap has to request from the OS. But when you free memory (as you should), you create "holes" at random places inside the heap's memory. In subsequent allocations of memory, the heap will try and reuse those holes, but if it doesn't find a hole that …

DaSpirit commented: Really helpful, nice guy. +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think it depends on your level of skill and what kind of projects you do. I can only give you my perspective on the ones that I am familiar with:

Eclipse: I had to use it for a class (in Java) and have used the C++ version a little bit too. I think it is too simplistic, which is probably good for a beginner and that's probably why profs often suggest it. It is poorly integrated with external build systems, it is too intrusive, it's code completion sucks, it is poorly integrated to GUI programming, but it's free!

VC++: It's not cheap (unless your company uses it or you have some student discount, like MS e-academy). It is certainly very complete but also quite complex. I was surprised at how poorly integrated it is with build systems (but maybe I just don't know enough about VC++, I just know I had trouble with this). In VC++ 2008, the code completion is really slow and often useless, but I think it is better in 2010, which I haven't used much. Apparently the code refactoring utilities are really good too in the 2010 edition (I don't think the Express edition has it though). I think the main problem with VC++ and many other MS products is that it is very heavy weight (basically, a Code Blocks install is less than 100 MB, while MSVS is like 6 GB or something ridiculous like that). I also despise the rigid integration …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I don't know about the memory leak (I would assume it is just a natural growth of the heap.. wouldn't worry about it too much).

What you are rendering is so trivial that you probably don't need VBOs (they are more critical when rendering meshes, e.g., a large complex model). Here is how to do it anyways:

GLuint vbo_ids[2];
  glGenBuffers(2,vbo_ids); //generate two buffers.
  
  //create arrays that store the points and colors for first geometry:
  GLfloat points1[] = {400.0, 160.0, 320.0, 440.0, 480.0, 440.0};

  glBindBuffer(GL_ARRAY_BUFFER, vbo_ids[0]);
  glBufferData(GL_ARRAY_BUFFER, 6*sizeof(GLfloat), points1, GL_STATIC_DRAW);
  
  //repeat for second geometry... you can also intertwine the data:
  GLfloat buf2[] = { 0, 0,  //tex-coord 1
                     100.0, 100.0, 0.0, //vertex 1
                     0.5, 0, //tex-coord 2
                     228.0, 100.0, 0.0, //vertex 2
                     0.5, 1, //tex-coord 3
                     228.0, 228.0, 0.0, //vertex 3
                     0, 1, //tex-coord 4
                     100.0, 228.0, 0.0 }; //vertex 4

  glBindBuffer(GL_ARRAY_BUFFER, vbo_ids[1]);
  glBufferData(GL_ARRAY_BUFFER, 20*sizeof(GLfloat), buf2, GL_STATIC_DRAW);

  while (!done)
  {
    SDL_Event event;
    while (SDL_PollEvent(&event))
    { //.. let's skip this stuff.. just to make it cleaner for the example...
    }

    glClear(GL_COLOR_BUFFER_BIT);

    glColor3f(1.0f,1.0f,1.0f);

    glBindBuffer(GL_ARRAY_BUFFER,vbo_ids[0]);
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(2, GL_FLOAT, 0, 0);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableClientState(GL_VERTEX_ARRAY);

    glEnable( GL_TEXTURE_2D );
    // Bind the texture to which subsequent calls refer to
    glBindTexture( GL_TEXTURE_2D, ret );
 
    glEnable (GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glColor3f(1.0f,1.0f,1.0f);

    glBindBuffer(GL_ARRAY_BUFFER, vbo_ids[1]);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glVertexPointer(3, GL_FLOAT, 5*sizeof(GLfloat), 2*sizeof(GLfloat));
    glTexCoordPointer(2, GL_FLOAT, 5*sizeof(GLfloat), 0);

    glDrawArrays( GL_QUADS, 0, 4);

    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glDisable( GL_TEXTURE_2D );
    glDisable (GL_BLEND); 
    glClearColor(0.7f, 0.9f, 1.0f, 1.0f); //remark: this only needs to be set once.

    SDL_GL_SwapBuffers();
    SDL_Delay(1000/30);		
  }

But, actually, for your application, …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

1) The reason why it doesn't run on your compiler but runs on the prof's compiler (or test thing) is that the value of "num" is not initialized. At line 7, it creates an int called "num" with no initial value, so the value of num could be anything when the while loop is entered. It just happens to be that your compiler makes "num" zero to start with and thus, your program stops right away. Your prof's compiler just doesn't do that (which is the "correct" behavior for a compiler... yours is weird). To fix it, just give a dummy non-zero initial value for "num" (like -1 or 231431 or whatever) before you enter the while loop.

2) The reason why it doesn't stop immediately when 0 is entered is because the condition of the while loop is only evaluated when the execution comes back to the start of the loop. So, when you enter 0, it will finish executing the loop until line 22 and then come back to like 10, evaluate the condition, and skip to the end of the loop (line 23). If you don't want that last time table to get printed, you should rearrange your while loop such that the condition is evaluated right after the input of "num".. I'll let you figure out how to do that.

3) A minor omission as well, you need to "return 0;" from the main function. Just insert "return 0;" between line 22 and 23.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I've never seen how does type int look like?
Neither did I. int is a primitive or built-in type. This means you won't find anywhere in the standard libraries an actual definition of int (like "class int { ... }") because the definition of the type is built into the compiler. Since classes are defined as containing data of other types, there has to be some starting types that are built-in otherwise there would be nothing to build other classes from, and these types are called primitives (int, float, char, double, bool, short, etc., etc.).

>>May someone give me a introduction to type int?
The type int stores an integer number (i.e. 1, 2, 3, 29, 342, etc... no floating point values or characters). It has a sign bit as well so negative numbers can be represented too. You can perform arithmetic operations on it (like +, -, *, /, etc.) and a few other math functions (like pow). It length in bytes varies from one system to another but mostly it is 4 bytes on 32bits systems and 8 bytes on 64bits system. I don't know what else to say about it.

>>Is my idea correct about above operators?
I think the point of this exercise is only to get you to know how to overload operators. This wiki will tell you all you need to know about that. In real life, it would be completely retarded to actually do this, but …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

With GLUT you cannot enforce a fixed time-step or frame rate because GLUT controls (partially) when the frames get rendered. I assume you have a rendering function which performs all the calculation for one frame and renders it. I assume also that your animation is stepping forward in "virtual time" one equal step at each render pass. This is no good when your frame-rate changes overtime. With GLUT, you cannot use the technique of waiting at the start of your render function for "1/60" of a second to have passed since the last render before rendering, because that will overwhelm GLUT who will be stacking up "ON_MOUSE_MOVE" events and that will cause you application to be "not responding" and a typical user of your game would hit ctrl-alt-delete after a few seconds of playing your game. Basically, this fixed frame rate technique is only applicable if you are not using a windowing system that triggers the rendering of your scene. Fortunately, all you need to do is instead of forcing each tick to take 1/60 of a second, you simply don't perform a tick if 1/60 seconds has not passed yet. This will give you a constant tick. However, as pointed out in the SO thread you linked to, the ideal implementation does not require a fixed frame-rate but either takes the frame-rate into account when updating the scene and hence adapts to it, or is completely independent of the frame-rate (multi-threaded, one thread renders on demand and another updates …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Wait a minute... what learning algorithm are you actually implementing? Your code looks like nothing I can recognize. Are you trying to implement this formula:

T_{ij}^{\rm new} = T_{ij}^{\rm old} + M_i^{\rm new}M_j^{\rm new}

This formula is a simple sum. You need to first initialize all weights to zero. Then you have three nested loops (M is the number of patterns and N is the number of neurons):

for each pattern m of M
  for each neuron i of N
    for each weight j of N
       w[i*N+j] += p[m*N+j]*p[m*N+i];

And that's it.. hence my earlier comment about this implementation being trivial.

If it is another algorithm you are implementing, please post the details or at least a link to a page describing it.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The ellipsis is an oddity of C++. As said by sean, it can be used for having a variable number of parameters to a function (called variadic parameters). Also, it can be used (as in the try catch example above) to accept any parameter (as in catching any and all exceptions). For the most part, this keyword should be avoided as it is usually bad design and requires care when using it. It does find more usefulness in certain template meta-programming techniques or to provide a default overload for a function. But, basically, I cannot recall a single place where I have used it in the past, and that's a good thing.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Guarding the header is enough, it guarantees that the header's definitions only appear once. So having a guard inside a guard is useless (not incorrect per se, but useless).

You have to soften your coding standards. Most rules are not that strict, as Sutter and Alexandrescu already point out in their introduction. You are taking a basic guideline of trying to avoid using #defines (because they are harder to maintain and can cause name clashes) to an extreme. You see, the C++ standard committee bends this rule for certain trivial stuff like "NULL" or "TRUE/FALSE", that should tell you that it is totally fine for these universal constants that cannot be mistaken for something else and will never change.

The most blatant coding standard that you are violating here is the fact that you are including headers that are not useful because you assume that any other library that uses your header will also use windows. That breaks rule 23 of the book and is also against the philosophy of rule 59. If you have a bundle of header files that very often all need to get included in many of your other h or cpp files, you can always make a separate header file like "headers_for_this_purpose.h" where you include the bundle of headers (and guard this header too, of course).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The stuff after the colon is the initialization list. Basically it allows you to initialize the values of data members of a class via their constructors instead of their assignment operator (within the body of the constructor). It is just a bit simpler syntax and also more efficient, so it is a good idea to get used to it. In terms of what it does the following two constructors have the exact same effect:

PhoneRecord(const std::string& aLastName = "",const std::string& aFirstName = "",const std::string& aPhoneNumber = "") : last_name(aLastName), first_name(aFirstName), phone_number(aPhoneNumber) { };

 PhoneRecord(const std::string& aLastName = "",const std::string& aFirstName = "",const std::string& aPhoneNumber = "")
{
   last_name = aLastName;
   first_name = aFirstName;
   phone_number = aPhoneNumber;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you pay attention to this sentence:
>>These last four classes are all expanded to have a graphical implementation with SDL.
You see that the last four classes should be expanded to include some display function (and maybe others). This calls for multiple inheritance. You can make another base class which is dependent on SDL and has this pure virtual "display" function with whatever parameters you need. Now, your last four classes should inherit from their respective base class AND from this SDL visible object class.

This way, all the code that uses the other base classes (Entity, PlayerEntity, etc.) doesn't need to have any dependence on SDL. And your code that handles the rendering and the SDL window can simply keep a record of all SDL visible objects (as base classes) and call their virtual methods for displaying them.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well there has to be other functions to export also. Basically, if the code that uses the DLL is in Visual Basic, then essentially, you are entirely restricted to a C interface (no class exports). Assuming "plugin" in an object of some class, then the VB code has absolutely no way to deal with that pointer directly. Normally, these things are handled by sending the pointer "plugin" with the GetInterface function (or anything similar to that) which is assumed to be an opaque handle that gets sent to any other functions exported by your DLL that take this handle as the first argument (this is typical of any API like win32 or posix or anything else). It could go something like this:

typedef void* HANDLE;

extern "C" __declspec(dllexport) HANDLE GetInterface(UINT32 interfaceId)
{
   if (interfaceId == HAPTIK_IHAPTIKPLUGIN) return new HaptikPlugin();
   else return NULL;
};

extern "C" __declspec(dllexport) void StartInterface(HANDLE interface)
{
  if(interface)
    reinterpret_cast<HaptikPlugin*>(interface)->start();
};

You should look into your documentation if it doesn't require a certain set of standard functions to be exported from the DLL that actually can be used to use whatever plugin or interface you are exporting. I'm sure they have a set of specific functions for every type of interface you want to export (and this GetInterface is probably just a common function to get a handle to any one of the interfaces.. this is at least what I would have done if I were them). Basically, exporting a class via a C interface involves writing …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It seems alright to me as far as the procedure you have taken to export the class from the DLL. That is the way to do it, as far as I know, but I don't do it often because of the remarks that follow.

One important thing that always needs to be mentioned when talking about exporting C++ classes from DLLs is that you have to make sure that all the code that uses this DLL is also compiled with the exact same compiler (same version (major, minor and revision), same OS, same platform (32bit or 64bit)). So, that is very restrictive and often makes the whole idea of using DLL to export classes very impractical. This link provides you a simple explanation of the problem. Basically, the options to cope with this problems are to either:
- export only C functions from DLLs (no class methods nor objects as parameters).
- use a ready-made ABI like COM, ActiveX, or whatever (this will basically confine you to Windows, I don't know of any major ABI that is cross-platform).
- follow very strict rules in your programming style to ensure binary compatibility (which is not a trivial task, relies heavily on the PImpl idiom (Cheshire Cat or Compiler Firewall)).
- stick to one single compiler and OS, and recompile your DLLs for every distribution or new minor version of all compilers (very hard to maintain if you expect wide distribution over some period of …

claudiordgz commented: Again... priceless help :D +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

For the record, I'm not an expert on Hopfield nets (but have dealt with other types of ANN).

You are right, you only need one matrix of weights if you have less than the maximum number of patterns for a given net. The Hebbian rule is quite trivial to implement if you look at this link.

Remember also that basically, you need the patterns to be reasonably "uncorrelated" in order to represent them uniquely with the net. This means that generating them at random might not be the greatest idea. Maybe you should test a pattern to see if it is not correlated too much with the other patterns before you add it to the set (if the Hamming distance between two patterns is to low, you might want to generate a new one). Another way to look at this is through the entropy of the set of patterns (with base 2, the entropy is equal to the number of truly distinct patterns in the set).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you have no restriction as to what you are allowed to use, I highly recommend you use the class "set" (#include <set>) to store the records. In order to use it, you will need to overload the less-than operator (<) in whichever way you like to sort the elements. A simplified version of your problem would look like this:

#include <set>
#include <string>
#include <iostream>

class PhoneRecord {
  private:
    std::string last_name;
    std::string first_name;
    std::string phone_number;
  public:
    PhoneRecord(const std::string& aLastName = "",const std::string& aFirstName = "",const std::string& aPhoneNumber = "") : last_name(aLastName), first_name(aFirstName), phone_number(aPhoneNumber) { };
    ~PhoneRecord() { };
    PhoneRecord(const PhoneRecord& aObj) : last_name(aObj.last_name), first_name(aObj.first_name), phone_number(aObj.phone_number) { };

    PhoneRecord& operator=(const PhoneRecord& aObj) {
      last_name = aObj.last_name;
      first_name = aObj.first_name;
      phone_number = aObj.phone_number;
      return *this;
    };
    //this is the overloaded operators you need for having an ordered set:
    bool operator <(const PhoneRecord& aObj) const {
      if(last_name < aObj.last_name)
        return true;
      else if(last_name == aObj.last_name)
        return (first_name < aObj.first_name);
      else
        return false;
    };
    bool operator ==(const PhoneRecord& aObj) const {
      return ((last_name == aObj.last_name) && (first_name == aObj.first_name));
    };

    //to be able to print, you need the following friend operator:
    friend std::ostream& operator<<(std::ostream& out, const PhoneRecord& aObj);
};

std::ostream& operator<<(std::ostream& out, const PhoneRecord& aObj) {
  return out << "Name: " << aObj.last_name << ", " << aObj.first_name << "\t Phone Number: " << aObj.phone_number;
};

int main() {
  std::set<PhoneRecord> phone_book;
  //add a bunch of records, in random order:
  phone_book.insert(PhoneRecord("Smith","James","555-7624"));
  phone_book.insert(PhoneRecord("Doe","John","555-3424"));
  phone_book.insert(PhoneRecord("Doe","Jane","555-9803"));
  
  //print the list out:
  std::set<PhoneRecord>::iterator it = phone_book.begin(); …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The problem is that you have default values for both parameters of your parametrized constructor. This means that this parametrized constructor can be called without any parameters, just like the default constructor. This is where the ambiguity comes from, if you create an object without parameters to the constructor, should the default constructor be called or should the parametrized constructor be called with default parameters. To fix it, you can either make at least one parameter of the parametrized constructor without a default value, or you can take out the default constructor (assuming that the default parameter values of your other constructor correspond to what you want to happen when an object is created without parameters).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

What I meant by creating a second image is that you need to make one image to store the modified pixels and keep one image intact such that you can pick the original pixels from it. So you will need to traverse both images at the same time, picking values from the original image, computing the formula and storing the result in the modified (or filtered) image.

>>I have a feeling that you have a far better grasp of the process than I.
Sure, I've done my share of image processing work. This process is at the core of almost all image processing techniques (called "convolution filtering").

I hope your exam went well!

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It seems Clinton has got you well covered, but just to correct something.. I'm 100% sure that for this emboss function, you need to start from the upper left corner such that you don't use modified pixel values. Say you start from the last non-bordering row of the image, when you get to the second-last row, you will be using the modified row of pixels in the calculation of the second-last row. I don't think that was the intent from the formula that specifically mentions the modified pixel as a function of the two _original_ pixels.

Also, for smoothing and sharpening, you will need a second image to put the result into (you cannot perform these operations "in-place" like you can with emboss).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have a memory leak in your code, you need to delete the "command" array before you expand it. This is bad because you have a loop that leaks memory at each iteration, this leads to a sustained growth of memory usage in time.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You are only resizing the "test" array, you also need to resize the "command" array (or use command as a temporary string since you don't really need to keep a record of it anyways).

If you want an easier solution, I highly recommend you use std::vector (#include <vector>).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have a whole bunch of uninitialized pointers at line 7:

int *day, *month, *hour, *min, *_hour, *_min;

Since you send those pointers by value to the function calls that you have, the only way that this program will not crash is if you don't use those parameters at all in the functions (which would be useless). You need to allocate memory somewhere and set those pointers to point to that memory. I understand that you are sending pointers to your functions such that your functions can set values of "min" "hour" etc., in that case, you should declare those as "int" (not int*) and then send them to the function as "&hour" or "&min" etc. (or better yet, use pass-by-reference instead).

jonsca commented: He'll get it eventually... +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yeah, so basically, you did the render-to-texture technique that I mentioned in my previous post (which is what you need for lens distortion, now that I think about it). Nicely done!

>>1) The rendered scene will not fill 100% of the window.
Since the scene is distorted, it will not fit inside a rectangular screen (there might be slightly more complex functions that can match the square boundary). I think the easiest is probably to scale the grid (glScalef()) such that it is just big enough to not leave any black spots around. Also, you don't have to have a black background, if you use another color (glClearColor()) or background image that replaces the black spots by something nicer (say you have a lens-effect as if the player was looking through binoculars, then you can first render some kind of image of the binoculars' peep hole(s) to decorate the surrounding if the viewpoint).

>>2) This code must affect the whole view, not just a portion.
That's not a big deal, people typically arrange rendering using scene-graphs, typically, something like: MainScene contains and renders a GUIScene and MainView; MainView contains and renders a WorldView (which it could just render to a texture and apply the distortion). The objects you render just belong to one scene and get rendered onto their parent's scene. This is good for being able to switch scenes and rendering methods on-the-fly (like when you hit the "change camera" button in a game, you …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It should work, verify that pthread_create actually returns 0. As in this example.

Check out Boost.Thread library, it is about to become the C++ standard library for multi-threading because it is easy and effective (and cross-platform), I strongly recommend it. See examples on using Boost.Thread with a global function and using Boost.Thread with a member function.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I'm assuming you have access to the source code of the DLL, otherwise you would not be attempting to use class methods that are exported from it (there are reasons why this would be impossible). I don't know where you got your info, but the methods you tested are all very wacky and definitely wrong. I will try to put a few options that are typical:

1. Compile your DLL code directly into a .lib file (not just changing the extension nor using a third party software to convert). You will need to select as build option something like "static library". Then all you need is to include the header in your main program and specify this static library in the command line. Note that this option will make all the code that you use from this library part of the final executable (i.e. bigger exe file, but no need to distribute the DLL along with the executable).

2. If you want to export classes from the DLL, you have to use the clause "__declspec(dllexport)" between the keyword "class" and the class' name. In the header file that imports the class, you use the keyword "__declspec(dllimport)". Basically, this should be done with a #define:

//in the myDLLClass.h
#ifdef MY_DLL_MODULE
#define MY_CLASS_API __declspec(dllexport)
#else
#define MY_CLASS_API __declspec(dllimport)
#endif

class MY_CLASS_API myDLLClassName {
  //.. everything will be exported or imported
};

Simply defining MY_DLL_MODULE when compiling the dll will export the class and any other use of the header …

claudiordgz commented: Excellent insight and recommendations +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Basically, the examples you gave are all part of the same family of tricks: non-linear projections. As you know, the projection matrix takes objects (vertices) from the 3D world (cartesian) space to a projective space (the frustum, with 2D screen coordinates and depth). But the projection matrix is a linear transformation. This greatly limits what it can accomplish, basically, no "roundish" distortions are possible with it.

So, to create non-linear projections, there might be special-purpose extensions to do this but I don't know any. How most people do it is you substitute the so-called "fixed rendering pipeline" with a pair of vertex and fragment shader. These are simple programs (usually only a few lines long) that can be send to and compiled on the graphics card (via simple OpenGL commands) and used by the graphics card instead of the default rendering pipeline you find in basic OpenGL rendering (with little to no special effects). This is a very vast topic and I am far from being an expert, I suggest to read up on it. A lens effect is probably fairly easy to make and I would suspect you can find open-source shader programs that do that, it's no big deal.

Now, some effects will not be possible just using shaders, you will need multiple rendering passes, in so-called render-to-texture techniques. As with your example of the spiral distortion, this, as far as I can tell, cannot be done well only with a sophisticated shader (because of some …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Quoting wikipedia: "Generally, segmentation faults occur because of an attempt to dereference a pointer that is either NULL, points to random memory (probably never initialized to anything), or points to memory that has been freed/deallocated/"deleted"."
That's what you should be looking for. Basically, anywhere you use memory pointed-to by a pointer, which includes accessing an array or vector by the index. You will get a segfault if you access elements beyond the array or vector size or if you dereference a pointer that is no longer or never was valid. If you have implemented this provider-consumer scheme and have not protected your memory with a mutex, that could very well explain it (especially if the problem seems to occur randomly (random times, random runs)).

To find the error, beyond just outputting log-messages every two lines of code (which you mind as well do if your code is below a few thousand lines of code), you need to use either a debugger or a memory profiler. On your Unix-like system, there are basically two essential tools: gdb and valgrind. GDB will let you put breakpoints into the code, step through it and inspect the variable values (i.e. a debugger), so if you have suspicions about where the error occurs or what variables might be corrupt it helps a lot and is usually all you need. Valgrind is a memory profiling tool, essentially, it sets up a virtual machine on which to run the program which …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Line 78, you messed up the operation priority. It should be:

z[m] = z[m] + (2/(lambda*alpha))*diffX[m];

To match the matlab version.

BTW, if you plan to use this C++ implementation, you have some serious cleaning up to do. You have way too much temporary memory allocations and passing vectors around function calls. Consider doing pass-by-reference and merging your loops together. For example, line 59 to 70, you first traverse a vector to fill another one with the absolute values, traverse that vector to square it into another vector, and finally pass the vector (by-value) to a summation function. Why not make one loop that takes each element of the original vector, square it and sum it (no additional memory and just one single, clean loop, which would also turn your 11 lines into only 3 lines or so).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Roughly speaking, you could say there are three types of classes. Those whose objects are:
1- Always in a valid state (and always constructed successfully)
2- Completely useless if not in a valid state
3- Could be in an invalid state and still be useful (or recoverable)

1- A trivial example of this is a simple POD class like a 3D vector class (holding coordinates x,y,z). Then, obviously, there is no need for a function to check the validity of the object's state because in itself any state is a valid state.

2- Not all, but many resource handling classes are of this type because the object is defined by the resource it holds. If it holds no resource (because it failed to acquire it), then it is meaningless. In this case, an existing object is a valid object, and thus, there is no need to have a function to check its status. Throwing an exception upon construction is a good way to abort any piece of code that uses the resource in case of a failure to acquire it.

3- To counter the above cases, there are many resource handling classes that can either allow a partially invalid state or lose its validity. A good example of both is the std::fstream from the standard C++ library. In this case, the class handles a resource (a file) and is generally constructed to open a file and closing it upon destruction (although the open() and …

StuXYZ commented: Well thought out post +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I can give a few comments that might be useful..

1. I think you have taken too much of an "externalizing" approach. What I mean is that these functions like connect, accept, and listen are kind of trivial in themselves and require the user of your socket class to do most of the work (which is to maintain the connection(s)). These functions seem more to me like they should be private (or protected) helper functions, and maybe your interface could be then a bit higher-level and more abstract.

2. The receive function is not correct IMO. TCP sockets are asynchronous by nature. I assume that the receive function will wait for the next string to come and place it in buffer_m. This forces the user make his own event system (because nobody would consider using a TCP socket in a serial fashion). I would suggest you turn the receive function into a callback mechanism at the very least. This way your socket class can take care of the loop that waits for the incoming messages and issue callbacks when a new one has arrived. This will also allow you to extend the class to a socket that uses a thread pool to be able to respond more quickly to incoming messages by relegating the event handling to an independent thread of execution (so that the receiving loop can go back to listening to the port immediately and not wait for the event handler to be completely finished processing …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Regarding the C or C++ issue. I'd like to keep it in C++, but if pthread.h is written in C, am I still able to compile in C++?

Absolutely. C is essentially a subset of C++. Putting a few issues aside, most C code can be directly compiled with a C++ compiler. As for libraries like pthread, they are "C-style" libraries which means they compile for either C or C++ without any trouble (and in fact, when you include pthread.h you are technically only including the header to an already compiled library, so even if pthread was written in some obscure programming language, it wouldn't make a difference because you don't need to really compile anything of it, you just use it). That was also the motivation behind enforcing backward compatibility of C++ to C such that all those kinds of libraries wouldn't have to be rewritten for C++.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@David: Yeah these are perfectly good examples. I just added a printout in the loop and removed the divide-by-zero situation by removing the zeroth iteration.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well I certainly would not recommend you do it in C if you already used to C++ (that would be a regression, C is only more restrictive).

About the buffer, if you use the queue class than this is a non-issue because this class will keep track of the number of items on the queue.

If you want or need to implement your own queue, then there are a few basic rules.
1. Make the start and end positions available (i.e. you know where the first and last elements are located in memory).
2. Make adding an element at the end and subtracting an element from the start as simple as possible (without needing to reallocate new memory and copy blocks of memory around).
3. Avoid reallocating memory.
So, a typical C-style queue implementation would use a large array (either a fixed size or a dynamic size). Then, you keep two pointers or two indexes, one for the start position and one for the end position. Adding an element to the end is just a matter of setting to element pointed-to by the end-pointer to the new element value, and then incrementing it (while making it wrap around back to index 0 if it reaches the end of the array). Subtract an element from the start is just a matter of incrementing the start pointer. If, at any point, the end pointer reaches the start pointer as it gets incremented, your buffer …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Ho, I didn't expect anyone not to know what a programming idiom is, let alone a veteran poster. Ok, so let me just quote wikipedia's definition, just for the record:

"A programming idiom is a means of expressing a recurring construct in one or more programming languages. Generally speaking, a programming idiom is an expression of a simple task or algorithm that is not a built-in feature in the programming language being used, or, conversely, the use of an unusual or notable feature that is built in to a programming language. The term can be used more broadly, however, to refer to complex algorithms or programming design patterns.

Knowing the idioms associated with a programming language and how to use them is an important part of gaining fluency in that language." -wikipedia.org

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you are not obliged to use pthreads, I would highly recommend using Boost.Thread instead. Both because it is so easy and it is about to be the standard multi-threading library for C++0x.

As for your problem, it is quite a classic and important scenario in multi-threaded applications. The term Buffer is just a general term for chunk of memory in which you temporarily store elements to be processed (unless your prof meant something very specific that I am not aware of). It can be implemented in whichever way you like, but essentially, it is a queue (FIFO) (so you would probably want to use the STL container of the same name).

As for implementing it, it will most likely involve protecting the buffer with a mutex (available in Boost.Thread or in pthread) and have the producer add elements to the end of the queue and have the consumer take elements from the start of the queue if it is not empty. Now, the queue becomes a buffer between the producer and consumer because if either one slows down momentarily for one reason or another, it won't affect the performance of the other. The mutex is critical here because you cannot have both sides tampering with the same memory at the same time, so their operations on the buffer have to be mutually exclusive (i.e. mutex). However, there is a way to avoid using a mutex, but that is for you to figure out.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Hey y'all,

I was just curious about which idiom you prefer or use very often.. and why?

Please vote on the poll! I understand that there are a lot of choices but you can vote for multiples, but try to pick only the ones you think are the best, or most useful, or most elegant to use, i.e., the ones you value most and/or recommend the most.

- Resource Allocation Is Initialization
- Non-copyable
- Factory Functions
- PImpl (Cheshire Cat)
- Singleton
- Lazy construction or evaluation
- Type Traits
- Smart Pointers
- Curiously Recurring Template Pattern
- The Visitor Pattern
- .....

You can also post comments on why you feel a particular idiom is more important than another. And suggest any other idioms that you like if I didn't include them in the list.

I don't want this thread to turn into a huge debate on which idiom is _the_ best one (which doesn't make much sense because they all serve different purposes). But I rather would like people to share what they value most in terms of design objectives and how certain idioms or design patterns serve those objectives better than others. I understand also that I have included both OOP idioms and generic programming idioms, feel free to discuss both.

I hope people will participate.

To get the ball rolling, I should first say that it is …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>It gave me wonky results though. My 3D Objects were all pointed at the camera instead of being perpendicular to the rendered floor.

It seems like you messed up the modelview matrix in the process (the modelview matrix determines the translation and rotation of the displayed objects). Make sure you understand the difference between the projection and modelview matrix, and how the various opengl functions work with those. Make sure that in your code, the transformations in the projection matrix and those on the modelview matrix are well separated.

>>The explanation, sadly, was incredibly complex...

No, the explanation was not at all complex (in fact the simplest I could find). I say this all the time to people: you cannot and should not do 3D graphics programming without a solid background in mathematics (at least geometry and linear algebra, and ideally vector calculus). If you really couldn't understand the explanation I linked to, then you have serious catching up to do in mathematics before you go any further in 3D graphics programming.

>>The vanishing point did not change, and my sidebar disappeared.

If you changed the projection applied to the 3D scene and somehow affected the rendering of the sidebar, then it means you are rendering both the world and the sidebar (GUI) with the same projection (I'm guessing on one viewport too). This is wrong. Any sidebar or GUI-type thingies you want to superimpose to the rendering of the 3D world, you need to …