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

Is there any reason at all for using a shared_ptr<node> for your links? Why not use a unique_ptr<node>? Why incur the extra memory payload and overhead. It seems to me that the following would be a bit simpler (and smaller, and faster):

#include <map>
#include <memory>
#include <stack>
#include <limits>
#include <iterator>

template <typename T>
class trie {
    struct node {
        std::map<T, std::unique_ptr<node> > link;
        bool terminal;
    public:
        node(): terminal(false) { }
    };

    std::unique_ptr<node> root;
public:
    trie(): root(new node()) {}

    typedef std::size_t size_type;

    template <typename String>
    size_type match(const String& s, bool require_terminal = true) const
    {
        // Follow the path until the end of the string or a mismatch
        auto it = &root;
        for(auto sit = s.begin(); sit != s.end(); ++sit) {
            auto lit = (*it)->link.find(*sit);
            if(lit == (*it)->link.end())
                return std::distance(s.begin(), sit); // Return the index of the mismatch
            it = &( lit->second );
        }

        if (!require_terminal || (*it)->terminal)
            return std::numeric_limits<size_type>::max(); // The path was matched completely

        return s.size(); // Return the index of the mismatch
    }

    template <typename String>
    void add(const String& s) {
        auto it = &root;
        // Traverse the path and extend it as necessary
        for (auto c : s)
            it = &( (*it)->link[c] );
        (*it)->terminal = true;
    }

