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

I'm having trouble understanding what it is necessarily used for?

Consider this piece of C++11 code:

#include <future>
#include <atomic>
#include <vector>
#include <iostream>

int main() {
  int value = 0;

  std::vector< std::future< int > > results;
  results.emplace_back( std::async( [&value]() -> int { return value += 2; } ) );
  results.emplace_back( std::async( [&value]() -> int { return value += 3; } ) );

  for(auto& x : results)
    std::cout << x.get() << " ";
  std::cout << value << std::endl;
};

If you are not familiar with C++11 concurrency features (like std::future and std::async) I recommend you look it up. In essence, this code creates two threads (via async) that will execute a function that increments a shared value (value) by either 2 or 3, respectively. Then, the results are printed out, and then, the final value of the shared value is printed too.

The million dollar question here is: What will this code print out?

The stupid answer:
It should print out 2 5 5. If you have no idea what threads are or how they work, you might think that this code is obvious: start with (value == 0), then increment it by 2 and store the result in the vector, then increment it by 3 and store the result in the vector, and finally, the value ends up with a value of 5. However, you can't rely on the "first" thread executing "first", because they can either execute simultaneously or …

JasonHippy commented: Great post! +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I raised this issue of privacy in the cyber-world a few months ago. You might want to give it a read.

GrimJack commented: I just read through it - very thoughtful. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I believe you need to do a grub recovery.

The fact that you installed Ubuntu and Windows on separate hard-drives might be the root cause of this issue. How exactly did you proceed to do the installation? I know you went through the Ubuntu install menus, but what I want to know is: Did you temporarily remove the Windows hard-drive? Where did you tell Ubuntu installer to put the Grub bootloader? Are you chain-loading with the Windows bootloader (e.g., with EasyBCD?)?

If you temporarily removed the Windows hard-drive in order to install Ubuntu on the other, then I am not the least bit surprised that you have the error that you have. Upon installation, the Grub bootloader for Ubuntu is configured to point to the installed the Ubuntu OS, usually by the name of the hard-drive, and by "name", I mean the sequence number (i.e., first, second, third hard-drive). If you change the hard-drives that are plugged in afterwards, this changes, and nothing works. If Grub detects that the OS is not where it is supposed to be, it just jumps to the command-prompt to let the user boot the correct OS manually (which is hard). See this issue.

You can probably repair your grub bootloader by booting from your LiveCD and going through the repair / recovery menus.

If not, boot from the liveCD (i.e. "Try Ubuntu" menu) and re-install grub. Basically, find the identifier for the hard-drive on which you installed Ubuntu by listing the drives …

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

You are missing the curly braces in this for loop:

    for(int j=0; j<=years; j++)
    cout<<"Enter runs scored by player"<<":"<<i+1<<": ";
    cin>>record[i][j];

You'll see it better if you space it out and indent properly:

    for(int j = 0; j <= years; j++)
        cout << "Enter runs scored by player" << ":" << i+1 << ": ";

    cin >> record[i][j];

As you see, the cin >> record[i][j]; is outside the scope of the for-loop. The error message is telling you that the variable j is undefined at that point. The reason the error message is weird is because it use to be (before the ISO standard) that the variable declared in the for-loop would exist in the scope enclosing the for-loop (e.g., holding the value it had at the last iteration), this rule has changed and is no longer allowed.

To fix the error, you need this:

    for(int j = 0; j <= years; j++) {
        cout << "Enter runs scored by player" << ":" << i+1 << ": ";
        cin >> record[i][j];
    };
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Sources?

I already quoted the source, here it is again:

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.

You can follow the references in that paper to get more sources, and read to your heart's content.

You honestly think if everyone had a gun on them at all times crime will increase?

I don't have to "think" so, it's a fact, as established by the comprehensive study I quoted.

So if a person has a knife on him instead of a gun and they are panicked just because they have a knife because of a gun they won't do anything?

Let me elaborate, which I didn't think was necessary considering how obvious this is to understand.

Case 1: Accident:
James accidently stabs his friend John, while mishandling a knife, which is a rare thing to happen (stab by accident). He most likely inflicts a minor wound to John, immediately feels terrible about the accident, drops the knife, and helps John to get some medical attention. The chances that John survives are extremely high.

James accidently shoots his friend John, while mishandling a gun, which is still somewhat rare but significant. He most likely inflicts a serious wound to John, immediately feels terrible about the acccident, drops the gun, and helps John to get some medical attention. The chances that John survives are good but not great.

Case …

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

This all depends on how you want to install it.

One option is to use a virtual machine, like VirtualBox. This will create one big file (that you place wherever you like) that is a kind of disk image. Basically, with this option, you can install Ubuntu (or any other OS) within the virtual machine and run it like a windows program. This is not ideal from a "native" experience point of view, and won't be as fast, but it is a good option to try at first and doesn't require committing a partition and setting up a dual-boot system.

