deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Have to say, the approach you took, and your design is somewhat different then what I would have thought

The key design aspect is simplicity of usage and implementation, so the class is really little more than a wrapper around how I usually do database access manually. I'd love to see how you'd do it when you feel comfortable sharing, as this is probably something everyone would do differently. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You could count the number of zeroes inside a number N with the following algorithm

And if the number begins with zeroes? What if the number exceeds the range of your numeric type? The best approach to handle input as it's typed is to work with it as a string rather than a numeric data type, like in Stefano's hint.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm sure I've mentioned this type of wrapper class for accessing databases in a provider-agnostic manner before, but never posted a functional implementation. So here it is. Questions, comments, and suggestions are welcome as always. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Ditto cgeier. I'm not a fan of directly managing data sources in Visual Studio; it just feels too inflexible compared to doing it manually with ADO.NET.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Um...what? Convert how? And does the picture of the dress need to be processed in some way? Your question is exceptionally vague.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How bout putting the database file into the same directory as your .exe file?

That's risky. If the application isn't run with administrative rights, extraneous files may not be accessible if they're in the application folder. A better approach would be to use something like Environment.SpecialFolder.CommonApplicationData and storing the paths/connection strings in a configuration file.

Typically anything that depends on the environment should be configurable anyway. Hard coded paths are a big no-no unless they're guaranteed to be legit and accessible across the board, which is difficult to do.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Well, the most widely supported method would be the ctime library:

#include <ctime>
#include <iostream>
#include <utility>
#include <string>

using namespace std;

pair<string, int> weekday(int month, int day, int year)
{
    tm date = {0};

    // Set the date properties
    date.tm_mday = day;
    date.tm_mon = month - 1;
    date.tm_year = year - 1900;

    // Let the library correct any discrepancies in the parameters
    time_t normalized_date = mktime(&date);
    char buf[1024];

    // Extract the user-friendly weekday name
    strftime(buf, sizeof buf, "%A", localtime(&normalized_date));

    return make_pair(string(buf), date.tm_wday);
}

int main() 
{
    pair<string, int> day = weekday(1, 1, 2014);

    cout << day.first << "(" << day.second << ")" << '\n';
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Define "easier" for your needs. With a vector, I'd probably do the same thing you've done, but there are serialization libraries (Boost comes to mind), but they can be non-trivial to use.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problem seems to be in your ToString override in that you want a format that's difficult to attain using enumerations. It can be done, of course. I'd probably approach it something like this:

namespace CS_TexasHoldem
{
    public enum CardSuit : int
    {
        CLUBS = 'c',
        DIAMONDS = 'd',
        HEARTS = 'h',
        SPADES = 's'
    }

    public enum CardValue : int
    {
        TWO = 2,
        THREE,
        FOUR,
        FIVE,
        SIX,
        SEVEN,
        EIGHT,
        NINE,
        TEN,
        JACK = 'J',
        QUEEN = 'Q',
        KING = 'K',
        ACE = 'A'
    }

    class Card
    {
        private static Dictionary<CardSuit, string> _cardSuits;
        private static Dictionary<CardValue, string> _cardValues;

        static Card()
        {
            _cardSuits = new Dictionary<CardSuit, string>();
            _cardValues = new Dictionary<CardValue, string>();

            foreach (var suit in (CardSuit[])Enum.GetValues(typeof(CardSuit)))
            {
                _cardSuits.Add(suit, ((char)suit).ToString());
            }

            foreach (var value in (CardValue[])Enum.GetValues(typeof(CardValue)))
            {
                if ((int)value <= 10)
                {
                    _cardValues.Add(value, ((int)value).ToString());
                }
                else
                {
                    _cardValues.Add(value, ((char)value).ToString());
                }
            }
        }

        public CardSuit Suit { get; private set; }
        public CardValue Value { get; private set; }

        public Card(CardSuit suit, CardValue value)
        {
            Suit = suit;
            Value = value;
        }

        public override String ToString()
        {
            return _cardSuits[Suit] + _cardValues[Value];
        }
    }
}

Note that the public interface only supports the enumerations. This saves you trouble checking against invalid values. The class then manages conversion of those enums into a friendly string format.

However, a better approach would be to avoid that string conversion entirely and let the calling application decide how it wants to handle display of cards. Right now you're doing something low level that's probably …

ddanbe commented: Nice! +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Well, a database is the way to go, but that's really a pointless statement. What you really want is a CMS. They'll use a database on the back end, but support record metadata for indexing and filtering such that you store only a single instance of the item yet can access it through a multitude of different paths.

I'm genuinely not familiar with anything but enterprise level content management systems, but I could easily see myself recommending FileNet, Sharepoint, OnBase, Laserfiche, or ApplicationXtender if you contacted my company asking the same question. OnBase in particular, since that's our forte, but it's very pricey.

My suggestion is to research content management systems in your price range and see if they offer the features you want:

  • Support for media content files.
  • Canonical storage of files (only one instance) and multiple metadata records that point to the instance.
  • Foldering of metadata records.
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It sounds like your professor wants you to play with different string representations. Specifically, how to determine length at any given time as that's the usual difference between string types. There are three common ones:

  • Terminated strings: An extra slot is allocated for storage of a terminating character (usually 0). Any manipulation of the string stops at this character, and modifications ensure that the terminating character is present to avoid corrupting memory. This is how C-style strings work, and the drawback is determining the length is an O(n) process because you need to traverse the string to find the terminating character.

  • Bookkeeping strings: Extra memory is allocated for storage of the string's current length. Usually it's a byte or two at the beginning. Storage of actual character data starts immediately after this bookkeeping block. Determining the length is quick and easy, but one drawback is you limit the maximum size of the string, or add unnecessary memory if the string is always small. Accessing the bookkeeping block can also be unintuitive.

  • Aggregate types: The string is just a block of memory and the size is stored in a separate variable. This is the most intuitive design, but it's risky in that the size variable must be updated religiously and it's easy to forget. Most string classes in OO languages define string types using this design.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It seems like we largely agree. :)