    template <typename String>
    void remove(const String& s) {
        auto it = &root;

        // Store the reversed path
        std::stack< decltype(it) > bak;
        auto sit = s.begin();
        for (; sit != s.end(); ++sit) {
            bak.push(it);
            auto lit = (*it)->link.find(*sit);
            if(lit == (*it)->link.end())
                return; // no match! nothing to remove! …
deceptikon commented: Thanks for the feedback! +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Definitely, I have to say it was an internship some years back. I worked in a lab (at Uni Duisburg-Essen) where they had a roller-coaster seat mounted to the end of a Kuka KR560 industrial robotic manipulator (about 600kg payload capacity), similar to the robocoaster systems. My job was to do some testing and fine-tuning of the control software for that robot and model its dynamics, but at one point, my supervisor just asked me to imagine the craziest rides possible as demos to impress visitors to the lab. I spent a two weeks doing that, and it was really cool.

I wish I had an actual video of this, but this one should give you a good idea of what I'm talking about (although they used an ABB one) (N.B.: we weren't as crazy reckless as the people in that video, we actually cared for safety regulations, not like these idiots).

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

(try and find a company that starts with !) :) ha ha

I found one (providing learning material for the !Xhosa language). Not an exclamation mark, but an alveolar click. (At least, I don't cheat!):

!Xhosa Fundis

TnTinMN commented: good job, I searched for 1/2 hour to no avaiil +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Actually, the words that finish with "ally" are basically all essentially and factually annoying. Basically, I am trying to gradually stop using them practically, but actually, it's hard. Essentially, speaking adverbially might sound fancy, but actually, it's annoyingly crappy, really.

TnTinMN commented: Actually, you have essentially made a factually good point! :> +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

In C++, every cpp file is compiled separately, and then linked together. When the functions appear in the same cpp file as the main() function, then it is compiled together and doesn't need linking. When the functions appear in a different cpp file, then all the compiled cpp files (compiles to .o or .obj files), including the one with the main() function, must be linked together. In order to be able to use the functions from any cpp file, a function needs to be declared in the cpp file in which it is used, usually through the inclusion of a header file that declares a set of functions.

Here is a simple example (hello world):

In hello.h:

#ifndef HELLO_H
#define HELLO_H

// This is a declaration of the function:
void printHelloWorld();

#endif

In hello.cpp:

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

// This is the definition of the function:
void printHelloWorld() {
  std::cout << "Hello World!" << std::endl;
};

In main.cpp:

// include the header file for the function:
#include "hello.h"

int main() {

  // call the function:
  printHelloWorld();

  return 0;
};

Then, you must compile both cpp files and put them together. In an IDE (like Visual Studio or CodeBlocks), you need to add both cpp files to the "project" and build it. If using a compiler like GCC using the command-line, you need to do:

$ gcc -Wall -o main main.cpp hello.cpp

which has the effect of doing the following steps:
compile …

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

Try to install build-essential (at least, in Ubuntu repos, I don't know if other debian distros have it too), it will install everything you need.

$ sudo apt-get install build-essential

Also, if you get the message "unable to locate package ..", then you should try to do a search for it:

$ sudo aptitude search gcc

It should list all packages that contain that word (like grep). It's possible that the package is named something else, like gcc-4.7 or something like that.

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

What I hate are all those French words or expressions that English-speakers use and speak with a stupidly exagerated and totally wrong pronounciation. Like "rendezvous" or "laissez-faire", even the online dictionaries have a ridiculous pronounciation, listen here or here.

Why don't people just call it the stomach or abdomen, tummy seems too childish if you ask me.

But then we wouldn't have great rhymes like "yummy yummy yummy, I've got love in my tummy".

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

could I do something like this

Yes. The mechanism to do this is called "templates". Your function would look like this:

template <typename T>
T* createEmployee() {
  return new T();
};

And it would be called as so:

Employee* p = createEmployee< Manager >();

For a more complete tutorial on this, refer to this, or this, or any good book on C++.

Also, I must remark on the fact that you should not return a new-allocated object by pointer from a function. This is bad style because it obscurs the method of allocation, and thus, creates confusion as to the method of destruction (with delete in this case). One option is to always provide a pair of functions, one for creation one for destruction:

template <typename T>
T* createEmployee() {
  return new T();
};

template <typename T>
void destroyEmployee(T* p) {
  delete p;
};

And make it clear in the documentation that anything created with the one function must be destroyed with its corresponding function.

Another option is to use a smart-pointer to (implicitly) bundle the pointer with a deallocation method. One such smart-pointer is std::shared_ptr (from <memory>):

template <typename T>
std::shared_ptr<T> createEmployee() {
  return std::shared_ptr<T>(new T());
};

This smart-pointer is reference-counted and will automatically destroy the object when there are no more shared_ptr to that object in existence (i.e., the object is no longer needed). In other words, you don't need to explicitly delete that …

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

we can say that set (ordered or unordered) are MAINLY used for look-ups ? and i have a big advantage with set(ordered) that they are arranged in sorted order when i will traverse it. am i roght ?

Yes that's right.

secondly, if can i have a set of structre ? if yes, then how will it check for uniqueness ? thanks.

If you want to use unordered_set with a custom class (or structure), you have to define a hash function as well as an equality comparison function, as you see from the signature of the class template:

template < class Key,                        // unordered_set::key_type/value_type
           class Hash = hash<Key>,           // unordered_set::hasher
           class Pred = equal_to<Key>,       // unordered_set::key_equal
           class Alloc = allocator<Key>      // unordered_set::allocator_type
           > class unordered_set;

The default equality comparison is the == operator for the class (which you can define).

For a std::set, it is similar, you have to define your own comparator (analogous to less-than), or simply overload the less-than operator.

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

Can we install .deb format on ubuntu 11.10 or 12.10 using sudo apt-get install???

In Linux, most software is installed through the package manager. This is an application that connects to a bunch of software repositories on the internet that host databases of .deb files (or .rpm in Red Hat variants). In the terminal (command-line window), you can install packages from the repositories via the command apt-get (or yum in Red Hat variants), which needs to be run as superuser. So, if you want to install GIMP (GNU Image Manipulation Program, i.e., a kind of open-source version of Photoshop), then you would open the terminal and write:

$ sudo apt-get install gimp

(note: the $ sign represents the prompt, you don't type that)

The sudo command means "superuser do". It allows you to execute one command (whatever follows it) with superuser privileges. It will ask you for your user password (same as when loging in).

The apt-get command is the program that can connect and fetch packages from the repositories. The option install speaks for itself. And the rest is a space-separated list of packages you wish to install (e.g., "gimp"). If you wish to remove a specific package (e.g., "gimp"), you would do:

$ sudo apt-get remove gimp

If you don't know the name of a package, you can always do a search that will return a list of suggestions:

$ sudo aptitude search gim    (note: missing 'p', 'gimp' will be suggested)

For .deb …

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

the words will be stored in the order they are added to the unordered set unlike a set where they are put in order of thier key value.

That's not true. Not at all. The values stored in an unordered_set will appear in whatever order they map to through the hashing function and the bucketing (to resolve collisions). This is why it is specified as "store elements in no particular order". If an implementation was required to preserve the order of insertion (as you suggest), there would be no way to implement this without doing an indirect indexing, and that is an unacceptable compromise for most purposes (if you want indirect indexing, just do it yourself through a vector and an unordered_set working together).

if i iterate it, then will they be in any specific order ?

No. The elements appear in "no particular order", which means neither sorted nor in their original insertion order.

what can be the use of it ?

If you don't need the data to be sorted (as in a std::set), then you can use an std::unordered_set for the same purposes you would use an std::set. Then, lookups, insertions, removals, and just about any operation that requires finding a particular value in the set can be done in constant time O(1) (amortized) as opposed to logarithmic time O(logN). For large numbers of elements, this can be a huge performance benefit. For smaller sets, you get less of a performance …

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

Of course, for such a project, you will have to do significant changes to the OS anyways, and in that sense, will end up developing a new derivative or variant of an existing OS.

One good option seems to be MeeGo or one of its derivatives. There are a number of different user interfaces / derivatives, I'm sure one of them will fit the bill.

Another option is to take a desktop distro which has a tablet- or phone-friendly interface, like KDE-netbook / Plasma Active, or Ubuntu Phone. Then, you can strip down the OS by removing components / features you don't need or cannot support on your limited platform.

I would recommend a Qt-based GUI (such as KDE, or Qtopia), because they are really nice (nice looking and easy to program).

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

Thanks, but there should be a simple solution, because teacher can't ask what he hasn't taught yet.

Well, programming is all about being able to learn on your own, because no amount of course-work is going to be enough to be proficient. So, who says the teacher can't ask for what he hasn't taught yet? If I were a teacher, I know I would do exactly that.

The other possibility is that your teacher has very very low expectation on the quality of the code that his students are supposed to produce. For example, he could expect you to produce the following:

#include <iostream>
#include <vector>

struct student
{
  int* subjects_number;
};

int main()  // <--- NOTE: main() must return an integer.
{
  int NoOfSubjects = 0;
  cin >> NoOfSubjects;

  // create a student record:
  student my_student;

  // allocate the array of subject numbers:
  my_student.subjects_number = int[NoOfSubjects];

  //... now you can access each subject number as 'my_student.subjects_number[i]'

  delete[] my_student.subjects_number;

  return 0;
}

But the above code, although correct for this trivial example, is absolutely horrible, and teaching to do this can be very damaging to the students' future coding habits. In the real world, the above code is complete garbage, it's a "throw it away and fire the guy who wrote it" situation, because anyone who thinks it's OK to code like this shouldn't be working for you.

MRehanQadri commented: Thanks Mike. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The more formal name for the "heap" is actually "freestore memory". In short, all the memory consumed by local variables is on what is called the "stack", which grows (by stacking more and more variables) as you declare more local variables and as you call functions that have local variables in them. Each function, with all its local variables (including function parameters), consume a certain amount of memory, but that memory is fixed at compile-time (i.e., the compiler generates static code that allocates those variables on the stack). If you need a certain amount of memory but it is unknown, at compile-time, how much memory you will need (e.g., like in the example, you don't know how many characters you will need until you have the argv[1] string, which is obtained when running the program), then, you need to allocate that memory dynamically (at run-time). The heap or freestore memory is there for that purpose. And yes, you allocate such memory by using the new operator, and you deallocate that memory with the delete operator (once you no longer need it).

The most basic example is this:

#include <iostream>

int main() {
  int run_time_count = 0;
  std::cout << "Please enter the size of the array: ";
  std::cin >> run_time_count;

  // allocate an array of the specified length from the heap:
  int* p_array = new int[ run_time_count ];

  // at this point, p_array is a pointer to the first element of 
  // the newly allocated array.

  // fill the array …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, your loop is infinite:

while ( numberLength / 3 != numberOfGroups || numberLength < 3 )
{
    strcat("0", argv[1]);
}

Because the values in the expression ( numberLength / 3 != numberOfGroups || numberLength < 3 ) are all constant throughout the loop iteration, so if it starts (evaluates to true), it will never end (the condition will always evaluate to true). A simpler way to check if the length is not an even factor of three is (strlen(argv[1]) % 3) (if non-zero, it means it is not an even factor of three).

Second, for the problematic expression, strcat("0", argv[1]);, if you read the reference page for strcat(), you will see that the first parameter (i.e., "0") is supposed to be the destination, not the second argument (as you seem to think). And, the destination must be large enough to hold the entire destination string, which is clearly not the case here because the string "0" is only big enough to hold one character and the null-terminating character.

I think that the method you are using is beyond repair, you must change your strategy. First, you will need to allocate an array of characters big enough to hold argv[1] + leading zeros + the null-terminating character. The number of characters in the final string can be calculated as the first 3-even number above or equal to the length of argv[1]. This can be computed as:

int old_str_length = strlen(argv[1]);
int new_str_length = …
tux4life commented: Nice that you took the time to explain it step-by-step :) +13
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here are a few facts that you need to know:

  1. Floating-point numbers are fixed by IEEE standards and do not differ between platform (except for extremely archaic ones). This means you don't need endianness conversions for float or double.
  2. Endianness conversions (e.g., htonl / ntohl) work on fixed-size unsigned integer types. The network conversion functions ending in l (for "long") use the integer type uint32_t, which is a fixed-size (32bit = 4bytes) unsigned integer type.
  3. The network byte-order conversion functions come in pairs. That is, htonl means "Host TO Network byte order for Long integers", and ntohl means "Network TO Host byte order for Long integers". You use htonl to prepare the value to be sent over, and you use ntohl to re-order the data that you have received from the network (to put it in proper order for the host platform).

So, you positional data should be of the following type:

  uint32_t time;
  float LAT;      // or: double LAT;
  double LONG;
  uint32_t ALT;

And before you send to the network, you need the following conversions:

// reverse the byte order of everything
  uint32_t time = htonl( uint32_t(currentTime) );
  uint32_t ALT  = htonl( uint32_t(AC_Alt) );
  // NOTE: the floating point values don't need conversion.

And, as a tip, a slightly nicer method for constructing the message is the following:

// Copy it all to message
  std::string message;
  message.append( (const char*) &time, sizeof(uint32_t));
  message.append( (const char*) &LAT,  sizeof(float));
  message.append( (const char*) &LONG, sizeof(double));
  message.append( …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To do this properly, you need to do a lot of work, and it will become a full-blown class (with private members, non-trivial constructor / destructor / copy-constructor / copy-assignment operator, etc.). Here is a good tutorial about this.

Objective: students could have taken different number of subjects. Now modify the structure such that its variable subjects_numbers has type pointer to int so that we can store scores for different number of subjects for each student.

Is this a self-imposed problem statement from you? Or is it what was given to you as an assignment? Because if this is what is required of you (have a pointer to int as member and do the allocation of a dynamic array with new/delete), then you have to follow the tutorial I linked to and adapt it to your problem context. But if you are not required to do that, then you should use the standard class std::vector:

#include <iostream>
#include <vector>

struct student
{
  std::vector<int> subjects_number;
};

int main()  // <--- NOTE: main() must return an integer.
{
  int NoOfSubjects = 0;
  cin >> NoOfSubjects;

  // create a student record:
  student my_student;

  // resize the vector of subject numbers:
  my_student.subjects_number.resize(NoOfSubjects);

  //... now you can access each subject number as 'my_student.subjects_number[i]'
  //     just like a normal array.

  return 0;
}
MRehanQadri commented: Thanks, but there should be a simple solution, because teacher can't ask what he hasn't taught yet. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You are already using the function that you are looking for. The function system() executes a command. In this case, you are executing the "pause" command. You can use the same function to execute other commands, including your own program. It's as simple as that:

system("InputProgram.exe myargument");

There are also more native Windows functions to do the same (with a bit more control), such as CreateProcess().

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

This error message means that you are accessing an address of memory that is not reserved for your program. This usually occurs when you read or write at a location pointed to by an invalid pointer or beyond the valid memory that the pointer points to. For example, these are three potential segmentation fault cases:

int main() {

  int* p1;   // an uninitialized pointer is invalid.
  *p1 = 42;  // ERROR! Segmentation fault!

  int* p2 = NULL;  // the NULL location is a universally invalid value for a pointer.
  *p2 = 42;  // ERROR! Segmentation fault!

  int* p3 = new int[4];  // allocating an array of 4 integers. 
  p3[4] = 42;  // ERROR! Segmentation fault! (index 4 is beyond the valid memory)

  delete[] p3;

  return 0;
};

There are, of course, countless more situations, but they usually boil down to one of these cases.

I'M tryin to use strcat() to add "0" to the left end of char *argv[1]

You cannot do that. If you read the reference on strcat, you will see the following description of the "destination" parameter (first parameter to strcat):

"Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string."

If the destination memory location is not large enough for the total string, then you will get a segmentation fault (i.e., writing beyond the chunk of valid memory that "destination" points to).

I don't know exactly how your code …

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

I think Danny Trejo is an awful actor with awful films... (my opinion so don't get mad...)

Maybe not the greatest actor, but he's an awesome guy.

LastMitch commented: Nice! +0
diafol commented: great link +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here's something, I hope it's not too complicated:

#include <iostream>

int main() {

  // create an array of C-style strings (const char*):
  const char* messages[] = {"Hello World!", "The answer is 42.", "Because the bold man told you so."};

  int selection_index = 0;
  std::cout << "Select the message you want displayed (0-2): ";
  std::cin >> selection_index;

  // declare a pointer to a C-style string, (or a pointer to pointer to const-char)
  // set the selection pointer to point to the string that was selected:
  const char** selection = &messages[selection_index];  
  // or, equivalently:
  // selection = messages + selection_index;

  std::cout << (*selection) << std::endl;

  return 0;
};

If the expression &messages[selection_index] confuses you, here's the explanation. Doing messages[selection_index] gives you the selection_index element from the messages array of const-char pointers, so, the resulting type of that expression is const char*. Then, the ampersand & takes the address of that element, and thus, returns a pointer to that pointer, i.e., it has the type const char**.

The alternative expression, which is messages + selection_index, is a bit simpler. In this case, the messages array decays to a pointer to the first element of the array, and so, it has the type const char**. Then, adding an integer to a pointer has the effect of moving the pointer by that integer amount, resulting in this case to a pointer to an element selection_index positions beyond the first element of the messages array. In other words, the result is the same as …

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

I have been told that in C++ the concept of a string does not exist. A string is just an array of type char.

Yes and no. At the fundamental level, a string is just a sequence of characters, and in that sense, an array of characters. This is the case in all programming languages, some expose that directly, others hide it in a standard library feature, and others hide it in a language feature.

In C, creating and manipulating strings is done through the creation and manipulation of an array of char, terminated by a null-character (i.e., usually called a "null-terminated C-style string"). C++, like any other C-inspired language, inherited that from C, however, the C++ standard library has a class called std::string (from header <string>) that hides away all these annoying details of the creation and manipulation of an array of char, and exposes much more convenient and rich functionality than raw arrays of char. So, the answer to your question is that the "concept" of a string is not embedded in the C++ language, but there is a standard string class that takes care of that. In practical terms, whether the language has strings as a language feature (e.g., Delphi or Java) or as a standard library feature on top of a more "low-level" representation as an array of char (e.g., C#, C++/CLI, Python, etc.), the difference is negligible. And in that sense, "does the concept of a string exist in C++?", yes, as much …

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

Well, I have a great deal of distaste for switch statements overall, in part because I find the syntax ugly, and in part because they are often an indicator that there's something you are missing out on an opportunity to have a more flexible design. In other words, when you leverage polymorphism well (statically or dynamically), you don't really need to use switch statements all that much. But with that said, there are definitely many uses for switch statements (some are necessary, others are just more quick and convenient than a more "designed" alternative). And my personal taste in the matter does not amount to a coding guideline, for sure, so, use them if you want to.

As for nested switch statements, I don't see any problems with that, as long as it is properly spaced out and indented. And obviously, you don't want redundancy (repeating a very similar nested switch statement again and again), if that's the case, consider rethinking it to see if it is possible to avoid that (e.g., putting the nested code into a separate function, or using dynamic polymorphism).

But take note that humans can keep on average 7 different things in their head at one time. The more variables you use, the harder it is to mentally keep track of them all when reading the code.

Yes, that's a good point and common-sense should always apply whenever following any kind of coding guidelines (whether stylistic or about code correctness). In my experience, …

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

That's a nice question. Code readability is really important.

Here are a few tips:

1) Leave the explanation of what a function does outside the function, and the comments about how it is done inside the function, near the code that does it.

2) Use meaningful and complete names for the variables and classes.

In your code, I see a lot of names like "Object", "Polygon", "Physics", "Motion", "Ntime", "Yvel", etc... which are either too general to be meaningful or too short to the readable. As the saying goes, typing is cheap, reading is expensive. In other words, the time you spare by typing shorter names or by not taking the time to come up with more meaningful names is time you're gonna lose many folds when you come back around trying to discypher what the code means.

3) Use verbs in function names.

A function is supposed to do something, and its name should reflect that. Your function is called "Collision". What is that supposed to mean? Is is checking for a collision? Is it (also) reacting to a collision (e.g., bounce the objects)? Is it computing a collision force? I don't know because I don't know your code (until reading the implementation), and your function's name is not helping me.

4) Let the code talk for itself.

If you follow tip 2 and 3, you'll find that code will read like prose (sentences). For example, here's a line of code from some of my own code (from some …

bguild commented: Educational and extensive! +5
tux4life commented: People should read the C/C++ forums on a more regular basis, even if it were only to read your posts. Keep up the nice posting ;) +13
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

British generally refers to either the UK or Great Britain, where the former refers to the main island (with England, Scottland and Wales) and Northern Ireland, and the latter refers to just the main island. England is just one part of the main island, and the other states (Scottland and Wales) are semi-independent. So, being Scottish means you're British, and being English means you're British, i.e., it's a super-set / sub-set thing.

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

One, I need a simple way of rendering a GUI with minimal headache.

I highly recommend Qt. It is in C++ (so, familiar territory for you, and no need to have an elaborate front-end / back-end design), and it is cross-platform (works anywhere, include mobiles). It is pretty much as easy as it can get for GUI programming (drag-drop designer, simple build method, feature-rich components, etc.). When I first learned to use it, within about an hour I was finished with what I had to do, it was a very simple GUI, but still, I never expected it to be that easy to pick up.

As you mentioned Ogre, I'll also mention that Qt integrates very well with OpenGL, and with Coin3D (aka Open Inventor) through SoQt. You can get a 3D scene up and running in no time, integrated inside a Qt GUI.

Two, I need a way to save data as classes and objects and a way to search through this

That's called Serialization. There are tons of options in this regard, both in terms of useful file formats that can form the basis for all your files, and in terms of libraries that do it. Most serialization libraries will support many of the different formats that are typically capable of storing a complex object architecture of various classes.

For file formats, the most popular ones are XML (or XML-like files), Google's Protobuf (used by Google for everything), and JSON …

Aarowaim commented: Thanks for the wonderful suggestions. I was definitely looking for something other than visual basic +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, you can proceed by elimination. I'm gonna try to explain without giving it all away.

Hint 1:
In an undirected graph, every edge that is counted on the degree of one node must also be counted in the degree of the other node to which it leads. For example, this list of degrees is possible:

0 1 0 0 1

because, clearly, there is an edge going from node 2 to node 5, i.e., it is counted twice, once in node 2 and once in node 5. On the contrary, this list of degrees is impossible:

0 1 0 1 1

Hint 2:
If the graph cannot have redundant edges (i.e., multiple edges going from the same source to the same destination), and that the edges cannot be looping back directly (i.e., source node and destination node are the same), then any one node cannot have a degree higher than the number of other nodes with a non-zero degree.

I tried not to spell out the answer too obviously... no sure if I succeeded.

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

This looks like a classic case of heap fragmentation. This is a rather classic problem which will cause the memory consumption to grow larger and larger even when the memory that you actually use is not increasing (no leaks). Normally, this will stabilize to a fixed amount of memory consumption after a little while.

To reduce fragmentation, you should, of course, avoid doing lots of dynamic allocations of small chunks of memory. For example, allocating lots of single objects with new is a typical driver of such fragmentation problems. Of course, in C++, you shouldn't be allocating lots of single object with new because there is no need for it, use stack-based local objects instead, and dynamic memory only for arrays (through STL containers).

Ketsuekiame commented: VLD is pretty good, so there's no real need to second guess it. Mike's proposition looks correct and is an example of good practice +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

b) the delayed write problem has nothing to do with nautilus which is not involved at all in this. I can think right away of many reason this bug could occur, some relating to serialised background thread launched by the kernel that are not reported back to the command window nor known by the typical user (like you), possible usb driver misprogramming (quite possible) or another possibility is that this particular usb has its own embedded circuit that moves the data inside itself from a rapid memory to a slower memory and that it flashes during that time (even though the data has completed its writing to its fast memory and therefore should be safe even if the usb removed) though that hopeful and reassuring scenario of delated writing inside the usb is somewhat far-fetched but still a possibility.

Read the bug report I linked to in my previous post. The issue has been identified and fixed, you don't need to speculate about what the source is. The issue is that newer flash drives and hard-drives have a hardware cache unit to speed up the reading / writing by buffering the data. The umount command can handle this already via a flag (command-line option to the command) that tells it to first request a sync'ing of the hardware cache (i.e., flushing the cache). Linux distributions like Fedora and Ubuntu use a desktop environment called "Gnome" which wraps those kinds of file operations and gives them additional functionality (e.g., …

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

Well, I dug around a bit and it appears there is a bug report about this problem with Nautilus here. Feel free to vent your misfortunes there, and petition to have it assigned a higher priority.

I am quite a bit puzzle by your slugishness in that you haven't already tested yourself on your 'Dolphin' which is probably a copy (with a different name) of the 'Nautilus' I am using.

Why would I do that? I have no stake in this. And Dolphin is not a copy of Nautilus. I use a KDE-based distribution, things like progress bars for file transfers / copies are handled differently, and it has been flawless in my experience with it. But, of course, for any kind of heavy-duty file manipulations / transfers, I do it in the terminal anyways, because it's faster.

But let's test it yourself as I did and see the result:

1) Use cp to copy a large file (say a 8gb file) to a usb drive.
2) See how cp returns before the file is actually finished copying (see the flashing light blink on your usb). Neat, would you normally think: the system can do the task in the background! But wait...
3) Now while the file is still copying in the background and your usb file is flashing: umount your drive!
4) Surprise, surprise: umount returns successfuly BEFORE the file copying has been completed.
5) And remember not every usb …

