deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Playing with the structure examples in the book reminds me of accessing attributes to a python Class

That's not a bad analogy. A structure in C++ is just a class with different default access (public instead of private). A union is different in that all members of a union share the same block of memory rather than each member having its own block of memory.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Well, yes. I used a SQL variable since it's a better idea to use parameters to your query rather than glue everything together directly as in your first example. But you could also replace @schoolYear with your string pasting:

"select count(*) from tblSchoolYear " & _
"where schoolYear = 'SY " & Trim(txtAddSchoolFrom.Text) & "-" & Trim(txtAddSchoolTo.Text)
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

May be any platform, any compiler, I just want to do the complete procedure myself.

The complete procedure really does vary between compilers and operating systems and the documentation for your compiler will give you specific instructions.

For a static library it's super easy. Just create a standalone project with the functions and types you want, compile, and add the resulting object files to a static library file (typically .a or .lib). From there you link to the library file as normal.

Shared libraries may be a smidge harder depending on your OS. DLLs in Windows require some coding effort in the library itself, for example.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For this I'd select the count of matching records:

select count(*) from tblSchoolYear where schoolYear = @schoolYear

If it's greater than 1, you have duplicates and can show a message box. However, that particular query strikes me as producing false positives unless the schoolYear column is largely unique. You'd likely need to add another condition to tie it to a specific student.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What about this part? How do you handle this?

All of them are under the programmer's complete control. I handle it by not writing stupid code. ;)

No-throw guarantee: this function never throws exceptions.

All functions in C have a no-throw guarantee. Why? Because C doesn't support exceptions in the first place. ;)

If str does not point to a valid C-string

Yup. The same goes for strlen, or strcpy, or anything that expects a valid C-string by definition. The strings contained by argv are guaranteed to be either a valid C-string or NULL. For other strings, a C-string is defined as zero or more characters followed by '\0'. In this case it's a matter of defensive coding to ensure that you don't produce an invalid string.

And of course, NULL is a simple check if there's any possibility of receiving it.

or if endptr does not point to a valid pointer object, it causes undefined behavior.

Noting that NULL is a valid pointer object, this too is a matter of defensive coding. Make sure your pointers point to an actual object or set them to NULL.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

atoi invokes undefined behavior if the converted integer cannot be represented by the int type. There's no workaround other than explicitly validating the string before calling atoi, and since strtol does this already (as well as not invoking undefined behavior in the same case atoi does), there's no good reason to use atoi.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Ah pronuciation. T'was the bane of my existence (not really, just mildly annoying) with a previous account.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Command line arguments are always strings. What those strings represent depends on your code and how you use them.

But yes, if an argument represents an integer and you want to store it in an integer type, you need to convert the string with something like strtol (atoi is not recommended...ever).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Am I using the +1 wrong?

There's not really a way to use it wrong, barring full out abuse like automatically downvoting every post from a member regardless of post content.

Typically I use the voting system as a type of kudos. If I think a post is well written and insightful, upvote. If I think a post is rude and unproductive, downvote. If the post is meh or otherwise average, no vote. Exceptionally good or bad posts get a comment and corresponding rep.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What arguments are you planning on supporting? Are they the strings to convert or switches that alter how the conversion happens? The first step is to solidify your understanding of how the program should work at a higher level, then you can dig down and implement the pieces.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Assuming the size of the register is 8 bits and the leftmost bit is reserved for sign shouldn't the size be -127 to +127.

It is. Well, that's the required minimum size defined in the C standard. However, the range can be extended by any implementation. Particularly, the extra bit of range on the negative side is due to how two's complement works with signed values. Different sign representations have different ranges, but two's complement is the most common, and they all meet the minimum requirement.

Your best bet for portable code is never to assume that your range exceeds [-127,127] for any 8 bit quantity.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But try again after including the library function #include<conio.h> as well.

Not only will this not solve the problem, it also destroys code portability by requiring the compiler to support a non-standard library.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This is an extension method I use for that purpose:

/// <summary>
/// Separates a list of items into sub-lists of chunkSize chunks.
/// </summary>
/// <param name="items">The original list of items.</param>
/// <param name="chunkSize">The desired size of each sub-list.</param>
/// <returns>A list of sub-lists of up to size chunkSize.</returns>
public static List<List<T>> Chunk<T>(this List<T> items, int chunkSize)
{
    if (!items.Any())
    {
        return new List<List<T>>();
    }

    var result = new List<List<T>>();
    var currentList = new List<T>();
    int i = 0;

    result.Add(currentList);

    foreach (T item in items)
    {
        if (i >= chunkSize)
        {
            currentList = new List<T>();
            result.Add(currentList);
            i = 0;
        }

        currentList.Add(item);
        i += 1;
    }

    return result;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

True, but an IT consultant specialising in networking would, you might imagine, know the basics about networking...

It depends somewhat. Sure, if you've taken classes on networking or electical engineering then cabling does get some treatment. If you've been trained on the job but never needed or been asked to snip cables, the color codes are unlikely to come up.

Even when consulting on networks, my go-to troubleshooting technique when it comes to cables is "try another cable", rather than "let me make sure your color codes are correct". ;) And for new networks, the detailed cabling aspects are typically done by the cabling agency who drops them rather than the consultant who helps design and/or optimize the network.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Now before you all go with strstr

I'm not sure I'd recommend strstr for this anyway. ;)

i dont want to use <string>

You mean <string.h>? That's where strstr is declared. <string> defines the std::string class.

Any suggestion for solution of this issue is a big Thank You.

Keep it simple. Search through the source for an instance of the substring, copy all characters up to that point to a new std::string object, the replacement string, then all characters after the substring. Shooting from the hip (please excuse errors):

string replace_string(const char *source, const char *match, const char *replace)
{
    const char *start = source;
    const char *end;
    string result;

    // Find the start of the match string
    while (*start != '\0')
    {
        if (*start == *match)
        {
            const char *p = start;
            const char *q = match;

            // Check for the rest of the match string
            while (*q != '\0' && *p == *q)
            {
                ++p;
                ++q;
            }

            if (*q == '\0')
            {
                // Perfect match, done with this search
                end = p;
                break;
            }
        }

        ++start;
    }

    // Copy up to the matched string
    result.append(source, start - source);

    // Copy the replacement string
    result += replace;

    // Copy after the matched string
    result += end;

    return result;
}

The only hairy part is manually searching for the substring, but it's not exceptionally tricky for an exact match. Of course, you'd also need to add error handling and edge cases, but …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm not entirely sure I understand the problem. A bool property will display appropriately as a checkbox by default in a DataGridView. So you'd add such a property:

bool Availability { get; set; }