However, C++ is a super set of C, so if you know C++ you know C.

C++ was originally a superset of C. Not so much nowadays, and especially when you pull in latest standards (C deviated from C++ with C99). I'm a strong proponent of the idea "if you know C++, you know C" being bullshit. Sure, you can write functional C, but good C takes a different mindset than good C++. Thus it's better to think of them as completely different languages.

Also, you can compile "almost" any C program in a C++ compiler.

After a fashion. ;) I'd wager that most C programs will fail to compile without minor changes. The first thing that comes to mind is adding a cast to malloc calls, and it would be hard to find any serious C program that doesn't use malloc. Note of course, that casting malloc in C is a poor practice unless the code is intended to be cross-compilable with C++.

C++ is better than C because it has all that C has plus more.

More and better are not synonymous. Barring the train wreck of standardization beyond C95, one of my biggest likes about C is that it's so small yet so powerful.

Probably I made this mistake because this is the way I learned C++. On the contrary, I believe that is better to learn C++ directly instead of learning C …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

my first question is whether a deck of cards should have a base class of card

It doesn't make sense to me, personally. A deck of cards is not a card, it's a collection of cards, so composition is the better choice over inheritance:

public class Deck
{
    public List<Card> Cards { get; set; }

    ...
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This tutorial may help.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's valid syntax, but guaranteed to be confusing and very likely to become incorrect as more members are added to the class. The private qualifier only explicitly applies to suit, and the public qualifier will only apply to your constructor. value will have default visibility, which in this case is private.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Off the top of my head, the C standards don't disallow that code in any way. Further, my tests with gcc don't mesh with your results. Please post a complete compilable example and the full compiler output including your instantiation of gcc.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Learning C is the long way to C++98 to C++03 to C++11 and do not have any benefit.

You realize that C is more than just an intermediate step to C++, right?

So jump directly to the best.

Best is debatable. Since the OP didn't specify what context the languages would be used, it's incorrect to definitely say that C++ is better.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Click the Chat button on the bottom bar. This will open the chat window and reset your pending chats count. It will also turn off the inline chat popup until you receive another chat in your chat box.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I tried but it dosn't work ...

"Doesn't work" is not a helpful problem report. Please be specific about how it doesn't work.

However, at a glance there are two immediate problems. One is subtle and the other is glaring:

char* s="Ctor of class Brain Called";

While compilers typically allow this, you should use a pointer to const char for string literals:

const char *s = "Ctor of class Brain Called";

myfile << *a;

This is fine if you only want the first character of the string to be written to the file. Otherwise, don't dereference the pointer.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Warning: This code is tested, but not as-is. I combined multiple files to simplify the snippet.

One of my specialties is document imaging, and custom tools to handle it. A common request for both scanner sources and file import is correction of when pages are not properly oriented. To avoid forcing users to correct this in their scaning utility of choice, automatic detection and rotation of these images is a nice feature.

This snippet is a command-oriented solution using the Tesseract OCR engine and a .NET ImageMagick library (both available on NuGet). It might be used like this:

using (var fs = File.Open(file, FileMode.Open))
{
    try
    {           
        using (var ms = new AutoOrient().Run(fs, new AutoOrientOptions()))
        {
            // Close the original file so we can manage it as necessary
            fs.Close();

            // Overwrite the original file
            File.WriteAllBytes(file, ms.ToArray());
        }
    }
    catch (Exception ex)
    {
        Log("Error running command" + ex.ToString());
    }
}

There's nothing unusual going down, but I'm offering this to save others time in developing something similar. The curious may find the simple command-oriented design interesting as well. Questions and comments are welcome. :)

