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

Like I said, the Taylor series is not going to work very well if you move too far away from 0. In this case, it seems that beyond -pi,pi, it stops working. What you need to do is to bring the angle back within that range, using the identity cos(a + 2*n*pi) = cos(a) for any integer n (positive or negative). In other words, add or subtract 2*pi until you get within the range, like this:

while(x > M_PI)
    x -= 2 * M_PI;
while(x < -M_PI)
    x += 2 * M_PI;

Put that code at the start of your function and it will work. (i.e., 6.28 is going to be near 0).

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

That's a whole different story. I'm not sure whether you mean (1) you want to avoid creating an OpenGL window and just render to an image, or (2) you want to render to an image without "affecting" the framebuffer (for the stuff drawn to the screen).

But first, you have to understand a couple of things about OpenGL. Specifically, the difference between "device context" (DC), "rendering context" (RC) and "framebuffer" (FB), which is one of the most awkward parts of OpenGL's design. Let me draw you a little diagram:

      OS
      |
      DC  <---  RC  <---  glDraw..()
      |         |
      ---  FB ---

What I'm trying to represent here is that the Operating System (OS) creates and controls the device context, which acts as a kind access-point to the GPU to be able to draw things on a window (GUI) that the OS controls (Windows GDI, or Linux/Mac/Unix X Server). Then, in OpenGL, you can create a rendering context (glCreateContext) to match the DC and attach it to that DC (glMakeCurrent). The RC acts as an access-point between the application (where you make OpenGL calls to draw stuff, like glBegin() / glEnd()), and an execution context inside the GPU that can actually do the drawing. And finally, you have the frame-buffer, which is essentially the data structure shared by the DC and the RC, and which represents what is actually drawn to the screen (if the window is visible, not minimized, etc.). In other words, the FB is the …

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

The piece of magic code needed is glReadPixels(). Like this:

int width=500;
int height=500;
uint32_t *colours=new uint32_t[width*height];

glBegin(GL_TRIANGLES);
//other drawing stuff, preferably no magic here?
glEnd();

glReadPixels(0, 0, width, height,
             GL_RGBA, 
             GL_UNSIGNED_INT_8_8_8_8,
             colours);

uint32_t c = *colours; // c should be the top-left pixel rendered by opengl

I don't know if it will start at the top-left or bottom-left corner, but that should be easy enough to figure out.

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

I would also point out that you don't need to calculate the factorial from scratch at every iteration and the same for the pow(x) calls, you can just calculate them as you go along with the main loop:

#define MAX_ITERATIONS 100
double cos(double x)
{
    // Set the total sum to 0:
    double sum = 0.0;

    // Create a sign to be flipped at iterations:
    double sign = 1.0;

    // Create an accum. for factorial:
    int fact = 1;

    // Create an accum. for power-of-x:
    double pow_x = 1.0;

    for (int i = 0; i<MAX_ITERATIONS; i+=2)
    {
        sum += sign * pow_x / fact;

        // flip the sign:
        sign *= -1;

        // accum two powers of x:
        pow_x *= x * x;

        // accum two factors of factorial:
        fact *= (i + 1) * (i + 2);
    }
    return sum;
}

Also, I should point out that the Taylor expansion you have there is centered around 0. So, you should not expect it to be a very good approximation as you move away from 0. A trick is to use trigonometric identities to be able to calculate things closer to 0 and then transform it back into the correct range.

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

Yeah, Old English and Old-Middle High German are very similar, but OE is a bit closer to Old Norse (which is kind of like modern-day Icelandic, which explains, for example, the "th" sound in English, and not in German). I recommend watching some of ProfASAr videos for a more elaborate exposition of all the germanic languages (incl. English) (according to times and places).

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

There are a few legitimate uses of goto, but it's not that it should ever be used carelessly. The main legitimate uses I can think of are: the "multi-break" and the "C-style cleaning". The "multi-break" refers to the problem of breaking out of a more than one nested loop at once, which is awkward without goto (usually involves flags and chaining of breaks). The "C-style cleaning" refers to the clean-up code that is needed when one chooses to use C-style constructs like dynamic array (with new[] or malloc()) instead of C++-style RAII objects (which automatically clean up during stack-unwinding). In that case, a goto (or set of gotos) beats repeating the clean-up code at every return-point, and risking repeating bugs. That C-style stuff is arguably no longer relevant in C++ though (I don't think I ever wrote a C++ function that required clean-up code, beyond the destruction of the stack objects).