bguild commented: Thoughtful and detailed +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

BTW - do ya think you could type in a Frngench axe-ont frngom know ôn, mon cher?

Well, Ay-eh can-eh try-eh too typ-eh wid eh québécouay haxent..

Reverend Jim commented: très amusant (eh) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I see you vented a bit there.

I will admit that GCC's build configuration is not the greatest, mostly because they use an antiquated system called "autoconf". This is a configuration tool they wrote decades ago (long before Linux), and it simply hasn't been able to keep up with all the additional complexity of modern-day operating systems (remember, in the days of its inception, the entire operating system could fit on a floppy disk (1.2 Mb)). Switching to a newer and better configuration system (e.g., cmake) would be an enormous task, and a very boring and painful one, something that open-source developers aren't rushing in to volunteer for.

As for the file copying, you must know that all the "real stuff" in GNU/Linux is done under-the-hood by small command-line utility programs (e.g., cp in this case). These programs are extremely reliable and well-behaved, you can be sure of that, and it is largely the reason why Linux/Unix/Solaris servers can run for years without any major hick-up, while Windows servers can at best run continuously for about 1 month before something "weird" happens, requiring them to go down and reboot. If you experience something quirky in Linux, like what you described, it is usually due to the GUI program, because these are typically written by novice programmers and enthusiasts that are just doing this to learn or make their mark. The GUI programs and desktop environment is one of the weakest points of Linux, since it simply hasn't been the focus …