Note that Tesseract OCR requires external training files that can be downloaded from the https://code.google.com/p/tesseract-ocr/downloads/list. The files I'm using are tesseract-ocr-3.02.eng.tar.gz and tesseract-ocr-3.01.osd.tar.gz. The latter is critical for orientation information.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This may help.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Depending on how familiar you are with Java (and programming in general), both should be relatively simple to pick up. All three are in the same family, after all. However, I suspect you'd find C++ more comfortable initially since it directly supports OOP.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Isn't the hash/salt value stored in the database table when the user first registers

Yes. When the user registers, you generate the salted hash and store it in the database. When the user logs in, you do more or less the same thing with entered credentials and compare with the stored hash to authenticate. At no point should a password be directly stored in the database, either plain text or merely encrypted.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Um...what?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The code you've linked to doesn't compile due to undeclared variables. Could you post the updated code which produces a segfault here, please?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hmm, my initial reaction is to suggest fixing the circular reference. You could try using reflection to invoke methods in a compiled assembly from the other project, but that strikes me as more of a Band-Aid than a solution.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How is the second one faulty? The most notable potential problem is you're incrementing num1 rather than count, but whether that's a bug depends on what you expected to happen.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why does this not need to be int main?

Prior to C99, omitting a return type causes the compiler to assume you meant int. This is called "implicit int", and it created enough confusion that C99 removed that "feature".

Why no return 0?

Either the code is correct yet non-portable if the compiler supports falling off main, horribly broken (but not required to report an error) if the compiler doesn't support it, or just fine in C99 and later because this:

int main(void)
{
}

Is equivalent to this:

int main(void)
{
    return 0;
}

Just like in C++.

Don't you need an initial declaration of sub() above main?

Not if the default signature for a function matches your definition, and provided the definition doesn't use variable arguments. I agree with you though, it's not a good practice to exploit this behavior.

How do I check if its c89 or c90?

C89 and C90 are for all practical purposes identical. For your compiler, it depends on your compilation switches which language standard is used. GCC defaults to gnu90, so you can expect C90 with GCC extensions if a switch isn't provided.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That code is weak in that it makes an assumption about the bit representation of characters. In particular ASCII upper and lower case letters differ only in whether the 6th bit is set, so that code ensures that the bit is the same before doing a comparison.

A much better approach would be to do the conversion with toupper or tolower instead as those don't assume ASCII.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

PLEASE PLEASE

Please read our rules concerning homework. If you need help with anything specific, ask a specific question. Nobody here will do the work for you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problem is i don't even know programming.

Yep, that's a problem alright. A big one.

I'd start by searching for tutorials on how to write an operating system; there a surprising number out there on the web. Once you have an idea of what's involved, you can start learning the programming languages and concepts required. But be aware that starting from zero means your project likely won't be finished for quite some time.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Even Daniweb promises to never go through private messages.

Which seems like a mistake on our part. Daniweb's TOS should probably include a qualifier that PMs may be reviewed in extreme cases (such as excessive harrassment) or shared with law enforcement to assist in any investigation.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This sounds like a variation of a repository library I wrote. The ID structure wasn't quite that simplistic, but the concept is similar. Something like this would be a start for you:

private void buttonLoad_Click(object sender, EventArgs args)
{
    var path = GetImagePath(
        Folder, 
        Convert.ToInt32(numericUpDownImage.Value), 
        ".tif");

    if (File.Exists(path))
    {
        // Load the image
    }
    else
    {
        // Handle no image
    }
}