Anyways, for such simple code, a goto is clearly not needed and should be avoided for good practice, in favor of a for-loop:

for(int i = 1; i <= n; ++i)
  f *= i;

Oh, and I can't finish without pointing out that the code shown is pre-standard (and non-standard). It seems to use a version of C++ before namespaces existed. This seems to match the screen-cap, i.e., MS-DOS from late 80s early 90s (i.e., more than 20 years old). The modern version of the code is, more or less, this:

#include <iostream>

int main() { …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Nobody is a saint. Most Saints were not saints. Even Ghandi had several darker sides to him (like his outspoken racism against African blacks).

Everyone is a mixed bag. Some good, some bad. If you have to tally it up, there is no doubt Mandela had a huge positive impact. Regardless of the more violent-rebelious nature of his early actions (pre-emprisonment), and the latest troubles with the ANC.

Elevating people to sainthood is not about some sort of mass-delusion to think that the guy is all good. It's about focusing on and being inspired by the good and the admirable parts of his legacy or life. Case in point, if you focus on "young Mandela", you might just see another "freedom front" leader, not the first, certainly not the last, and probably not much of an example to follow. But if you focus on the Mandela that ended Apartheid and de-fused much of the racial tensions through conciliation, mutual understanding, and forgiveness, then you can draw a lot of inspiration and it can certainly serve as an example to follow. The former is uninteresting, the latter is useful.

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

The question becomes is ME ths same as Anglo-Saxon?

No, ME comes much after Anglo-Saxon. Anglo-saxon is an antiquated term that refers to the Germanic settlers who came to the British Isles in the first millenium, before the Norman (French) invasion. Words of "Anglo-saxon" root are usually referred to with the more precise and modern term "Old German" in most dictionaries. And Middle English is essentially the language spoken in Britain after the significant mixing of French from the Norman invaders / occupiers (from 1066 and on).

I don't like the term Anglo-saxon because it attempts to re-write history to make it sound as though it was a mix of "Anglo" (i.e., the "English people") and "Saxons" (i.e., a small ground of immigrants from modern-day Netherlands / north-west Germany). It's a classic case of Anglo-centric re-writing of history. It attempts to deny the fact that the British Isles were essentially a part of the Viking empire for several hundred years (until the Norman invasion), and that even before the Vikings era, much of the population came from Scandinavian and Germanic areas. British historians have a long history of re-writing history to reflect the nationalistic view that the "English people" were always there and mostly ruled their own land (only admitting to short-lived invasions). The reality is quite different, but few history books will tell you that, mostly because they haven't been updated in a while.

English is a Germanic language with very strong French influence. About 70% of …

Reverend Jim commented: Interesting +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Each of us knows something but all of us know everything, and hopefully one day, we'll learn to listen to each other. - Jim & me

cproger commented: haha +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yeah, it's quite sad. Although, it was expected for some time.

@Warrens80: Bringing down the apartheid is no mean feat. And be prepared for a flurry of down-votes.

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

The arrogance of the 'literate' class was that Latin was the ultimate language thus gave us the 'split infinitive' rule and they even took a fine Anglo-Saxon word 'det' and latinized it as 'debt' (a silent 'B' even for craps sake).

Well, that's a bait I'm willing to take. As a native French speaker, I find it very hard to believe that "debt" comes from an Anglo-Saxon root. And obviously, it isn't. It's part of the "debit" latin family of words. And, when it came into English from French, it was just "dette" like it is in French. I guess some British twit decided to add a "b" in there. By the way, the Anglo-Saxon counter-part for "debt" is "guilt", as it is used in most other Germanic / Scandinavian languages today.

You can't taunt me with this stuff, as a French-Swedish native speaker, I'm unbeatable on Anglo-Saxon vs. Latin roots in English.

as you were discussing 'split infinitives' previously, I thought I'd use 'split infinities', to see if you'd rise to the bait and correct me.

When was I discussing "split infinitives"? I just learned about them in this thread, I've never heard that term before. I guess my English teachers managed to completely omit the splitting of infinitives.

but there are fewer numbers in 1 to ∞ than there are between 0 and 1.

The only thing that stands between 0 and 1 is not. ;)

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

I was ribbing Mike while baiting him with my own malaprop. He didn't see it or decided not to bite :

I didn't understand the thing about "splitting infinities". I still don't get it. Is that an expression or something? Or is it some clever joke that I'm too stupid to understand?

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