bguild commented: Thoughtful and detailed +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If I install gcc 4.8, and then later I install other software (automatically with ubuntu software manager or manually), will this wreck everything (at least in some cases) as (possibly) the software downloaded is written for an earlier version of gcc (4.6) and might be incompatible with gcc 4.8 and crash on compilation or later?
If so, should I instead install everything I think I will need before installing gcc4.8? Would that work or will I be facing other problems?
Or is there nothing to worry about here?

This mostly depends on where you install gcc 4.8. It is surely a good idea to install the standard stuff before (from repositories), and for GCC, you don't have a choice since you need a compiler to compile the compiler!

For general guidelines, I think I explained this recently in another thread, but here it is again. In Linux (or any Unix variant), there are a number of folders where applications and development libraries get installed:

  • /usr/bin : where top-level executable programs or scripts are put (i.e., when you execute a command like gcc, it fetches the executable /usr/bin/gcc automatically).
  • /usr/share : where you find all the "application data" for all the applications installed (e.g., icon images, docs, etc.).
  • /usr/lib : where you find all the compiled libraries (static or dynamic) (more or less equivalent to Windows' "System" or "System32" folders).
  • /usr/include : where you find all the header files (C / C++, whatever else) for the libraries. …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The word a$$ either means anus or donkey, so pick whichever you like: "anus-kicking computer" or "donkey-kicking computer". ;)