Then convert the result of the combobox as necessary (varies depending on how you've got the combobox set up):

// If the items are the strings "Yes" and "No"
Newvideo.Availability = comboBox2.SelectedItem.ToString() == "Yes";
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@deceptikon, is that still the case on most modern implementations?

Yes. In the past the biggest problem with modulo (where small ranges were concerned) was an artifact of low order bits not being as "random", and that's largely been fixed in modern implementations. But the distribution problem remains since it's more of a fundamental mathematical thing; pigeonholing a larger range into a smaller range can be tricky.

A better approach in terms of distribution (assuming the generator gives you a uniform distribution within its natural range) would be something more like this:

int r;

do
    r = rand();
while (!inrange(r, min, max));

With this you're working within the uniform distribution rather than fighting against it.

High modulo divisor with low number of samples is less uniform distribution; but the lower the modulo divisor and higher the number of samples the more uniform the distribution becomes.

True. But typically when you care about the distribution, any bias tends to be too much. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In the program below what is the difference between rand and srand?

rand generates a pseudorandom number. srand seeds the generator that rand uses. The seed essentially determines what the first random number will be and affects subsequent numbers in the sequence. If you don't call srand, the seed is always 1, so the sequence you get will be predictable.

Yet this code returns a number from 1-6, how is that?

Take any number between 0 and 32767, then apply modulo 6. This will force the number into the range of [0,5]. 1 is added to shift the range to [1,6]. You can play with the idea using a calculator, it's simple math. :)

Note that this is a naive technique for fitting the result of a random number generator into the range you want. It's weak because it severely damages the distribution of random numbers, but that's sometimes acceptable.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It looks like the compiler is interpreting Image as System.Windows.Controls.Image rather than System.Drawing.Image. The error is correct in that the target class doesn't have a FromFile method.

I'm a bit surprised that you're not getting an ambiguity error instead, but a quick fix would be to fully qualify the class:

var image1 = System.Drawing.Image.FromFile(filename1);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Wires with the same base color are paired, so it makes sense to distinguish them somehow as pairs. They can't both be a solid color or you'd confuse them on each end of the cable. Thus, the white stripe.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The article I linked to covers that, and followup articles cover balancing techniques. The problem with Knuth is that it uses a home grown assembly language for code examples. I love the books, don't get me wrong, but translating the code into C++ is more of an intermediate exercise that distracts from the concepts of the data structure.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There are a number of ways to go about it, but I'd suggest starting simple. This is an article that cuts right to the chase and doesn't include any fluff that might confuse the core concepts.

Once you have the basics down you can introduce classes to wrap it all up into a nice package.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Vague much?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your methods must be wrapped in a class:

public class Connection
{
    public static string GetConnString()
    {
        return WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    }

    public static void InsertUser(string name, string pass, string email)
    {
        string ConnString = Utils.GetConnString();
        string SqlString = "INSERT INTO university (username, password, strEmail) VALUES (@username,@password, @strEmail)";

        using (OleDbConnection conn = new OleDbConnection(ConnString))
        {
            using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("username", name);
                cmd.Parameters.AddWithValue("password", pass);
                cmd.Parameters.AddWithValue("strEmail", email);
                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
}

However, since your code refers to text boxes, I'm assuming the class already exists as a Form, in which case you only need to add methods to that class (probably called Form1).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Not sure about the namespace.

You don't need a namespace, but you must have a class. C# has no concept of top level methods or fields, they're all members of a class.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What do you mean by "generate"? Are you trying to write an arbitrary length number library or something?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but neither seem to be working for me.

On a side note, String and string are equivalent. string is a keyword alias for System.String.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The answer to that question is: "It's usually advertised with the hdd itself.

Advertised poorly. Manufacturers tend to advertise in increments of 1000 rather than 1024, so a 1GB drive is smaller than a binary minded person would expect. Throw in necessary formatting and system reserved space, and the advertised size is woefully misleading. As drives grow, so does the amount of apparent loss.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I have my own reasons for using the latest revision though. I'm usually curious to see what the differences are, and I like the feeling of "being up to date" with the development of companies.

True. Despite past experiences, I was an early adopter of Windows 8, and it turned out quite well.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Never assign raw data directly to an uninitialised pointer. If done so, where would the pointer point to? Where will the raw data be stored? Maybe it will compile, maybe it won't. Maybe it could lead to disastrous effects. You have to make sure a pointer points to something (safe) before using it. So: char *st="myname"is plain wrong.

Um...what? char *st="myname" is fine. The pointer is initialized and points to a string literal. The only disastrous thing involved is the read-only status of the string literal, and that's only a problem if subsequent code tries to modify it through the pointer.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why doesn't the user have the option of deleting his own post??

Because there's a strong risk of breaking thread continuity. Users have a window of time after posting in which posts can be edited (and possibly deleted, I honestly can't recall). After that window the post is set in stone and can only be modified by moderators.

because it is full of errors, it is somewhat confusing, and the code I submitted does not run

You can update the thread by replying to it with corrections.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is this possilbe guys?

Yes.

Help here will be highly appreciated

It's difficult to help without knowing what language or GUI library you're using. It's entirely possible that no code is needed; changing to a control that's better suited for numbers than a text box could be the solution. Once again, depending on what you're using to develop this application.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

and to make sure that everything works with the latest revision

Windows ME.
Windows Vista.
The first incarnation of Windows XP.

;)

I personally didn't have any problems with Vista (though I seem to be in the minority), but ME and early XP were a bear. Typically best practice is to wait for the first major service pack before adopting new software, unless the software is minor enough that problems don't hurt too much.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Perhaps part of the lesson to be learned from your assignment is about the case-sensitivity of C#.

I sure hope not, because that'd be a cruel and stupid way of teaching a simple rule of the language.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For what it's worth, I'm sorry for the heartache we caused you even though my opinion on it hasn't changed. IIRC, I was one of the loudest voices in opposition of the idea.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You need an image library.

You don't need one, but it's strongly recommended given that image processing is rather complex. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

rear

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Problem is I've never used a pre-designed CMS system... are they are fairly easy to setup, configure, and use?

A lot easier than writing one, I assure you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

in that instead of an else {} it uses a test for not-null, after it already did a test for null of the interface object

Would you believe that I've seen stuff like this in production code?

YesNo check = CheckThing(thing);

if (check == null)
{
    // Okay, I suppose
}
else if (check.Yes)
{
    // Sure
}
else if (check.No)
{
    // Yup
}
else if (check.Maybe)
{
    // Seriously?
}
else
{
    // WTF!
}

How many conditions can you find for yes or no? ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

With real discussion communities, rewriting posts is completely frowned upon to the point of being insulting. Community members don't appreciate having words put in their mouth or having what they say altered by others.

As evidenced by the backlash when you tried to roll out intellitxt several years ago. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I agree or disagree depending on what agile components you think are effective. ;) Sprints and stories, awesome. Pair programming, hit or miss. TDD, weak at best in my experience. Agile as a whole is good, but there are parts that aren't so good, which is why there are so many flavors of methodology.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