Well, you have a few typos in your code, and then, you forgot the end the lines with a semi-colon ; almost everywhere. With those small corrections, we get:

const double NUM = 10;
double a[NUM];
double b[NUM];
bool c;
for (int d = 0; d < 10; d++)
{
    if (a[d] != b[d])
    {
        c = false;
    }
    else 
    {
        c = true;
    }
}
return 0;

which mainly has one problem: it does not return the true/false that it is supposed to. The thing to realize here is that if you see a single mismatching pair of numbers, there is no point in continuing to look at the other numbers, because you already know that you can't have two identical arrays. And so, you can return false as soon as you see a mismatch, and return true if you made it to the end without an issue:

const double NUM = 10;
double a[NUM];
double b[NUM];
for (int d = 0; d < 10; d++)
{
    if (a[d] != b[d])
    {
        return false;
    }
}
return true;

That takes care of the logic of the loop for the first problem. However, I don't see any function signatures or where the numbers in the arrays are taken from. And without that, it is kind of hard to move forward. Can you please post the complete program, not just short excerpts.

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

If you want to dedicate your website to someone, dedicate it to Mother Teresa, someone who is worthy of it.

That's a pretty bad example. Mother Teresa is far from being praise-worthy.

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

The problems with your code are not about having template members inside a class, but they are about pretty much everything else. I understand you "get several errors", but I can tell you that you are probably getting far too few errors, because there are many errors your compiler cannot diagnose, but I can ;) So, let me play the role of a "smart" compiler:

Line 10: Warning: A single-parameter constructor not marked as 'explicit' is an implicit conversion operator, it could trigger unintended conversions.

Line 10: Warning: Template argument b could be a const type.

Line 10: Warning: If b is a const type, the reference parameter value could be bound to a temporary or rvalue.

Line 12: Warning: Implicit cast to void*. Prefer to use explicit C++ casting operators, in this case, static_cast should be used.

Line 12: Error: If b is a const type, cannot convert b* to void* as it would cast away the cv-qualifiers (const).

Line 12: Error: Should not keep a persistent pointer to a passed-by-reference parameter that might be bound to an rvalue.

Line 13: Error: 'b' is a type identifier, not a value or a variable identifier.

Line 13: Error: No possible conversion from type identifier 'b' to variable 'typ' of type 'T'.

Line 18: Warning: Template argument 'b' could be a 'const' type.

Line 18: Warning: If 'b' is a 'const' type, the reference parameter 'value' could be bound to a temporary or rvalue.

Line 20: Error: …

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

I was just teasing.

diafol commented: I know, so was I - "infinities" - but I guess it didn't work :( +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Marian Webster and the British Oxford Dictionary are the most authoritarian dictionaries in the world.

Lol, I didn't know a dictionary could be "authoritarian". I think you could benefit from consulting them too ;) They are the most authoritative dictionaries.

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

As software engineering is similar in many ways to architecture, there is a principle that they share: "Form follows function". The principle is summarized as the fact that the form that a construction takes depends primarily on the function or purpose intended for it.

The reason I point this out is that you are asking about the form that code should take, without explaining the purpose or function that the code should accomplish. That can't work. You have to explain the function before you can determine what the best form is.

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

I don't agree that "the title says it all". I have no idea what your question is. Programming involves creating and using functions and classes, how could it possibly be not "ok", if you can't create / use functions and classes, you can't do anything. It's like asking "is using a hammer and nails 'ok' for a carpenter?". Please explain what you mean more clearly, and we'll be happy to help.

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

Here is some food for thoughts, imagine you have this scenario:

std::queue<int> line1;
for (int i = 1; i <= 10; i++)
    line1.push(i);

std::vector<std::vector<int>> returns1(2);
std::vector<std::thread> threads1;
for (int i = 0; i < 2; i++)
    threads1.emplace_back(DoTransaction, std::ref(line1), std::ref(returns1[i]), i + 1);

std::queue<int> line2;
for (int i = 1; i <= 10; i++)
    line2.push(i);

std::vector<std::vector<int>> returns2(2);
std::vector<std::thread> threads2;
for (int i = 0; i < 2; i++)
    threads2.emplace_back(DoTransaction, std::ref(line2), std::ref(returns2[i]), i + 1);

Do you see a problem here?

The problem here is that whether the mutex is a global variable or a local static variable, the problem remains the same: both sets of threads will lock the same mutex even though they are using different queues.