I would also vote against censorship, if it was a democratic decision.

Nick Evan commented: Ha! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

On writing to cout, terminate your lines with << endl;, otherwise you won't get your output displayed on the screen before you are asking for the input.

That's wrong. cin and cout are tied together under-the-hood such that asking for input from cin automatically triggers a flushing of the output stream, exactly for that kind of situation.

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

I guess we also have to specify that the formula is not computed with integer arithmetic. Otherwise, for any integer greater than 1, the division would yield 0, and thus, there would be "billyuns and billyuns" of possibilities too (2^160 for 32bit unsigned integers). ;)

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

When doing cross-platform work, there isn't really a need to constantly use both or move between two platforms all the time for doing the actual coding, only for compiling and resolving issues. You code on one platform (whichever you prefer), and frequently check that it compiles on your other target platforms, and that your unit-tests pass. Virtualization or dual-booting will do just fine, even remote desktoping works well to just make sure things compile and pass the test-suite (there's nothing easier than just SSH'ing to another computer, run the build+test script, and continue coding while you wait for the results).

The main challenges are not in the setup of the computer(s), but rather in the methodology used while coding. First, you need a decent way to easily transport your code-base from place to place, whether it's between a Linux-friendly folder/partition and a Windows-friendly folder/partition, or between two distinct computers, or into a third-party computer, or into the computer of a collaborator / contributor. Second, you should keep track of changes to be able to see what changed between the last successful cross-platform build and the current one (if it failed). You can solve both of these problems by hosting your code-base on a server like sourceforge or github (I highly recommend github), it's very convenient to commit all your daily changes to the server and be able to pull them from any other machine, anywhere (and it even does the Windows new-lines / UTF new-lines conversions …

bguild commented: Detailed and helpful +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here is a pretty complete tutorial for Linux. For Mac, it is a Unix-like system like Linux, and so, the tutorial is equally valid for Mac.

(I think it's different in you can't create/import .dll's instead it's .lib).

You have wrong, here is how it is:

Windows:
.dll : for "Dynamic-Link Library", the DLL is needed to run the executable (i.e., the library code is in the DLL only, not imported into the executable, and that code is loaded dynamically (when loading the executable)).
.lib : for static library (only used by Microsoft and Borland compilers), the lib is only needed when compiling the executable (i.e., the library code is imported into the final executable, making it a standalone executable).

Unix-like systems (Unix, QNX, Linux, Mac, Windows/Cygwin, and just about every other OS that exists today):
lib***.so : for "Shared Object", this is essentially the same as a Windows DLL (although the linking mechanisms are a bit different, but that's an advanced topic).
lib***.a : for "Archive" or also called a static library, this is the same as a .lib, but for all compilers other than Microsoft or Borland (i.e., GCC / Clang / ICC / ... under Windows also use .a for static libraries). The only difference between a .lib and a .a is the binary format used (the .a files use the ELF (POSIX) standard from Unix).

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

So who do you think is going to win?

The team that scores more points than the other by the end of the game. -- Captain Obvious

<M/> commented: you will be rich if that is how you bid lol +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

More and more I find that I can no longer assume that the developers and IT specialists I work with have any clue how to do their job.

The worst is when the only skill that people develop during a programming course is their skills at finding code on the web and disguising it as their own. At some point, it gets to the point that they even believe that they did it themselves. A while back I delegated a simple coding task to a senior computer science student that was part of my robotics team. It was a simple pattern-matching task, no big deal, maybe a few hundred lines of code or so. It took him about 3 months to get it done and what he delivered was clearly pieced together from 2 different sources, and still had the original authors' names in most of the source files. And of course, the code was completely inappropriate for the task given. And when I confronted him to those facts, he couldn't understand why I would say that he didn't do the work, but said that of course he didn't literally write the actual code himself, as he said "nobody does that anymore", some programmer he is. It never occurred to him that his programming courses were trying teach him to be able to write the actual code himself, he thought the point was to have a vague understanding of it and be able to cobble up code from …

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

sets up a way for users to permenantly close their own threads so they don't have to take in anymore solutions or have a "timer" that closes threads permantly after a few months of being "dead". Wouldn't those be helpful features to prevent spam?

If I'm not mistaken, there is a time out on the email notifications. As in, the OP or other members who contributed to an old thread don't get notified by email that someone has resurrected their thread. If not, that could be a good idea (but then again, I'm sure Dani would say that it's good that resurrected threads poke old members, possibly bringing them back to Daniweb, if they haven't been around for a while).

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

By any chance is Dani developing a way to permenantly close "dead" threads, to prevent spam?

No, or at least, it would be extremely surprising. She has made it abondantly clear (mostly in moderator-only discussions) that people contributing to old threads is not only in agreement with the rules but also welcomed, even if it's annoying for members to see old thread popping up in the listings. And as the queen, her wishes are our commands.

I do agree that it would be nice to have some feature that's more "in your face" about the thread being dead would be a good thing. But then again, the current purple, large-font message and the big fat link to start a new discussion is pretty "in your face" already.

It could be a two-step thing: remove the editor box from threads that are too old and replace it with a message like the current one, with the addition of a link to make the reply-editor appear if the person really feels he has something valuable to add to it. That additional, simple step just makes it impossible for someone to just glare over the thread and the "dead thread" message without noticing and replying to it as if it was a current and active thread.

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

I have a tentalizing scenario for the whole "holding the door" conundrum: double doors. Walk into a restaurant, mall, or building with double doors, whoever gets to walk through the first door held open for them is going to reach the second door before the other. And there comes the "test", (1) will the person return the favor (and establish equality of manners), (2) will the person slow down expecting the gallantry to be repeated, (3) will the second person rush in to hold the second door too, or (4) will the person just open the door and walk through (and probably holding it open for the second person).

To me, the first case is nice and pleasant for all parties involved, even among strangers, it just feels good to care for others and/or be cared for. The second case, which would usually involve a woman as the person waiting for the gesture of gallantry, is a bit backwards and weird, and I don't think anyone (of my generation) likes that, whether on the receiving or giving end. I think few men are still attracted (if ever) to the whole "I'm a princess and you're my knight" thing. And if women are offended to be put in that role, then great! The third case is also bad for the same reason, except that, in that case, the man is trying to put the woman into that princess/knight paradigm. In the last case, clearly the person doesn't care much about the …

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

Ok, completed compilation of Clang 3.3
In other system, you wouldn't need to do this: you would just use the working binaries that you be available at the site of the developper. But, hey this is the linux world: always make it the most complicated possible so we can keep busy all the time.

Take any fairly complex bleeding-edge open-source library or application and try to use it in any system other than Linux, and then you will know what real pain is. You cannot compare something like getting the very latest version of Clang or GCC (a very recent, experimental-version, open-source compiler) with something like installing stable versions of GCC or MSVC distributed in Windows. MSVC works on a 2 to 3 year release cycle (which is really long), is closed-source, and commercially packaged. GCC has a much shorter release cycle on Unix-like systems (a few months), is open-source, and is packaged (as binaries) only after sufficient stability and field-testing, and is packaged for Windows (in MinGW) every so often (and never with the bleeding-edge version either). If you can accept that situation (lagging behind in version, waiting on long release cycles), as the vast majority of people can, then you can install those pre-packaged binaries and have no trouble at all, in Linux, it is as easy as issuing the command $ sudo apt-get install build-essential and that's it. But if you choose to get the bleeding-edge version (of Clang or GCC), you must accept …

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

Ok, now I actually seem to be able to compile Clang 3.3. The computer is running for quite some time now (I am crossing my fingers...). I am curious: about I long will it take on a duo-core laptop ? An hour or a day?

It should take about an hour, at most two. Clang and LLVM are not that big.

But still, why is it not working (the config.log that it refers is many many pages long and totally useless for me)?

I'm pretty sure it is this issue with the crti.o libraries and such (as in my previous post). I had that issue before, and it is seems to be a recent change by Debian (since Ubuntu 11.10) that the GNU people didn't adjust to yet in their configuration scripts.

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

Have you tried clang?

It's funny you say that. I just built clang + llvm + libc++ from source today (for the first time). I had no problem whatsoever. And now, I'm compiling my entire code-base with it (about 130 thousand lines of code) and it's going very well. I also just tried a very nice utility derived from clang, called include-what-you-use to analyse header-file dependencies in the hopes of reducing inter-dependencies and adding forward-declarations wherever possible (getting this tool was the main reason that I compiled clang from source). Clang is a great compiler, it's very fast, standard compliant and uses very little memory.

If I add #include <iostream> in a reckless moment of happy expectation, it can't compile it and I can have real fun trying to decipher:

/tmp/test2-LUg9Sk.o: In function __cxx_global_var_init': test2.cpp:(.text+0x10): undefined reference tostd::ios_base::Init::Init()'
test2.cpp:(.text+0x16): undefined reference to `std::ios_base::Init::~Init()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

It seems that your clang program is not able to find the standard library to link to. Clang can use either libstdc++ (from GCC) or libc++ (from LLVM project). You can specify it as a command-line argument (but it should attempt to look for libstdc++ by default):

$ clang -stdlib=libstdc++ test2.cpp -o test2

or

$ clang -stdlib=libc++ test2.cpp -o test2

You must make sure that either one or both of these are installed. The easiest is just to make sure you have installed the package …

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

And by the way, version 4.7.2 that is now on Ubuntu's repositories is perfectly fine for doing C++11 coding, the difference between 4.7.2 and 4.8.0 is not that great in that regard.

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

So I ask: has anybody ever succeeded in building/loading/using SUCCESSFULLY g++ 4.8 on a Ubuntu computer?

Yes. I keep a rolling version of GCC on my computer at all times, i.e., GCC compiled from source obtained from the latest development branch of GCC's svn repository. And most of my computers have Ubuntu (actually Kubuntu, but it doesn't make a difference for this task). I also have a fedora laptop, and I also have a rolling version of GCC there too. No problem.

Then in what mysterious ways have you been able to achieve this monumental achievement?

I wouldn't call it a "monumental achievement". Except for the time that it takes to compile all the code-base (a couple of hours), I never had too much trouble doing it. I followed the instructions carefully, made sure to install all the dependencies, and that's it. I remember getting a few errors, but I just copied the error message, googled for it, and found a fix within a very short time.

Do you have a specific problem?

Typically I get completely cryptic errors such as:: error 4 or error 2 WITHOUT any sort of error log available nor information to consult (this is very very typical of my experience with gnu).

Most of the time, if there are errors (which might be cryptic to you), they only show up on the terminal at a high-level, the error logs are located within the sub-directories of your build directory, they …

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

even if you take away the guns, people still kill each other... if you get to keep them, you still kill just as many people as you do without a gun.

That's false.

M. Killias, "International correlations between gun ownership and rates of homicide and suicide", Canadian Medical Association Journal, 1993. - Quote:

There was no negative correlation between the rates of ownership and the rates of homicide and suicide committed by other means; this indicated that the other means were not used to "compensate" for the absence of guns in countries with a lower rate of gun ownership.

L. M. Hepburn and D. Hemenway, "Firearm Availability and Homicide: A Review of the Literature", International Journal of Aggression and Violent Behavior, 9(4), 2004. - Quote:

Most studies, cross sectional or time series, international or domestic, are consistent with the hypothesis that higher levels of gun prevalence substantially increase the homicide rate.

The truth is, having a gun at your disposal makes it easier to commit a homicide or a suicide, and thus, more guns equal more homicides and suicides. All studies on the subject, whether international or state-by-state arrived at the same conclusion. The causality is obvious, and the correlation is apparent. That case is closed. The only debate is about how to effectively reduce gun ownership. And if I'm not mistaken that is what AD is trying to argue (by presenting titbits of anecdotal evidence), that the gun control laws being considered now, …

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

You can actually blaim scientists (and China) for our gun violance. (link). They started it all in about 700 AD.

Yeah, and you can blaim the Wright brothers for drone strikes too! (translation: don't blaim the people who do it and promote it today, blaim some dead guys from another era)

Brady Gun Bill == "Feel-Good about ourselves" bill with no real impact.

You keep repeating that gun control laws have no impact and are just to make some people feel good. All countries that have gun control laws have extremely low levels of gun violence, and all countries that don't have such laws have very high levels of gun violence (mostly third-world countries, plus the USA). That's hard to ignore, even within the right-wing echo-chamber (e.g., a majority of republican voters support stricter gun control). You can choose to cover your ears and scream "LA LA LA LA LA, I can't hear you", but you can't keep repeating your point and expect rational people to buy it.

I would agree that gun control is not going to solve the problem completely, not by a long shot, but it's a step in the right direction. But, of course, it is more of a measure to stop the bleeding (literally), not really a solution to the root of the problem, which is widespread desperation and obscurantism. There are a lot of things that distinguish other civilized countries from the US besides gun control, for example, …

Reverend Jim commented: I like the Wright Brothers' reference +0