if we don't use return then there is no value returned to the function?

It's not quite that simple. For extra credit, try to explain what's happening here:

#include <stdio.h>

int foo()
{
}

int main(void)
{
    printf("%d\n", foo());
    return 0;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why do we use interface references to call methods of an object?

For the most part it's a poor man's polymorphism. An interface is a contract where the implementing class says "I promise to support at least the definition provided by the interface".

As long as a class implements the interface, that class can be accessed through an object of the interface:

interface IFoo;
class Bar : IFoo;
class Baz : IFoo;

static void Main(string[] args)
{
    IFoo obj1 = new Bar();
    IFoo obj2 = new Baz();
}

Of course, like your example, the above is nigh useless and just a complication over using the class directly. However, imagine instead a factory that gives you a different implementing class depending on its arguments:

static void Main(string[] args)
{
    var provider = GetMailProvider(server, port, user, pass, mailbox);

    ...
}

IMailProvider GetMailProvider(params object[] args)
{
    if (IsPop(args))
    {
        return new PopMailProvider(args);
    }
    else if (IsImap(args))
    {
        return new ImapMailProvider(args);
    }
    else if (IsEws(args))
    {
        return new EwsMailProvider(args);
    }
    else
    {
        throw new UnsupportedMailProvider(args);
    }
}

The calling code doesn't care which class it gets, because all of them support the same interface. provider is used the same way, so all three mail provider types are supported without extra logic in the client code. Further, the underlying classes may not be accessible to you, only the interface. In fact, this is precisely how I implemented my email library with support for multiple providers.

Returning back to the …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The two examples are functionally identical. Which one you'd use depends on which fits better with the rest of the code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Because if the fields are public, users of the class have unrestricted access to them. Exposing fields through properties introduces a controlled interface. Presumably your question is about this:

class Foo
{
    private int _bar;

    public int Bar
    {
        get { return _bar; }
        set { _bar = value; }
    }
}

This is indeed not much better than making _bar public. The only benefit here is that you have the option of controlling access in the future without changing the public interface. For example, let's say that you later decide Bar can only have a range of [1,10):

class Foo
{
    private int _bar;

    public int Bar
    {
        get { return _bar; }
        set
        {
            if (value > 0 && value < 10)
            {
                _bar = value;
            }
        }
    }
}

This cannot be done if _bar was public originally.

General best practice is for private fields to be used for anything that only the class has access to, public fields should not be used without very good reason, and public properties should be used to expose a controlled interface to private fields if needed.

JorgeM commented: easy to understand with a clear example! +12
JOSheaIV commented: Beat me to it +3
nitin1 commented: cool one... +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Most likely the desktop version of Visual Studio 2013 Express is what you want.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Let's first differentiate Unicode and UTF-8. UTF-8 is an encoding technique for Unicode code points. So you can break the problem down by removing the encoding aspect and only thinking about code points.

For simplicity sake, consider the code points which can fit in a single byte. These correspond to ASCII, and the case conversion is identical in concept with ASCII. The only real difference is more complex encoding logic of the value because UTF-8 is a variable width encoding.

Extending that a bit to the non-ASCII code points, a simple arithmetic transform may not work. At that point the upper case function would use a lookup to map the two characters.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm not sure I understand the question. Upper and lower case glyphs have a unique encoding, they're independent of each other in the same way digits and letters are.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Bounded array means static it it?

"Bounded" typically means one of two things:

  1. The size of a container is fixed and cannot change.
  2. Accessing indices outside of the container's range will produce an exception.

Can you clarify what you mean by "bounded"? I'm also not familiar with that as any kind of standard terminology. IIRC, the C++ standard only mentions "bounded" in reference to numeric ranges and syntax grammar; nothing about arrays.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your company's IT department will have either an installation disk or a repair disk for your computer. The former requires a product key that the same department will have, though they'll probably ask to install it themselves rather than give it out to you. Since it's your company's property, I would strongly recommend talking to them about your need.

On a side note, asking for product keys to licensed software is illegal and against Daniweb's rules. We'll help direct you to getting a legit copy of Windows installed on your laptop, but we won't help you with anything that smells of piracy.