The only viable solution is to associate the mutex with the queue, somehow. A cheap and easy solution is just to pass the mutex to the function along with the queue. A somewhat fancier solution would be to implement a thread-safe queue class, which could be as simple as just wrapping a mutex and a queue into a simple class that does what you need to use it for. Another solution might be to use something like this class I wrote a while back.

Another typical solution is just to use a functor class:

struct Transactioner {
  std::queue<int> line;
  std::mutex mtx;

  void serveCustomers(std::vector<int> & customersServed, int wait)
  {
    while (!line.empty())
    {
      mtx.lock();
      int val = line.front(); 
      line.pop();
      mtx.unlock();
      std::cout << val << "\t" << wait << std::endl;
      customersServed.push_back(val); …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The core issue is that the std::thread cannot guess whether you want to pass things by reference or by value, and it would not be safe or possible to assume that you want to pass things by reference, it must assume that all parameters are passed by value. The std::ref() and std::cref() functions allow you to wrap a reference into a small object that can be passed around by value, until there is a forced conversion to a reference (which happens when the actual function is called). This is the reason why you have to use these wrappers.

Internally, the std::thread class probably uses std::function<void()> class template to store the function pointer and its forwarded parameters. The rules are the same for constructing a std::function<void()> object.

Since each thread needs to share the queue I am passing it by reference.

Remember to also use a std::mutex to protect the accesses to the shared data. It implements a mutually exclusive lock such that multiple threads can access shared data without mutual conflicts. See docs on std::mutex.

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

So, it's pretty much used for effect by many.

Yeah, that's true. That's part of why I like to use it. Being a native French speaker, my English tends to be slanted towards more "fancy" words that come from French and come more naturally to me. Sometimes, I come across as snob or elitist or whatever (even had people say that to me, on more than a few occasions), like native French speakers often do. So, using terms like "ain't" balances things out a bit.

Just goes to prove how the English language is changing over time -- from my generation to yours today

Yeah, I think that on average, it takes about 300 years for the language to become so different that a normal person (without special linguistics training) can no longer understand the words of his ancestors. For example, Shakespeare in its original version is virtually unintelligible for native English speakers today (they can only understand it with some help and careful study of the text, but it's not like they can read it off and understand it all right away). Some languages have changed less than others (e.g., Icelandic), but most languages change significantly over time, and older people (70s/80s) are often linguistically very far already from teenagers or young adults (among other differences, obviously). That's why you find grumpy old men sounding alarms about the youth "losing their language" in all generations in all countries since the invention of the printing press …

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

It seems that what you need is just a utility like diff. You can easily reproduce it. This is a classic utility used extensively for the purpose of figuring out what changed (especially in source code) between different versions (i.e., make "patches").

The algorithm is quite simple actually, it is just basic string comparisons. You concurrently traverse the two strings and find matching sections and differing sections of it. There are a few interesting challenges such as doing concurrent look-aheads and things like that. You also might want to do things like ignoring comments and white spaces, but that's easy too.

Is there anything you are having trouble with in particular?

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

When I was in school you would have gotten your knuckles smacked for saying "ain't" because "there's no such word".

The contraction "ain't" is a perfectly acceptable form, even though it's very old and classic vernacular (from the 1600s). It's considered as a familiar form, and improper in formal speech (although that is currently under dispute, especially since it is considered acceptable in formal speech in Southern American English dialects, and since some contractions like "I'm" or "it's" are often accepted in semi-formal speech). But this forum is not a formal setting, the last time I checked, and so, it's perfectly acceptable to use it here.

If that contraction was good enough for Charles Dickens and for Mark Twain, it's good enough for me. And I ain't joking ;)

And by the way, contractions like "I'm", "it's" or "I'll" are both more modern and less formal than "ain't". If you can use the ones, you can certainly use the other. I personally like this form, and I use it often, even in semi-formal / formal speech (not formal writing). And if some people see it as "lower-class" and have a problem with its use because of that, then it's their problem for making such a discrimination.

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

It would appear that you and I have similar sensibilities about grammar. We can't expect others to have the same erudition as you and I. If they make mistakes, let them, they're only demonstrating their ineptitude to you and me.

And I ain't an expert in grammar either, although I fancy myself a connaisseur.

ddanbe commented: Nice example of the use of I and me! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As Moschops said, and also there are other extensions that are typical for header files, especially .hpp (the .h is conventionally reserved for C headers). For the rest, header files are just plain text files, like all other types of C++ source files too (cpp files are also just text files). This is true of nearly all source files in all programming languages in general.

If you have trouble with understanding the C++ compilation process, I suggest you read my comprehensive tutorial on that subject.

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

Your functions modify the elements of the array (i.e., swaps them during the sorting). There is no way that you can declare that as const, because that implies a promise never to modify the contents, but your functions require that you do so.

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

This thing could be done with any language, i.e., it is possible to do it in any language. However, certain languages are not really appropriate for this problem. This is a fairly low-level, heavy-lifting application, meaning that high-level, light-work languages are not going to be very appropriate. On that criteria, you can rule out VB.NET and C# right off the bat, because these languages are geared towards the rapid development of user-facing applications, not for heavy-lifting. PHP might be useful for its "network oriented" qualities, maybe as a front-end to your application. But for the most part, you'll have to write it in a heavy-lifting language like C or C++. This is really the kind of application that C++ is geared towards.

You'll have to define more precisely what your task is. You said that what I described was exactly what you meant, but I described things if very vague and general terms, not really something that can be "exact". You need to provide a more specific definition of your problem.

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

I think the OP is talking about plagarism detection software. This is software that can take a given document (text, code, video, etc.) and any other meta-data (title, assignment problem statement, etc.), and then scan the world (i.e., the internet) for any document that is suspiciously similar to it. This is, for example, very common in scientific publication systems, i.e., if you submit a scientific article or dissertation, it will automatically compared against a database of existing articles and dissertations to determine if it is likely to be plagarism or re-publishing the same work, in integral form or re-hashed. For school assignments, especially in computer science, this is also very common to verify that students did not cheat by grabbing code off the web. Youtube also has similar scanning algorithms to automatically detect copyrighted material (video or music) in uploaded videos.

Needless to say, this kind of software is quite complicated in order to avoid taking forever to do its work. It has to employ all sorts of strategies to cut down on the amount of work it has to do, such as compressing data with checksums, doing associative searches, lots of fancy data mining indexing techniques, etc..

But for a simple example, like mining the internet for any code that might be too similar to code submitted as an assignment, then the solution could be rather straight forward. Just pick out keywords from the problem statement, try out many permutations, and for each, you do a google search, pick …

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

The problem is that your reverse function takes its parameters by value, causing a (shallow) copy of the stacks:

void Stack::Reverc(Stack s,Stack d,Stack c)

This is wrong, for a few reasons. First of all, the stack that you seem to be reversing within that function is the s stack, but you really should be reversing the this stack, and this is the way that you call it in the main() function (i.e. you call reverse on a stack object and then print the result). In other words, with that correction, you get this:

void Stack::Reverc(Stack d, Stack c)
{
    int x;  
    while(!this->IsEmpty())
    {
        x = this->Pop();
        d.push(x);
    }
    while(!d.IsEmpty())
    {
        x=d.Pop();
        c.push(x);
    }
    while(!c.IsEmpty())
    {
        x = c.Pop();
        this->push(x);
    }
}

At this point, the result should be "correct", but there are still a couple of issues with the code. One issue, which is true in general, is that if you have variables like c and d that are only needed within the reversing function, then you should not pass them as parameters to the function, but instead, create them locally within the function:

void Stack::Reverc()
{
    Stack d, c;
    while(!this->IsEmpty())
        d.push( this->Pop() );
    while(!d.IsEmpty())
        c.push( d.Pop() );
    while(!c.IsEmpty())
        this->push( c.Pop() );
}

Another issue is that your code is leaking memory all over the place. The general rule in C++ is that every new allocation of memory must have a corresponding delete. You did this correctly in the push / pop functions by …

ddanbe commented: Very thorough! +15
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Can you find a safe way to execute an external program?

What about checking a checksum on the executable before executing it? Something like this:

int secure_system_call(char* app_name, char* app_md5, char* app_args) {
  char* test_md5 = compute_md5(app_name);
  int cmp_result = strcmp(test_md5, app_md5);
  free(test_md5);

  if( cmp_result == 0 ) {
    char* full_name = malloc( strlen(app_name) + strlen(app_args) + 1);
    strcpy(full_name, app_name);
    strcat(full_name, app_args);
    system(full_name);
    free(full_name);
    return 0;
  } else {
    return ERROR_MD5_CHECKSUM_MISMATCH;
  };
};

where the compute_md5 would be some function that computes the MD5 checksum for the given file. And, of course, this assumes that you have some mechanism to securely acquire the expected checksum value for the application, which can be compromised too and is also a portability nightmare (unless you package the executable along with your own).

I'm sure there are also other ways to "verify" the authenticity of the executable. Doesn't Windows have some sort of way to do this? I'm pretty sure that signed packages in Linux environments provide this through MD5 or SHA-1 checksums.

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

The saying I came up with about pointers is this:
"Pointers: Beginners hate them; experts hide them."

The thing that makes pointers "hard" for some is that they are too simple, ironically. A pointer is nothing more than a number (integer) that uniquely identifies a location in memory (an address). That's all they are, nothing more. It's what they are not that is complicated for some to deal with, for example:

  • Pointers do not own the memory at the address, i.e., having a pointer to a location does not guarantee that that memory will remain valid.
  • Pointers do not always have a valid address value, i.e., they can point anywhere, including arbitrary or invalid addresses.
  • Pointers do not copy the pointed-to memory when they are themselves copied.
  • Pointers do not know what they are pointing to (nowhere, start / middle / end of array, stack / heap memory, etc.), and there is generally no way to find out.
  • Pointers are not managed by a garbage collector.

Beginners, especially those who come from a "higher-level" language where pointers are completely hidden, make mistakes, involving pointers and memory management, precisely because they assume one or many of the things listed above, or at least, they code as if to assume them, or, they are just really careless with pointers out of a habit they have developed in their "native" language. That's why beginners hate pointers.

Experts (that is to say, people with more experience in C++) deal with pointers by …

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

Yo mama is so stupid that the highest score she ever got on an exam was 65, and that was for her IQ test.

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

First you get a self proclaimed expert who says it is absolutely wrong to ask for other people to write code for you

It is absolutely wrong to ask for other people to write code for you. That is stated in the Rules of Daniweb:

"Do provide evidence of having done some work yourself if posting questions from school or work assignments"

We get a lot of people who simply post their homework question and demand to have full working code for it. We generally tell them that nobody will do their homework for them, because it is (1) against the rules, (2) probably against the school's ethics policies, and (3) not helpful to them, as they should do their homeworks by themselves if they want to learn.

Then you find this self proclaimed expert begging for other people to give them code here--> http://www.daniweb.com/software-development/cpp/threads/144681/way-to-do-this

The two threads you are referring to are 5 years apart. I don't know about you, but 5 years is plenty enough of time to go from needing help to being able to help others. And I'm having trouble finding where iamthwee self-proclaims to be an expert.

It's hard to take you seriously. This sounds a bit too much like you're trying to smear iamthwee because he ruffled a few of your feathers.

It's no secret that iamthwee can be a bit obtuse at times, even as far as getting dangerously near a "keep it pleasant" infraction. …

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

Until we have a basepoint for discussing the ramifications intelligently

We have Robocop! These were documentaries, right?

I don't see much wrong with robotic prostetics, and they are certainly coming soon. How much is too much? I don't know. And also, it is important to understand that robotics is not like in the movies, i.e., robots are not more "powerful" than humans, a typical humanoid robot is about an order of magnitude weaker than a human. Electric motors and power technology is still far from being a rival to the strength, power and agility of a human body. Movies have carried this myth that a robot like those in "I, Robot" can hit a guy and throw him 20ft in the air. In reality, current robots of that size can barely lift 10kg, and if they were to hit you with all their force, you would get, at worse, a scratch from its rough metalic edges, but the hit itself would feel that it's coming from a 5 year old kid.

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

I'm not sure that I see the Matrix-style plug-and-play memory system as being that great. I don't think that human memory is really infinite. It compresses and loses over time.

What is much more appealing to me, with the same kind of tech described in that video, is the prospect of being able to connect to a kind of external hard-drive with recorded "memories" of certain things. For example, I work in a very multi-disciplinary engineering field, it is very hard to remember in details every equation or every concept, and I find myself looking those up constantly in books or wikis. It's just not possible to keep all that in one brain forever. If I could come in to work, plug my brain into an external storage containing all the knowledge I need in a form that can be accessed as if I remembered everything in detail, then that would be really cool and really efficient. And, I don't think that it would take away my individuality or whatever, it would probably enhance it since I don't have to fill my brain with as much technical knowledge.

But I agree with others here, this should not make school "obsolete" or something like that. It's like open-book exams, which are very common in engineering curriculums, where the focus is not on remembering, but on problem solving skills and understanding, neither of which reside within "memory". If you enhance or even replace memory, it won't change the fact that you still …

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

I don't think anyone will bother with human cloning

I don't know if you could consider this a form of cloning, but I see much more promise in the "cloning" of organs, i.e., artificially growing real organs out of your own (repaired) genes in order to replace your used / damaged organs. I think that could have a significant impact. At first, it would be just to eliminate the need for organ donors, then it would become a common procedure for all sorts of problems, and then it could become a means to extend life significantly.

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

Yeah, I think that the scores on the preview are normalized to 1. The maximum is 20 (with 0 characters), so, you take your number (e.g., 0.45) and multiply by 20 to get the real score (e.g., 9).

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

First, you should use i<101 instead of i<=100. Also, your for-loop could be like this for(int i=0;++i<101;). That's two characters saved. However, D allows for range-based for-loops too, so you could write foreach(i;1..101), that is 4 more characters saved.

Then, you can, in general, replace almost any sequence of if-statements with short-circuit logical OR or AND. For example, this code:

if(i%3==0) w("Fizz");

is equivalent to:

i%3||w("Fizz");

Then, you also forgot that you have the ternary ?: operator in your toolbox, you can use that to save the second comparison:

    i%3||w("Fizz");
    i%5?i%3&&w(i):w("Buzz");
    w("\n");

The final, indented version is this:

import std.stdio;
alias write w;
void main(){
  foreach(i;1..101){
    i%3||w("Fizz");
    i%5?i%3&&w(i):w("Buzz");
    w("\n");
  }
}

That takes the total down to 110 characters. And the score is 0.45.

Just for fun, I came up with this C90 version (C90, because C99 does not allow inferred-type main() function, in other words, a C90 compiler is required to tolerate this program, a C99 compiler will probably throw it out). And, it cannot be C++ because it relies on a tail-recursion on the main() function, which C++ does not allow, but C does.

C90:

#include<stdio.h>
#define w printf
main(i){
  i%3||w("Fizz");
  i%5?i%3&&w("%d",i):w("Buzz");
  w("\n");
  i<100&&main(i+1);
}

That's 110 characters, I don't know how it could possibly be much shorter. That gives me a score of 0.435.

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

If you look at any species from a strictly evolutionary point of view, it makes little sense for an organism to live past the progeny producing/rearing years.

And also considering that the rate of change of organisms under evolutionary pressures is mostly a matter of how quickly the population is renewed (i.e., time between generations). If a species has a reproductive cycle that is too long, it will not be able to keep up with changes of their environment, and will go extinct, along with like 99% of all species who ever lived on Earth.

And because it doesn't make much sense that a species would evolve to live much beyond their "fertile" period, it means that a species that evolved to live very old must either have a very long reproductive cycle or a very low success rate at reproduction.

Unless those species are very resilient and able to cope with different environments, they are the first on the chopping block when any kind of major environmental change occurs. And if they unlucky enough to be on top of the food chain, then they are in big trouble! That's why at every major disruption in the past, all species that weight on average above 50kg get wiped out (i.e., ever wondered why birds are the only dinosaurs that survived?).

Anyways, I digress too. I get there's a point here too: if we come to live for 1000 years or so, then we will essentially stop the evolution …

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

I can do it with a pencil

Well, if the "completely filled square" is already done, then the hollow square could be done with an eraser!

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

There used to be TeX/LaTeX support, which is what you would use to create such equations. Support for it got taken out with the move to the new system. I agreed that it was not the most commonly used feature, but when you need it, it is certainly very nice to have.

It would be nice to have some sort of MathML / Mathjax / LaTeX support for writing equations.

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

The problem is with lines 51-52:

t = clock();
t = clock() - t;

which is the same as t = clock() - clock();, which is the same as t = 0;. So, that's why you get zero all the time.

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

As far as I know, Vim or emacs or nano or any other in-terminal text editor are all implemented just using the curses.h library. There are ports of curses for Windows too, and I believe the Windows ports of Vim/emacs are based on that.

I've got unbuffered input, and I have methods for output to print to anywhere in the console.

That seems to describe what conio does. Conio is the DOS counter-part to curses (for Unix/Linux), but (like most DOS/Windows stuff) is much less powerful and has much fewer functions. Curses has a lot more stuff in it, but at the end of the day, this is still generally based on doing character-by-character drawing of the screen, except that curses provides a few nicer things like a blinking cursor and stuff like that.

And if you want to know, you can just check out the source code for one of these editors (they are open-source, after all). You might want to check out a simpler editor, like GNU/nano.

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

That's sort of what boost::any does. Although, in practice, using just void* is going to cause some issues, like not being able to invoke the correct destructor before deallocating the memory. Using void* is the traditional C-style way of doing type-erasure, but in C++, it isn't really practical.

In practice, the basic implementation of a class like boost::any is something like this:

class any {
  private:

    struct base {
      virtual const std::type_info& type() const = 0;
      virtual base* clone() const = 0;
      virtual ~base() { };
    };

    template <typename T>
    struct erased : base {
      const std::type_info& type() const {
        return typeid(T);
      };
      base* clone() const {
        return new erased<T>(*this);
      };

      T value;

      erased(const T& val) : value(val) { };
    };

    base* p_b;

  public:

    any() : p_b(NULL) { };

    template <typename T>
    any(const T& val) : p_b(new erased<T>(val)) { };

    ~any() { 
      delete p_b;
    };

    any(const any& rhs) : p_b(rhs.p_b->clone()) { };

    friend void swap(any& lhs, any& rhs) {
      std::swap(lhs.p_b, rhs.p_b);
    };

    any& operator=(any rhs) {
      swap(*this, rhs);
      return *this;
    };

    template <typename T>
    any& operator=(const T& rhs) {
      swap(*this, any(rhs));
      return *this;
    };

    bool empty() const { return (p_b == NULL); };

    const std::type_info & type() const {
      if(p_b)
        return p_b->type();
      else
        return typeid(void);
    };

    template <typename T>
    friend
    T any_cast(const any& rhs) {
      erased<T>* p_e = dynamic_cast< erased<T>* >(p_b);
      if(p_e)
        return p_e->value;
      else
        throw bad_any_cast();
    };

};

This is the basic type-erasure technique used in C++ almost in any places you would typically use void* in …

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

If you want to use a fixed selection of types, then you should use Boost.Variant (discriminated union type, similar to that old C-style variant type in windows.h).

If you want to use any types, then you should use Boost.Any, which is a kind of ultimate type-erasure device.

And if you want to take any type and turn it into a serial stream (like a string), then you should use a serialization scheme, like Boost.Serialization.

These are, generally, three separate problem, so, you have to figure out which one is really the one you want.

cambalinho commented: thanks +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I suspect this is not a problem related to Visual C++ but about your code. Please provide the code and the error messages that you get.

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

Otherwise, it would be appreciated if you ever clarify what you mean by "Deterministic", maybe I didn't figure you out.

A good place to start is probably the first sentence on the wiki page:

"A deterministic algorithm is an algorithm which, given a particular input, will always produce the same output, with the underlying machine always passing through the same sequence of states."

In other words, a deterministic method just means that given a particular input (or "problem to solve") it will take a specific, finite, and entirely predictable set of steps, and reach the same end result or output.

Under that definition, a quick-sort algorithm that chooses pivots as either the first, last, middle, or median-of-three is a deterministic algorithm. A quick-sort algorithm that chooses pivots using a perfect random-number generator is a non-deterministic algorithm because the same input (the same unsorted array) would not be sorted with the exact same set of steps (i.e., the sequence of pivot points chosen). In the first case, for a particular input array, you can predict the exact number of steps required, and there are specific pathological cases where that number of steps is O(N^2) (i.e., pivots will always be really bad). In the second case, we can evaluate the probability that every chosen pivot is the worst possible choice (i.e., the "most unlucky" run), which is usually very low, meaning that the algorithm nearly always performs pretty well.

Such randomized algorithms that introduce random inputs or random steps are …

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

Please show the DLL's code (or at least, the function declarations).

The compiler isn't throwing the NULL pointer error. It's hitting the 'else' statement in the second 'for loop' and out putting the cout statement.

Yes, that is exactly what I understood.

I've doubled checked the DLL and the functions are exactly the same. It's declared to return void because the function doesn't return any thing.

So, you have checked the list of exported symbols from the DLL. I am not talking about the source code of the DLL or its function declarations, but the actual list of symbols that you could be able to get out of the DLL file itself.

The only difference is the char inString and char outString aren't declared as arrays when declaring the type def but the complier doesn't like me doing this.

There is a big difference between an array of chars and a char. You cannot use one for the other, this will result in a stack corruption or crash if you try to call the function (assuming it is not NULL).

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

"There are only two kinds of languages: the ones people complain about and the ones nobody uses." -- Bjarne Stroustrup