The other main option is to install Ubuntu on a separate partition and setup a dual-boot system. In this case, it's a bit more tricky and you have to be a bit more careful. The partition on which you choose the install Ubuntu will be reformatted (all data erased). Usually, you can create a new partition instead of wiping out an existing one. Under Windows' partition manager, you can shrink and move your current partitions (which will not erase the data) to create some free space (I would say 20Gb minimum, around 100Gb is plenty enough). When you boot from the LiveCD/LiveUSB to do the installation of Ubuntu, you will have to select that free space as the place to install it to, and it will automatically create the required partitions and format them. Of course, before you fiddle around with the partitions (especially if you have to move a …

kvahanyan commented: Good answer, covered most of the topics he needs +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

In the code above, it does return a pointer. This returns a pointer:

Rectangle* Rectangle::getInstance(int l, int w)
{
    static Rectangle firstInstance(l, w);
    return &firstInstance;
};

If you want to return a reference, you can use this:

Rectangle& Rectangle::getInstance(int l, int w)
{
    static Rectangle firstInstance(l, w);
    return firstInstance;
};

Either way, it's pretty much equivalent. A pointer is just a bit easier to deal with, but a reference is often preferred as a matter of good coding style.

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

you have it all wrong, no one wants to kill their neighbors we just want the right to protect ourselves and our family.

And from whom do you think you are going to "protect" yourself, if not your neighbors. That's what I meant.

Also it's more about having the god given right to protect yourself

Well, saying it's "god given" is pretty ungrateful towards the generations of people who fought (mostly with words) to give you those rights.

I'm referring to mostly outsiders, and extreme liberals in this country that believe taking weapons is the way to stop crime.

Empirical evidence is clear, reduce the gun possession means a reduction in crime. I won't discuss this further, this is just facts, and:
"Facts are stubborn things; and whatever may be our wishes, our inclinations, or the dictates of our passion, they cannot alter the state of facts and evidence." -- John Adams.

just not universal healthcare.

Yeah, because we all agree that some people just don't deserve to live. (sarcastic)
That's what "not universal" means, in case you didn't know.

When us "gun nuts" talk about guns it litterally means guns and it's also meaning the right to protect yourself which is essentially the peoples sentiment of security.

You misunderstood me. The "sentiment of security" does not mean that (at least, I didn't mean it that way at all). I have a sentiment of security when I can …

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

The Rectangle::getInstance(3, 3); is the syntax for calling a static member function of a class. Because a static member function is associated to the class only, not to objects of the class. In other words, regular member functions operate on one instance of the class (object), but static member functions do not, they are just defined as part of the class. Here are the different syntaxes:

MyClass my_object;  // this declares an object of class 'MyClass'.

my_object.callRegularMemberFunction();  // calls the function on the object 'my_object'.

MyClass::callStaticMemberFunction();  // calls a static function belonging to 'MyClass'.

my_object.callStaticMemberFunction();  // this is just for convenience, you can also call a static 
                                       // function on a object, but it is no different from the 
                                       // previous syntax with 'MyClass::'.

MyClass* my_object_ptr = new MyClass;  // declares a pointer to an object of class 'MyClass' and 
                                       // initializes it to point to a dynamically allocate object.

my_object_ptr->callRegularMemberFunction();  // calls the function on object pointed to by pointer.

my_object->callStaticMemberFunction();  // same as above, just an alternative syntax for calling 
                                        // the static function.

As for the Singleton implementation that you chose to use, it is a terrible one. There are many reasons why I recommended the Singleton implementation that I posted earlier. There are many alternatives that are really bad, the one you chose isn't the worse I've seen, but definitely not great. I highly recommend you go with the implementation I suggested instead.

As so:

Rectangle.h

#ifndef RECTANGLE_H_INCLUDED
#define RECTANGLE_H_INCLUDED

class Rectangle
{ …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Weapons are trivial for America to function, once they're gone it's OVER.

That's extremely sad. It's sad that you consider it a defining aspect of America; that people keep a piece of equipment in their house and be prepared to use it to kill their neighbors.

In some countries (..cough.. Canada ..cough..), people consider it a defining aspect of their country; that people would never wish harm on their fellow countrymen and have the confidence that their military could never even stomach the idea of turning their weapons onto their fellow countrymen.

In my perspective, when the people lose that sentiment, THAT is when it's "OVER".

My favorite quote: [...] "The people will not understand the importance of the Second Amendment until it is too late" - Thomas Jefferson

You might consider making this your new favorite quote:
"An educated, healthy and confident nation is harder to govern." -- Tony Benn

You seem so passionate about the issue of your guns being "jeopardized" (I am not sure what exactly you are referring to... the recent extremely weak and short-lived attempt at closing the gun-show loophole?). You might want to direct some of that passion towards other threats that are much more real and well underway for decades. I'm referring to the threats to the education, mental and physical health, and confidence of the American people. In the last decades, the education system has become massively underfunded, and undermined by pretenses that "teaching facts and critical …

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

This is called a Singleton class.

The most straight-forward way to implement it in C++ is as follows:

// in the header file:

class MySingleton {
  private:
    // private constructor:
    MySingleton() { };

    // private copy-constructor (left undefined):
    MySingleton(const MySingleton&);
    // private copy-assignment operator (left undefined):
    MySingleton& operator=(const MySingleton&);

  public:

    // public static function returning a reference to the singleton class:
    static MySingleton& getInstance();

};

// in the cpp file:

MySingleton& MySingleton::getInstance() {
  static MySingleton instance;   // a static local variable is initialized on first call to the 
                                 // function only, afterwards, it is always the same variable
                                 // for every subsequent calls to the function.
  return instance;
};

You can, of course, do the same but return a pointer, whichever you prefer.

With the above scheme, the user of the class simply has to use the getInstance() static member function to obtain the unique instance of the class. The instance will be unique within a single program. Because the copy-constructor and copy-assignment operators are private and undefined, it is impossible for a user to copy the instance either (called the Noncopyable idiom).

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

The type char arrayOnes[10]; is an array of 10 characters. In your initializer, you are defining an array of strings (which are themselves arrays of characters). This would be the correct version:

const char* arrayOnes[10] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

The above defines an array of pointers to const-characters. A pointer to a const-character is the type of string literals like "one".

Of course, in more modern C++, we don't really use those kinds of C-style arrays anymore. In C++11, you would do this:

std::vector< std::string > arrayOnes = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You just forgot the * next to the type Object in your for-loop. It should be:

for( std::map<string, Object* >::iterator itr=_c.begin(); itr < _c.end(); itr++)
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

In RPM-based systems (Fedora, Red Hat, etc.), you generally use the yum command:

$ sudo yum install package_name

(where package_name is the name of whatever package you want to install, not the file name, just the name)

In Debian-based systems (Ubuntu, Debian, etc.), you generally use the apt-get command:

$ sudo apt-get install package_name

If you happened to have downloaded the package file manually, then you can install them directly.

In RPM systems:

$ sudo rpm --install package_file_name.rpm

In Debian systems:

$ sudo dpkg -i package_file_name.deb

On most Linux distributions, however, if you simply double-click on the rpm or deb file from the folder navigator (Dolphin, Nautilus, etc.., the "Windows Explorer" thing), it should auto-launch an installer window.

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

As simple as this:

#include <iostream>   // to print to console
#include <fstream>    // to read / write to a file
#include <string>     // to represent words (strings)

int main() {

  std::ofstream output_file;
  output_file.open("test.txt");       // open a file for outputting to it.

  std::string data = "Hello World!";  // create some "data" to be written

  output_file << data;                // write the data.

  output_file.close();                // close the file.

  std::ifstream input_file;
  input_file.open("test.txt");        // open the file for input.

  std::string data_from_file;         // create some place to put the data in.

  getline(input_file, data_from_file);// read one line from the file.

  input_file.close();                 // close the file.

  // finally, write the result on the console:
  std::cout << "Received this data from the file: " << data_from_file << std::endl; 

  return 0; // everything went well! Return value of 0.
};

You could easily split the reading and writing parts into two separate programs and you have what you asked for. For more info, read this tutorial.

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

There might be a stray character on the input stream. Try to use cin.ignore(); before the second input.

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

Mainly, stay away from those that are the most "strip down" distributions. You might hear that they are preferred by some programmers, but that's implying they are good programmers and experienced Linux users who like to temper with the system or set it up exactly as they want. Distributions to avoid are things like Arch Linux, Debian (pure Debian, not the derivatives), and anything based on Slackware, or any of the "server" versions (which usually means no GUI, no user-software, only server software tools). Most of these distributions are stripped to essentials or come with very little software such that you can build it up to your exact desires, and will inevitably require lots of familiarity with the terminal / shell (command-line interface).

Distributions that are friendly for the new user mainly include:

  • Ubuntu (and its friends) (desktop versions)
  • Fedora (and its spins) (desktop versions)
  • Linux Mint
  • OpenSUSE
  • CentOS, Scientific Linux, etc..

Just checkout the main distributions on distrowatch. One of the reasons to stick with one of the more popular distributions is to minimize the potential (and real) trouble when installing and configuring it (i.e., more popular distributions have been tested on more computer models and peripherals, and have a bigger community of people sorting out problems). There are usually some hick-ups when you first install Linux, so be careful and be prepared to have to do some troubleshooting to get everything running smoothly (there are usually a few peripherals and drivers that won't work right …

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

Any Linux distro is good for C++. The C / C++ languages are fundamental to Linux and GNU tools, not so much in Mac (C / Objective-C are the preferred language, and C++ is pretty terrible to use on Macs).

Qt is also a great choice for Linux (and all other OSes). Eclipse also works in Linux, as well as all the Qt development tools (Qt Creator, Qt Designer, Qt Assistant, qmake). I personally prefer KDevelop as my IDE.

I really like the Qt-based desktop environment called KDE. Any distro that uses KDE is a great choice in my opinion (Kubuntu, OpenSUSE, Fedora KDE-spin, etc.). KDE is a somewhat more conservative yet user-friendly and customizable desktop environment, and in many ways, it is very programmer-friendly. And of course, it is tightly integrated with Qt. In other words, it is a platform programmed in C++ with Qt, and it has lots of software to facilitate programming in C++ with Qt, i.e., made by C++/Qt programmers for C++/Qt programmers (among many other types of user).

But again, any other Linux distro is going to work great too for C++ programming, and overall it doesn't matter that much which you choose on that front since most Linux software is available in most Linux distributions. So, choose the distro you like best from a "normal" user perspective.

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

First, you need to use standard headers and only standard headers. The headers like iostream.h are pre-standard (before 1998), and should no longer be used, more the .h part (note: this is for standard headers only). The C-standard headers like math.h and stdlib.h must have the .h removed and a c must be added to the start. The conio.h header is an old and non-standard header dating back to the times of MS-DOS, few compilers still support it. So, the list of includes become:

#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>

Since the standard (1998), everything from the standard libraries are in the std namespace. So, things like cout are actually std::cout. To avoid having to put the std:: everywhere, you can just write this after the includes:

using namespace std;

Now, the code starts as follows:

int main() {

  char Continue;
  do
  {
    cout << "How many sales items do you have? : ";
    int hval;
    cin >> hval;

Notice that I have removed the list of variables that you were declaring at the start of the loop. Declaring variables en masse at the start of a function / loop is an archaic practice and is generally discouraged. Instead, declare variables close to where they are first used.

For instance, here I declare the isTotval just before I have the loop that computes the total of the sales items. Also, individual sales items are inputted in a local temporary variable ival, which …

adil.ghori commented: very very helpful.. Thank You Mike :) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There isn't much point in delving into ICs unless you plan to mass produce. They are just electronic circuits made to be much smaller, far less energy-hungry and much cheaper to produce. If your interest is semi-conductor physics than that's one thing, but if your interest is electronics, do electronics, not integrated circuits. I.e., concentrate on the "circuit" part forget the "integrated" part, until you work for a big firm or research center, as rubberman pointed out.

If you want to do really low-level electronics stuff, you would normally build the circuit around a number of simple (and cheap) ICs for specific purposes (level converters, gate arrays, standard transistor bridge configurations, etc.). You would build the circuit as a custom PCB (Printed Circuit Board), which you can easily and cheaply make either through a company (you send them the plans and some money, and you get a shiny PCB in the mail a few weeks later) or by yourself (you can buy some home do-it-yourself chemical PCB etching kits).

If you are more interested in programming this kind of thing, then go with programmable logic instead. With a good micro-controller and a little bit of electronics work, you have what is needed to write the firmware for this. In fact, I'm not sure you could create a RAID module without a micro-controller of some kind (I don't know enough about RAID).

If I had to do this (i.e., most effective home-made solution), I would probably just replicate the USB connection …

ddanbe commented: Good explanation +14
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, the most complete source for information on the pre-processor is the section on it in the C++ standard document (you can download the draft for free, almost identical to the actual thing). The section only has 11 pages (which is extremely short of a chapter of the standard). The pre-processor is really simple, because it really should only be used for really simple things.

christinetom commented: Very extensive.. Thanks for the help. +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I haven't explored Chrome extensions all that much, but here are a few that I use and like:

Grammarly Lite - "Smart" spellchecker.
Session Buddy - This is an extension to manage sessions (a collection of open tabs). It is nice because if you have to close all browsers or shutdown the computer, you can just save all your current tabs as a "session" which you can reload later (when you come back).

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

What makes you think that there is supposed to be a sequence of characters at the end of a file that indicate that the file has reached the end?

The EOF flag is artificial, it doesn't appear in the files. If you try to read / write to a file and the OS determines that you cannot because you have reached the end of it, you get the EOF flag as a result of the operator (either by setting the eofbit in the stream or returning EOF character from the char-read operation, or both).

The other place where you might use the EOF character is in an ASCII file that you want to artificially split into different files. But this only works for text files which will be read and interpreted. If you read a text file (non-binary), the characters that are read are interpreted, and if a EOF character is found, the stream will go into a failed mode, indicating that you have reached the end. If you expect more data to exist (i.e., another "file") then you can clear the error bits and try to read again. This can be useful, for instance, to pipe multiple files between programs in a BASH shell.

The character(s) is ignored in binary files, and it isn't a meaningful character that should appear for any other reason in a text (ASCII) file. When you do binary reading / writing, the operations are "unformatted", meaning the characters are not interpreted, and thus, any …

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

Alright, for the sake of do-it-yourself experience, we can discuss how you could do it.

The central issue here is something called "type erasure". This is something you encounter for time to time in C++. It's not always possible but often useful. The Boost.Function library (and the standard std::function template) do type erasure on function objects (or function pointers).

BTW, your solution, using the void*, is what people would call a "poor man's type erasure technique". It is very often used in C (or C-style C++), because that's pretty much the only technique available there. The fluff you have with the to and from functions is just eye-candy.

In your case, what you want is for the caller of the callback function not to have to care about the type of the function it is calling, nor about the type of the parameters it is giving it, if any. So, these are the types you want to "erase".

In your problem, the caller doesn't know anything except that it must call the callback function. Even though, in your code, you provide a void* to the function call, in reality, the caller contributes nothing of its own to the function and does not expect anything back either. So, for the sake of not complicating things more than they need to be, your caller should look something like this:

void call_function(some_callable_type f)
{
    f();  // provides no parameter, recieves nothing in return.
}

The some_callable_type should not be a template …

rubberman commented: Nice explanation mike! Worth reading. +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The database part is almost definitely better handled with a database engine. A reasonably good and cross-platform, and free one is MySQL. All database engines are setup in a server-client arrangement over a network (or loopback). And most GUI toolkits (I recommend Qt) have a number of pre-existing widgets to deal with databases (query data, display, insert entries, etc.), and for the rest, you just some database-client library (like libmysql). In other words, you could solve your problem simply with this arrangement:

Server: 
  - Run a MySQL database server (or some other database server)
Client:
  - Use a mix of pre-existing database widgets and of custom code to communicate with the server
  - Create the rest of the eye-candy GUI

This means you only really need to code one application, and you don't need to worry about complicated server-client coding. It's going to be a walk in the park.

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

You're correct. The standard sort function will provide const objects to the comparison function. When calling a function with a const object as parameter, the function must take the object either by const-reference or by value. This is why changing the signature of the comparion function to non-const references does not work. And because you need non-const objects inside that function, the only remaining solution is to take those parameters by value. This is, of course, wasteful (useless copy), but that's one of the consequence of not caring to const-qualify things properly (i.e., making the "name" function non-const is stupid, leading to more stupid / wasteful code).

9-2. If we define the name function as a plain, nonconst member
function, what other functions in our system must change and why?

My answer to this question would be that every piece of code that depends on this function will have to change and code that relies on conventional constness rules will be broken, because making the "name" function non-const is a major breach of the integrity and consistency of the class' interface. I guess that's the lesson that this exercise is supposed to teach you.

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

I really enjoyed the interview. It was quite endearing how Dani was giggling the whole time. One thing I got out of this interview is that Dani, you really got your shit together! (pardon the language) I mean, you clearly understand this business well, from the technical and marketing side, and that's impressive. I've grown to respect you a lot over my years on Daniweb. You're a force to be reckoned with.

One of my biggest regrets today is that I never got my MBA.

Pfff.. You could be a guest lecturer in an MBA course. The purpose of an MBA is to pad a resume, you don't need that, you've got more than a million Daniweb members padding yours.

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

First of all, if you don't need the AbstractClass beyond the scope of the constructor, then all you need to do is make the constructor templated:

class FileWriter {
    ofstream file;
  public:

    template <class AbstractClass>
    FileWriter(const string& fileName, const AbstractClass& ab) {
        // must turn on io-exceptions, as the only way to signal error from the constructor.
        file.exceptions( ofstream::failbit | ofstream::badbit );
        file.open( fileName.c_str() );
        file << ab;
    }

    ~FileWriter() {
        file.close();
    }
};

Second thing is, I don't understand why you want to have a constructor that does the serialization of an object. It doesn't make sense. The only way to use this class is to create a temporary FileWriter to serialize one object, and then immediately destroy that temporary writer object. In other words, it will always boil down to this function:

template <class AbstractClass>
void writeToFile(const string& fileName, const AbstractClass& ab) {
  ofstream file;
  file.exceptions( ofstream::failbit | ofstream::badbit );
  file.open( fileName.c_str() );
  file << ab;
}; // file will be destroyed here, which closes the file.

Why do you need a class to do this? At the very least, your FileWriter class should have the constructor and object serialization split into two functions to make it more usable:

class FileWriter {
    ofstream file;
  public:

    FileWriter(const string& fileName) : file(fileName.c_str()) { };

    template <class AbstractClass>
    void write(const AbstractClass& ab) {
        file << ab;
    }

    // convert to bool to know if the writer is in a good state.
    operator bool() const { return …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I just tried it out. I have Kubuntu 12.10, with python installed (default) and with the mxDateTime and Mako installed as instructed by JasonHippy. I extracted the Haizea sources as instructed, I launched the setup.py as instructed, and received a message similar to yours (ending in "Writing ... haizea-1.0.egg-info"). All seems to have worked correctly. I also ran the test to verify the installation and it works just fine. Did you try the verification? If it tells you something like:

IOError: [Errno 2] No such file or directory: '/usr/share/haizea/traces/sample.lwf'

then you just have to go into the sample_trace.conf file and look for the path to this file and change it to wherever the file was actually installed (might be /usr/share/haizea/traces/sample.lwf, or /usr/local/share/haizea/traces/sample.lwf, or ~/share/haizea/traces/sample.lwf, depending on where you installed haizea, you seemed to have installed it in /usr/local, which is good).

As for your troubles compiling Python, well... as JasonHippy said, you DO NOT NEED TO DO THAT. Compiling Python from sources is likely to be quite a task in itself (probably has a gizillion dependencies), and there is no reason to do it. (btw, if libffi is missing, just install it: sudo apt-get install libffi-dev).

JasonHippy commented: Been away for a few days. Cheers for picking up my slack on this! And a really good, accurate response as ever too! :) Thanks Mike! +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The answers given by the OP are correct, that is, 1: B & D and 2: B. The explanation is as follows:

1) The Linux naming convention for hard-drives has the first two letters to identify the kind of hard-drive it is, usually "hd" for normal hard-drive and "sd" for a SATA-connected hard-drive (as opposed to the old IDE connections). The letter after that is just an alphabetic order letters to identify the drives (a: first, b: second, etc..). And then, the number is the number of the partition. Thus, hdb2 is in a "hard-drive", it is in the second physical hard-drive, and it is the second partition of that hard-drive. Thus, the answers are B and D.

2) Both a DLL and an EXE contain executable code, so, (a) is false. Both a DLL and an EXE contain mapped addresses of executable code (i.e., exported symbols, as they are usually called), so, (c) is false. And a DLL does not necessarily, and almost always not, contain all the executable code for a program, so, (d) is false. By process of elimination, (b) must be the correct answer because it is quite true that there is very little difference between a DLL and an EXE, in fact, the differences are quite trivial, just a flag that is different (to tell the OS whether it is a EXE or a DLL), and the fact that an EXE is expected to have a main() function while a DLL is expected to optionally …

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

So how can I distinquish the difference? In other words, how can I figure out which kind of T** they are passing?

You can't. There is no difference between T** (pointing to an array of arrays) and T** (pointing to a pointer to a T variable) from a type perspective. You can file it under "another reason not to use C-style arrays".

When using a "strongly typed" language, if you wish to benefit from static type checking, it is your responsibility to correctly and strictly encode the requirements of the passed parameters into their type. A type like T** does not enforce any requirement other than "it must point to a pointer to T". The requirement that the first parameter should actually refer to an array of arrays is not well represented by the type that you used for that parameter. The compiler can only enforce the requirements that you laid out.

The solution here is that you should have some other type that would be more strict. This could simply take the form of std::vector< std::vector< T > >, or some other more general type. Maybe a custom type like Matrix<T> or something like that. Otherwise, you'll have to accept that this function is just weakly typed, and cannot ensure, statically, that the passed parameter is truly of the correct type.

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

Well, for one, you must always turn on all the warnings (-Wall) when compiling your code, and most compilers will warn you when you are using uninitialized variables, or that a variable might be uninitialized at some point.

If the type is not a trivial type (int, double, etc.., and some trivial classes), then it will always be default-initialized or zero-initialized. Only trivial variables can be truly uninitialized (i.e., have some garbage value).

Some compilers (e.g., Visual Studio, Borland, etc.), under debugging-mode, will fill all uninitialized memory with some weird bit-pattern to informally mark them as being uninitialized. When you are debugging and reading a stack dump or memory dump in hexadecimal form, you will see patterns like 0xBAADF00D or 0xDEADBEEF in the memory, those correspond to uninitialized memory. The reason why this is only done in debugging-mode is because it is an expensive operation, and any correct program cannot be relying on any kind of uninitialized memory, so, it is useless in any final product / application.

Uninitialized variables have an undefined value. This means that a correct program cannot use that value under any circumstance. And for that reason, there is no such thing as a function to "check if it is initialized" because that would imply the possibility of reading the value of an uninitialized variable, which is undefined behavior, and thus, an incorrect program. In other words, such a function would be, by definition, a guaranteed bug in your program.

The solution, of course, is to …

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

we even get some very minimal traffic from North Korea. Just because people from North Korea may visit DaniWeb can't possibly mean that we have to uphold North Korean internet and privacy laws!!

But it does mean that the site should be usable from a Windows 95 computer. ;)

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

The spelling went away when the old system (vBulletin) was replaced. It has been a constant irritant ever since. People (including me) have asked for it many times. I think there is some technical reason why it is kind of hard to do, but I don't buy it. I think it is long overdue now.

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

If the option is between this:

int row_locs, col_locs;
int row_descriptors, col_descriptors;
double **locs;
double **descriptors;

call_function(row_locs, col_locs, row_descriptors, col_descriptors, locs, descriptors);

and this:

struct return_struct {
    int row_locs, col_locs;
    int row_descriptors, col_descriptors;
    double **locs;
    double **descriptors;
};

return_struct result = call_function();

Then, it depends on whether the function gets inlined or not. If inlined, the two will probably be identical, and I mean, literally identical (same machine code) (or maybe just a different order on the data on the stack). If not inlined, then the second option will probably perform a little bit faster. Like others have said, the performance difference is probably not worth worrying about, until you identify it as a performance issue.

The reason that the second version could be faster is just because it's almost guaranteed that the compiler can do a return-value optimization on a POD type (the struct). What RVO means is that the copy of the return value is optimized away. In other words, the return value (the struct) is constructed directly at the destination, instead of being copied. So, with RVO, there is no copy and no indirection required inside the function (indirection: de-referencing pointers or references). When passing references into a function, the compiler cannot optimize away the indirection unless the function is inlined, so, you avoid the copy for sure but you suffer from indirections (which is not significant overhead, especially if they reference stack-based variables). Passing by value and returning by value will avoid …

deceptikon commented: Good as usual +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Isn't is easier to start with Petzold if one is going to program under Windows?

There are a few problems with this. First, GUI programming is not the be all and end all of programming, it's merely a tiny (and rather trivial) subset of it. Second, not everyone targets Windows, and learning C++ and learning Windows programming are two very different things that have to be treated as two separate learning processes. Third, why learn to do specific Windows programming when you can easily learn to use cross-platform tools that develop equivalent skills yet are more durable and useful in industry. Fourth, Petzold's books don't teach C++ at all. The pre-.NET editions teach you about the Win32 API and uses the C programming language (not C++), both of which are interesting for legacy reasons but a largely outdated these days. The post-.NET editions are in C#, with some examples translated to C++/CLI (or C++/CX, or whatever the latest re-branding of Managed-C++ is), neither of which have anything more to do with C++ than Java does, which is a terrible pathway to learning C++. And finally, Petzold himself stresses the fact that these are not books that teach programming, knowledge of programming is assumed prior to reading the books, they are just guides to help a capable programmer find his way around Windows' APIs. So, certainly, this is nowhere to "start with".

And this thread is about books that teach C++ programming, let's keep it to that, otherwise it …

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

What you are saying is that a DLL with a properly written c-interface can have its functions (or classes if in c++) called by pretty much any language that supports calling c functions and on most operating systems

Well, if by "most operating systems" you mean "Windows-only" (and probably a relatively recent version of it), then yes. DLLs are only for Windows, and they could use code (via OS calls) that are not supported on older versions. In every other kind of operating system (all Unix-like environments), we don't call them DLLs, we called them "shared object files" (with extension ".so") and they are similar to DLLs, but they are also very different (and far more powerful, actually).

whereas a static link library would only really work for people using MY compiler (or a similar one).

Not exactly. Here again the world is split as Microsoft vs. the World. If you use the Microsoft compiler (MSVC) (with .lib extensions for static libraries), then, yes, static libraries are not compatible between compiler versions, but there are really only a few versions (2008 (MSVC9), 2010 (MSVC10), 2012 or 2012-nov-update (MSVC11)) that anyone would reasonably still use today. All other compilers (except for older Borland compilers) use the Intel C++ ABI standard, and all the C/C++ static libraries (and dynamic libraries) are compatible across all versions since the adoption of that ABI standard. So, in the non-Microsoft world, all these issues we've been discussing don't really exist.

Another thing, …

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

I have written DLLs and SLLs? before, but I never fully understood them.

Ok. Let's take it from the top. When the compiler compiles each c/cpp file, it generates an object file (usually with extension .o or .obj, depending on the compiler). These object files contain, among other things, a section of compiled code for each function. That section of code is marked with a symbol to identify it (the symbol is usually the function name, possibly with some extra decoration). Any function call in the code usually remains in the object file as a symbol reference, that is, a kind of "this needs to be replaced by a jump to the final address of that function" marker.

Then, the job of the linker is to take all the object files, collect all the symbols into a massive symbol table (i.e., associates symbols with where its corresponding code can be found), and then goes through all the symbol references and replaces them with a jump to the appropriate code (finding the symbol in the table is called resolving the reference (and hence the errors like "unresolved reference to ..."), and replacing the reference with a jump (or call) is called linking).

A static-link library means that the linking is done completely before generating the final executable or DLL. Essentially, a static-link library is just a collection of object files packed together in one file. Linking to a static-link library is pretty much identical to having all the cpp …

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

I had no idea you could do that little struct myClass thing and actually use a class in there for the c implementation.

In C++, struct and class can be interchanged at will. The only difference between the two is the default access rights (private for class, and public for struct) and the default inheritance (private for class, and public for struct), but these only matter for the declaration of the class/struct (i.e., where you have all the data members and functions). When the same class name appears in multiple places, it is usually because there is one declaration and then a number of other things like forward declarations and friend declarations. In those multiple places, it doesn't matter (strictly speaking) whether you write struct or class. However, some compilers might complain with a warning.

can you just pass a void pointer to the c-style functions and then cast it to a class in the c++ definition of the function? I would have guessed that would be impossible.

There is a requirement in the C++ standard that states that any pointer type can be cast to a void* and that for any type A, a pointer to an object of type A (lets call it a_ptr) can be cast using void* v_ptr = reinterpret_cast< void* >(a_ptr); and then cast back to a pointer to type A, yielding the same as the original pointer, i.e., ( a_ptr == reinterpret_cast< A* >(v_ptr) ) will always be true.

This …

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

African or European?

Have you ever been to Disney Land / World?

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

You are going to have to explain what you are actually trying to achieve, because it's really not clear at all from the code.

Then, there are a few obvious problems, of course.

First, seeing stuff like this:

typedef struct { /*something here*/ } *myNewType;

makes steam come out of my ears. Don't "hide" pointer types behind a typedef, especially not raw pointers, and it's even worse when you don't even mention the fact that it is a pointer in the name of the typedef. Just don't do it. I can live with people doing things like typedef std::shared_ptr< MyClass > MyClassPtr;, because there is a benefit in shortening the type name and passing a shared-pointer around is quite safe. For raw pointers, I say, no way José!

Second, defining a MACRO to replace the main function, well... that's just terrible. Any solution that requires this (or similar nasty hacks) is a bad solution, period.

Third, I'm trying to understand whether you are trying to wrap a C library with some C++ code or whether you are trying to expose a C++ library with a C interface. Although the latter is more usually the case, your code is very odd if that's what you are trying to do. The sort of canonical code for exposing a C++ library via a C-compatible interface goes something like this:

#ifndef MY_CLASS_H
#define MY_CLASS_H

#ifdef __cplusplus

class MyClass {

  /* some C++ code, as usual */
  public: 
    void foo();  // some …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think it's too big, that's all. Consider this is a heading

Some Heading

and this is a sub-heading:

Sub-heading

I think that the current sub-headings are the size that the headings should be and then have a smaller/different font for the sub-headings. I always thought it was weird to be able to create headings that are the same size as the thread's title.

bguild commented: Agreed! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I was just looking a this thread with a lot of quotes (people quoting each other) and there were these really weird graphics (see the attached snapshot).

I'm using Chrome:

Google Chrome   26.0.1410.63 (Official Build 192696) 
OS  Linux 
WebKit  537.31 (@147513)
JavaScript  V8 3.16.14.11
Flash   11.2 r202
User Agent  Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31

a6e878ffd975a92ad73f17a72bb71fae

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

While this has been alright for me and those involved in my department, I've been thinking about what problems may arise when someone other than me (in the future) has to analyze and fix the problems. Because of the lack of documentation, future maintainenance will be a big issue if I'm not the one maintaining this beast.

What I always like to remind people too is that there isn't much difference between someone who is a stranger to your code and yourself a few months down the line when you've moved on and don't remember much of the details of the code. So, this is not only going to be an issue if someone other than you has to maintain it, it is also an issue if you have to maintain it later. If in six months you get asked to update or fix some bug in the details of an implementation that you wrote 9 months earlier, will you really be able to just jump right into it? Or will you have to re-learn all about the details of the implementation? Probably the latter.

All that being said, are you thorough with your documentation and do you document every aspect of your projects? Or, do you have a document writer?

It can be quite difficult to keep up with this, I know I have a hard time doing it. It's really a multi-tier system. If I start from the inside, going towards the outside, I …

Stuugie commented: Great post, thank you very much! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

For a linked list, the easiest is probably to save all the nodes (without the pointers) sequentially in the file, and then reconstruct the linked-list when loading the elements.

I suggest you read up the documentation of Boost.Serialization to understand the logic of doing saving/loading of objects. Naively doing is.read(reinterpret_cast<char*>(&o3), sizeof(a) ) is not correct or robust in general, even for primitive types (i.e., because of endianness).

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

I am a billionaire! .... Well, if I count everything in Vietnamese Dongs!

Have you ever crossed a polar circle?

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

You cannot open a file in append mode (std::ios::app) to read from it (input). Technically speaking, it doesn't make much sense to open a file for "appended read operations". As far as the C++ standard goes, it says that this is implementation-defined (i.e., will behave differently depending on the system). Some implementations will just ignore the "append mode" request, and open it normally. Some implementations will refuse to open the file (which is what I suspect is happening here). And some implementations will open the file and move the read-position to the end of the file (making the very first read operation hit the "end-of-file" marker). In other words, don't open an input file-stream in append mode.

N.B.: the vagueness comes from the fact that files in different systems (Windows vs. POSIX) behave differently, and there couldn't be a consensus, so it was left as "implementation-defined". In practical terms, it means you can't reliably use it.

When a file is not opened, the read operation leaves the memory unaltered, which explains the "garbage" values that you see (i.e., uninitialized data). Try this:

a o3,o4;
ifstream is("test.txt", ios::binary | ios::app);
if( is ) {
  if( is.read(reinterpret_cast<char*>(&o3), sizeof(a) ) )
    cout << "o3.get() => " << o3.get() << endl;
  else
    cout << "Read operation on input stream failed!" << endl;
} else {
  cout << "Input stream could not be opened!" << endl;
};

My guess is that you will get one of those two error messages to print out.

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

I guess I agree with Labdabeta.

It's a matter of balance. There are things that you need to code, and there are things that would be really stupid to do via code.

The reason why drag-drop GUI designers exist is because it is really asinine to do all that in the form of code. For example, if I'm creating a notepad application, I need the edit area to be resized every time the window is resized, i.e., it should fill the window. I could code this up via an "OnResize" event with code to update the size and placement of the edit area within the resized window area. But doing this would be a waste of time, if all I need to do is check a checkbox in a GUI designer to tell it that I want that component to expand along with its parent window. And then, I won't even talk about how wasteful it would be to actually have huge lengths of code that just place components at the right place and resize and all that stuff. Doing all that stuff via code is like creating a 3D model with lots of code that creates the mesh with hard-coded points. When you think of it that way, and know how stupid it would be to create your 3D models like that, you realize why drag-drop GUI designers are good and what they should be used for.

And then, of course, you have stuff you need to do with …

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

At first glance, the whole "Option 0: Do nothing" versus "Option 1: Do what I propose" just reeks of false dichotomy. If I was a law-maker I would dismiss the proposal on that basis alone. There is no way that a serious person doing a serious proposal would have found that there are only two possible options, nothing and his own idea. Law-makers passing this show a great lack of basic critical thinking skills, they ought to be ashamed in requiring such a low standard for what a serious proposal is. Not to mention that the document itself looks like it was drafted by a high-school student.

That said, I don't disagree too much with the proposal / law, per se. It is clearly directed more towards the classic preconception of "orphan work" as kind of old footage, recordings or pictures, that people might want to use as part of a documentary or something. I think the provisions are OK for those purposes. But, obviously, the issue is complicated by the fact that in our insane IP-landscape, things like software are also under the same copyright classification as these works of arts, when, clearly, these are apples and oranges.

The problem with something like software development is that I can write some open-source code (say, under GPLv2 or GPLv3), and then a company can grab that code, strip away the license notices and meta-data in the files, and use it to create some closed-source application, and I will probably never …

Ketsuekiame commented: Good analysis. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It's also nice to be a native-code programmer, because you always have an excuse to take a break.