private string GetImagePath(string root, int imageId, string ext)
{
    int folderId = imageId / 1000;
    int imageId = imageId % 1000;

    if (!ext.StartsWith("."))
    {
        ext = "." + ext;
    }

    return Path.Combine(root, folderId.ToString(), imageId + ext);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It sounds like you copied the executable itself rather than creating a shortcut.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how can I use it ??

A "dynamic array" is really nothing more than simulating an array. Once created, you use it very much like a regular array.

how can I allocate and intialize it ???

This will allocate a dynamic array of 10 pointers to int, then initialize the pointers with an increasing value. The values are printed by iterating over the array and dereferencing each pointer. Finally, the dynamic array is freed:

// Allocate
int **a = new int*[10];

// Initialize
for (int i = 0; i < 10; i++)
{
    a[i] = new int(i);
}

// Use like an array
for (int i = 0; i < 10; i++)
{
    cout << *a[i] << '\n';
}

// Release
delete[] a;
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please read our rules concerning homework.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It seems the subtle humor of my response was lost on everyone. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your question is essentially "how do I write a program using functions?", which is extremely vague and basic. Do you know how functions work and the syntax for defining them?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Someone can help you when you ask a specific question. Daniweb isn't a "do my work for me" service.

I do have one question though, given that VB6 is increasingly becoming unsupported on Windows (eg. runtime dependencies are no longer installed by default): Why are you using VB6 instead of VB.NET?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It depends quite a bit on the contents of your file. Let's say that the file looks like this:

resistor
inductor
capacitor
diode
transistor
circuit

Then you would replace your push_back calls with something like this:

ifstream in("words.txt");

if (in)
{
    string line;

    while (getline(in, line))
    {
        words.push_back(line);
    }
}

It would be easier to show you where you're going wrong if your code actually had an attempt to read the file. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You're sorting and printing while building the array, which is not entirely incorrect, but unlikely to display properly. Finish reading the file, then sort and print; you'll get the correct result that way. Here's the corrected code with a few other changes:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static void sort_a(void *array, unsigned n);
static int cmpr(const void *a, const void *b);

int main(void)
{
    static const char filename[] = "input.txt";

    char *line_array[1000];
    char line[1024];
    int i = 0;
    int j = 0;
    FILE *file = fopen(filename, "r");

    if (file != NULL)
    {
        while (fgets(line, sizeof line, file) != NULL)
        {
            // Trim the newline character
            line[strcspn(line, "\n")] = '\0';

            // Stop processing if line_array is full
            if (i < sizeof line_array / sizeof *line_array)
            {
                line_array[i++] = _strdup(line);
            }
            else
            {
                break;
            }
        }

        fclose(file);

        sort_a(line_array, i);

        for (j = 0; j < i; j++)
        {
            printf("%s\n", line_array[j]);
        }

        // Clean up your memory
        for (j = 0; j < i; j++)
        {
            free(line_array[j]);
        }
    }
    else
    {
        perror(filename);
    }

    return 0;
}

int cmpr(const void *a, const void *b)
{
    return (strcmp(*(char **)a, *(char **)b));
}

void sort_a(void *array, unsigned n)
{
    qsort(array, n, sizeof(const char *), cmpr);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is it valid to use an integer variable as a condition?

Yes. This:

if (var)

Is logically synonymous with this:

if (var != 0)

Provided var has an implicit conversion to an integer or boolean type, it's perfectly valid and makes for nice shorthand in some cases. In this case, 0 is false and any non-zero value is true.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The reply editor also has helpful buttons that will do this for you.

  1. Select your text and click either the Code or Inline Code button to apply formatting.

  2. Click the Code button to open an editor popup where you can paste your code. Submitting that will insert into the post a formatted code block with the contents.

  3. click the Inline Code button and a sample formatted section will be inserted into the post.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How can you make sure that the replies and info we receive are correct?

Trust, but verify. If only one source tells you something and others contradict it consistently, that source is likely in the wrong. If multiple sources say the same thing, it's probably correct.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Off the top of my head, I might approach it two ways:

  1. Simply have the application check periodically for new records. This would be the easiest to implement, but it may see derading performance over time.

  2. Use a notification service that pushes new records to client applications so that they can pop up a notification box or something. This would be my preference, probably using a WCF service.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Works fine for me. Compare and contrast:

#include <iostream>

using namespace std;

int main() 
{
    char input[256];

    cout << "Password? ";
    cin.get(input, 256);

    for (int i = 0; input[i] != '\0'; i++)
    {
        if (isupper(input[i]))
        {
            input[i] = tolower(input[i]);
        }
        else if (islower(input[i]))
        {
            input[i] = toupper(input[i]);
        }
    }

    cout << input << '\n';
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I could not agree less, but to each their own.

Fair enough. I'd be a hypocrite if I said that there's no value in learning the dark side, but willingly sharing that knowledge to folks with unknown intentions has been deemed too risky for this community.

Out of curiosity, what is your answer to "this is buffer overflow, and here is how you avoid it"?

It's situational. I'll point out the risk in given code and show measures to avoid it with a safer best practice.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here is the fix:

for (i = len - 1; i > m; i--, m++) {

I'll leave it to you to figure out why that fixes it, but working through the logic with a small line of text on a piece of paper will help greatly. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The logic should be conditional. You're inverting the case based on the original case, not unconditionally changing it:

for (int i = 0; input[i] != '\0'; i++)
{
    if (isupper(input[i]))
    {
        input[i] = tolower(input[i]);
    }
    else if (islower(input[i]))
    {
        input[i] = toupper(input[i]);
    }
}

cout << input << '\n';