nmaillet 97 Posting Whiz in Training

Couple questions: are you using MS SQL Server, or something else? And is the data type variable length (varchar or nvarchar) or fixed length (char or nchar)?

nmaillet 97 Posting Whiz in Training

Have you tried simpler test cases, such as SELECT FirstName, LastName FROM ClientNCar to ensure the connection and column names are all correct? Also, is your database case-sensitive, and if so, are you accouting for that?

Another thing, be careful with that code, I don't think SqlCommand makes any effort to prevent SQL injections in your database. I'm pretty sure SqlCommandBuilder does, so you may want to look into it down the road.

nmaillet 97 Posting Whiz in Training

@nesa24casa He said he can't use classes. Structs are essentially the same thing (minus the allocation on the heap), so I doubt he could use them.

I ran a quick test with:

string[] ret = RazvrstiPoVrsti("c:\\test.txt");
Console.WriteLine(ret.Length);

for (int i = 0; i < ret.Length; i++)
    Console.WriteLine(ret[i]);

Console.ReadKey(true);

and it gave me the following output:

5
Staind ? 'Not Again'
Five Finger Death Punch ? 'Under and Over It'
Theory of a Deadman ? 'Lowlife'
Breaking Benjamin ? 'Blow Me Away'
Anthrax ? 'The Devil You Know'

I don't see where the arrays (imeKomada and stGlasov) are giving incorrect lengths. Could you post the code you are calling this method with, the actual output and the expected output.

nmaillet 97 Posting Whiz in Training

A StackOverflowException is usually caused by recursive function calls. Try taking a look at the method(s) that instantiate a new instance of the Settings class (or post them here). There is probably something that calls the method again, or another method that ends up calling the method.

If your IDE shows gives you a call stack, post that too. I'm pretty sure Visual Studio won't, and since .NET 2.0, you can't catch it.

nmaillet 97 Posting Whiz in Training

Also keep in mind that local variables may not even take up space on the stack. Depending on the architecture, instruction set, compiler, etc., local variables may only exist in registers.

nmaillet 97 Posting Whiz in Training

You could handle the increment of i inside the for-loop like so:

for(int i = 0; i < lotto.Length; )
{
    check = rand.Next(1, 41);
    Console.WriteLine("Random number to be checked is -> "+check);

    if (lotto.Contains(check))
    {
        //You could do another WriteLine() here.
    }
    else
    {
        //Only add check and increment i if it does not contain check.
        lotto[i] = check;
        Console.WriteLine("slot " + i + " contains " + check);
        i++;
    }
}

So you'd only increment i, if the random number is not contained in the list.

nmaillet 97 Posting Whiz in Training

Won't getch() do the trick?

It's not part of the standard library. Microsoft includes getch() it in the conio.h header, but I'm not sure what's used (if anything) with other compilers/operating systems.

nmaillet 97 Posting Whiz in Training

Then post your code, and tell us what is not working right.

nmaillet 97 Posting Whiz in Training

Yeah, but the point is: you should be forced to enter valid data before submitting a form, but not before changing fields. Also, like I mentioned before, this doesn't force users to enter valid data, unless they select the field...

nmaillet 97 Posting Whiz in Training

If you want help here, you're going to have to show some work, then ask questions if you get stuck. Don't expect anyone here to do your homework for you.

nmaillet 97 Posting Whiz in Training

how to convert from UDP to TCP

Just Google some C# TCP socket tutorials and read through the MSDN class reference for the Socket class. There is alot to go over, so I'm not going to post everything here. For starters though, during Socket initialization, you'd change it to this:

Socket peer1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Using a stream (which you have to when using TCP) essentially means you read it like you would for a file (with delay and such). Packets are still being used in the backend, but you can't directly access them.

You would then have to call the Bind() method, to bind the socket to a particular local end point and port number (you can use IPAddress.Any if you want the system to assign it on connection).

Now, you would either call Connect() or Listen(), depending on if you'll be acting as the client or the server. You can still use SendTo() to send data, but its unnecessary, as each TCP socket will only have one remote end point. You'll have to create multiple sockets if you are communicating with more than one remote end point.

how to define maximum bufer on receiver when i received packet for UDP and TCP

I'm not sure what you mean. You can set the ReceiveBufferSize property to specify the internal buffer. If you're talking about the byte array (your buffer), then ReceiveFrom() and Receive() both have overloads to specify the maximum number …

nmaillet 97 Posting Whiz in Training

They won't work due to the == operator. The "strings" are really just character arrays. When you use the == operator, you're comparing the memory addresses, not the characters. Take a look at strcmp in the cstring header.

If you're used to working with C# (or possibly Java, but I can't remember how Java handles string comparison), class comparison (which strings are) is generally done the same way (except their object points instead of a memory address), however the .NET framework overloads the == operator to compare the value of strings.

nmaillet 97 Posting Whiz in Training

Also the suggestion of using the leave event forces the user to complete one textbox at a time. Once they select one they must enter valid data before advancing. As a user I would find this quite unprofessional and irritating. Specially when one couldn't remember, say a credit card number on an online shop, so went to fill everything else out first, oh no im locked into the number field.

Thank you. I just added a small spiel to my last post, but it looks like you already covered it.

nmaillet 97 Posting Whiz in Training

I understand what it does, it won't let the Click event fire since the Button cannot get focus. Now let me ask you this, how do you validate a TextBox that the user never selects?

EDIT: A bit of personal preference, but I believe this is poor design. First, I don't believe a message box should be shown for every single validation error; it can break workflow for business users and simply be annoying for consumers. That's a bit of a minor gripe, but there are some important issues as well. For instance, what happens if a user tries to tab their way down to a particular TextBox? Suddenly their stuck filling out another TextBox. This isn't really an issue for names, addresses etc. It does become an issue when you start introducing large fields like descriptions, comments, etc. This may not make much of a difference in this case (since I have no idea what the form data is); however, having a user friendly UI can be very important.

nmaillet 97 Posting Whiz in Training

Why limit yourself to 20? You could use either of these:

  • (<tab>){2,}
  • (<tab>(?:<tab>)+)

See the Quick Reference from the MSDN for more info. Both are simple ways to capture two or more tabs. Also, are you looking for the string "<tab>" or tab characters? You would use the character escape \t for tabs, and also note there's a \s to match all white-space characters should you be so inclined.

nmaillet 97 Posting Whiz in Training

No, the textbox_leave is subscribed to Leave event of the every textbox you decide, it doesn't need to be in the register click event.

What good is validation logic that doesn't prevent the user from submitting information? It's better than nothing, but doesn't really do what most developers want, and it would seem this includes the OP.

nmaillet 97 Posting Whiz in Training

Yeah, sure... It would be easier to use a for-loop instead of a foreach-loop. You would handle the first item before the loop, like this:

if (words.Length > 0)
    strFile.Append(word[0] + " ");

Then, you would change the foreach-loop to a for-loop:

for (int i = 1; i < words.Length; i++)
    strFile.Append(i + ":" + words[i] + " ");

You could do the first part inside the for-loop (or the foreach-loop), but it would add a condition that would have to be checked on every iteration, which would only evaluate differently on the first iteration.

nmaillet 97 Posting Whiz in Training

@nmaillet well then why are you frustrated for that? why can't you just ignore that then? if you're an atheist so be it, you're just showing how afraid you are to be an atheist

I would say I'm more annoyed than frustrated. The same type of annoyed I get around the holidays when I see people saying "Merry Christmas" to everyone in the stores, no matter what their religious background.

nmaillet 97 Posting Whiz in Training

If it's simple enough, you could use the classes in the System.Drawing.Printing namespace.

nmaillet 97 Posting Whiz in Training

Take a look at strtol for signed long integers or strtoul for unsigned long integers. In particular, look at the example from the first link; it could easily be made into a loop that can handle your problem.

nmaillet 97 Posting Whiz in Training

How is that method still "active"? Are you creating a second thread for each movement action? Generally, if you want to explicitly move something, you would have a method set the object's speed, then the actual movement is handled each step through the main game loop. Something like this:

function move_left() {
    hspeed = -1.0;
    ...
}

function move_right() {
    hspeed = 1.0;
    ...
}

function game_loop() {
    ...
    obj.x += obj.hspeed;
    ...
}

You also shouldn't be incrementing your speed, you should be setting it. With so little information, I can't really give you any more advice. Please post some code or, at least, some details on how your handling movement.

nmaillet 97 Posting Whiz in Training

Jason, Since this is the C forum, why all the C++ suggestions? Steer him correctly to C solutions.

To me, it looks like he was trying to explain the difference, since the OP doesn't seem to understand. Wouldn't the correct solution be better than the C solution?

EDIT:

Walt, I am aware of which forum this is, but from the OP's post it's kinda ambiguous which language they are trying to write in. Are they trying to write in C or C++? They have an extremely bad mix of both in their code.

And it wouldn't be the first time that a noob incorrectly posted a C++ question in the C forum would it? How many times has C code been incorrectly posted in the C++ forum, or vice versa?

Because of the ambiguity, I simply tried to cover both bases. Does that really deserve being downvoted?

If the OP's code was intended to be C, they now know what to do to correct their code and can safely ignore the C++ related parts of my answer. If by some chance they have posted in the wrong place and were trying to write C++, they also know what they need to do.

Also my reply was a little brief because I was on my phone at the time. Thanks to the fiddly nature of my phone and the limited screen-space, my reply wasn't as comprehensive or detailed as I would have liked.

Seriously, what is your problem? …

nmaillet 97 Posting Whiz in Training

What problem are you having?

Couple things I see right away:

  • You'll want to keep clearing the StringBuilder, otherwise you're going to keep appending everything you previously appended.
  • The using block for StreamWriter should be nested outside the foreach block. You don't want to keep opening and closing the file for every iteration.

Maybe I should quickly explain the using block. It is used to dispose of unmanaged resources. In other words, resources not managed by the .NET framework, like things the Operating System manages (such as file handles, network resources, etc.). The class handles this by implementing the IDispoable interface, which has a method called Dispose(). So, something like this:

using(StreamWriter writer = new StreamWriter(fileName))
{
    ...
}

is essentially equivalent to:

StreamWriter writer = new StreamWriter(fileName);
try
{
    ...
}
finally
{
    writer.Dispose();
}

Note that it still attempts to call Dispose(), even when an Exception is thrown. The point I'm trying to make is, when Dispose() is called on a StreamWriter, the file is flushed and closed. There are quite a few things that happen here, that can make this an expensive call.

So, bringing it back around, you should almost always keep a file open for as long as you need it. There are cases where you can't (or shouldn't) keep files open for very long, but I don't think it applies in this situation.

nmaillet 97 Posting Whiz in Training

Assuming the number is a string (since it is greater than a 64-bit unsigned integer), you could do something like this:

char *smallStr, *bigStr;
size_t index, offset;

smallStr = "2345654345555556667777";
bigStr = (char*)calloc(100, sizeof(char));

/* This copies the null terminator from smallStr. Change to "100 - strlen(smallStr);" if you do not want the null terminator. */
offset = 99 - strlen(smallStr);

for(index = 99; index >= offset; index--)
    bigStr[index] = smallStr[index - offset];

/* Pad bigStr with 0's */
for(index = 0; index < offset; index++)
    bigStr[index] = '0';

Hope that's what you meant...

WaltP commented: Close enough -- but now he doesn't have to think about it anymore since you handed him the code. -3
nmaillet 97 Posting Whiz in Training

I'm not entirely sure what you are asking. You can iterate through an array in reverse like this:

for(i = size_of_array - 1; i >= 0; i--) {
    ...
}

Or refer to the array like this:

array[size_of_array - 1 - index] = some_value;
nmaillet 97 Posting Whiz in Training

There are a number of libraries that deal with large integers, such as GMP.

nmaillet 97 Posting Whiz in Training

Take a look at the System.Net.Sockets namespace. You would start by initializing a Socket class. I'll assume you are using TCP (if you aren't, it can vary). You'll have to call the Bind() method on both the server and client sockets. On the server end, you call Listen() and on the client end, you call Connect().

Read through some of the documentation on the MSDN for specifics, but if you need any clarifying, feel free to ask (or you can always Google C# socket tutorial).

nmaillet 97 Posting Whiz in Training

It's possible... you'd have to use Reflection (essentially it makes the program source code aware). I would highly recommend you do not do this, as it can be very prone to bugs/errors and is generally reserved for debugging (or possibley very speciallized circumstances).

What are you trying to achieve?

nmaillet 97 Posting Whiz in Training

You want the substring to start at the character following the colon. So you would add one to x:

string d = word.Substring(x + 1);

There was another point I was trying to make. Constantly adding to the StringBuilder is going to consume a lot of memory. You can nest your using statements, so you can write out each line of data as you iterate through the file:

static void Main(string[] args)
{
    StringBuilder strFile = new StringBuilder();
    using (StreamReader reader = new StreamReader(@"F:\New folder (4)\xxx.txt"))
    {
        using (StreamWriter outfile = new StreamWriter(@"F:\New folder (4)\xyz1.txt"))
            for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
            {
                char[] charsToTrim = { ' ', '\r', '\n' };
                string kkj = (line.TrimEnd(charsToTrim));
                string[] words = kkj.Split(' ');
                foreach (string word in words)
                {
                    int x = word.IndexOf(':');
                    string d = word.Substring(x);
                    strFile.Append(d + " ");
                }
                outfile.WriteLine(strFile.ToString());
                strFile.Clear();
            }
        }
    }
}

I just changed it so that it would write out the StringBuilder data to the file, and clear the StringBuilder. You could also directly write to the file, and remove the StringBuilder completely, but at least this way, we wouldn't have to consume so much memory.

Just as an aside, the StringBuilder is a wrapper for a character array (or possibley multiple character arrays). This has a limited capacity, and once you pass it, it either has to allocate another chunk of memory, or reallocate its current array (i.e. allocate and copy everything to the new …

nmaillet 97 Posting Whiz in Training

You could give SqlCommand.Cancel() a try, although I hear it isn't very reliable. Another option is to close the connection. Closing the connection should immediately raise an exception (which you'll have to deal with).

nmaillet 97 Posting Whiz in Training

First, I wouldn't recommend using the ReadToEnd() method or storing everything in a StringBuilder before writing it to a file. In your example, it is not so bad, since you are essentially doing one line at a time, but when you go to read that file with 10000 lines, it will start consuming a significant amount of memory. Also, you shouldn't be opening and closing the same file over and over again. You should start with something like this:

using(StreamReader reader = new StreamReader(...))
{
    using(StreamWriter writer = new StreamWriter(...))
    {
        ...
    }
}

You could then use a loop to read each line like this:

for(string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
    ...
}

You could then use the Split() method to break up the line by spaces, use something like IndexOf(':');, and use the Substring() method to retrieve the data and index. You could a bit of error checking at this point (i.e. increment a counter to detect missing or out of order indices, checking to ensure the data is valid, etc.) if you wish. You could use a StringBuilder to construct each line, and write each line out to the StreamWriter.

Let me know if I need to clarify anything. Best of luck.

nmaillet 97 Posting Whiz in Training

That isn't a trivial task. Even if you only wanted to be able to support one platform (Windows, Linux, etc.) the Java API is huge. It would take several experienced programmers (or maybe one really dedicated programmer) a good amount of time to implement/test it.

Also, why would you really need to do this? If performance was an issue, a language converter would likely created more problems than anything else.

nmaillet 97 Posting Whiz in Training

This also depends on your network as well. Many modern switches provide layer 3 support as well; that is, they are IP aware. If they do, they will keep routing tables, and usually only forward it to one port. Some commericial switches have a specific port that all packets are forwarded to for packet sniffers to use.

nmaillet 97 Posting Whiz in Training

Yeah... I have no idea what you're trying to show here...

Why don't you start by explaining what you are trying to do, give some code of problem areas, explain what it is doing wrong and what is should be doing, and any unexpected exceptions you are getting (and where they're coming from)?

nmaillet 97 Posting Whiz in Training

I don't know how to do that, teach me please

You would set that up in the constructor (or Form.Loaded event handler) with something like this:

textBox7.Tag = "First Name";
textBox7.Leave += textBox_Leave;
textBox8.Tag = "Last Name";
textBox8.Leave += textBox_Leave;
...

The Tag property simply holds any object. The Leave event is triggered whenever focus is taken away from the control (TextBox). This means any time the user navigates to another control, via the mouse or keyboard, the event is triggered. This will not implicitly check the conditions before any actions are performed however (such as a button click).

You can take a look at this article. It shows the built in validation logic for WinForms. You could handle the Validating event the same way you would handle the Leave event, but you could also call ValidateChilder() in the button Click event.

If you don't want to use that, you could setup a quick array in the constructor:

TextBox[] checkEmptyTB = new TextBox[] {textBox7, textBox8, ...};

Then iterate through them in the Button.Click handler:

bool empty = false;
foreach(TextBox tb in checkEmptyTB)
    if(tb.Text.Trim() == string.Empty)
    {
        empty = true;
        break;
    }
if(empty)
    MessageBox.Show("Please fill up all the required details.");
else
{
    ...
}

God Bless you all!

Isn't it a bit presumptuous to assume others believe in the same things you do?

nmaillet 97 Posting Whiz in Training

Aren't we getting a bit off topic here? This looks like a homework question, and a fairly specific one at that. It looks like something from a programming intro course/tutorial, not an algorithms course. Some teachers/professors/markers may give you bonus marks; most, in my experience, take away marks for not doing what the question asked.

It doesn't seem like a question that is concerned with efficient algorithms, it seems like a question concerned with for loops...

nmaillet 97 Posting Whiz in Training

You may want to check this out.

Although I agree that is the proper way to handle something like this, the question says to use nested for-loops.

nmaillet 97 Posting Whiz in Training

You need a symbol to concatenate the "\Desktop\" and username. Also, you should be referencing the Text property of the TextBox username, not the TextBox itself.

Captain_Jack commented: Thanks +0
nmaillet 97 Posting Whiz in Training

What are the errors?

nmaillet 97 Posting Whiz in Training

Nobody's going to do your homework for you. Show some work and we'll help. Although it isn't a best practice, since it's a 6-bit number, you could do it with 6 for-loops, which I think is what their looking for.

nmaillet 97 Posting Whiz in Training

What error are you getting?

nmaillet 97 Posting Whiz in Training

You would just use the string.Split() method. Essentially the same thing you did in the LINQ statement.

nmaillet 97 Posting Whiz in Training

You could use a loop. First, if your CSV files get very big, this is going to consume a large chunk of memory to store the entire file at once. I would recommend using a StreamReader with the ReadLine() method in a loop. You can start with something like this:

using(StreamReader reader = new StreamReader(@"C:\Users\Zach\Desktop\test.csv"))
{
    for(string line = reader.ReadLine(); line != null; line = reader.ReadLine())
    {
        ...
    }
}

Once the StreamReader is disposed of, the file will be closed. Now, back to your question. Each iteration of the loop, you'll want to construct an XElement and parse the single line of the CSV file. You can then store it to a file, either by using your method or using the XElement.Save() method. Using the Save() method adds the <?xml ... ?> tag to the beginning of the file. This makes it a valid XML file, but could consume more disk space.

nmaillet 97 Posting Whiz in Training

You generally use the Children property of any class that derives from Panel. For example:

stackPanel.Children.Add(x);

WPF handles layout differently than WinForms. In WinForms, each control can handle its own position (although a LayoutEngine can override this). In WPF, the parent control positions its children. A StackPanel will position controls one after the other, either horizontally or vertically. You may want to look at the Canvas class. It positions controls relative to its local origin (top left corner of the panel). You would then use the static methods (which are wrappers for attached dependency properties) to sets the controls position. For example:

canvas.Children.Add(x);
canvas.SetLeft(x, 16.0);
canvas.SetTop(x, 32.0);

Sizing is handled through the Width and Height propties of the TextBox. Also note that WPF does not use pixels (note that I used double values in the above example), it uses logical units (which are essentially pixels when using 96 DPI). This can create some issues, since the WPF rendering engine will use anti-aliasing, which can lead to "fuzzy" lines. This may not be relevant in this case, but keep it in the back of your mind, and look into the SnapToDevicePixels (all versions of .NET) and UseLayoutRounding (.NET 4.0 only) properties if it becomes an issue. Hope this helps.

nmaillet 97 Posting Whiz in Training

In what context? If you're just doing standard mathematical computations, work your way up using order of operations. If you're doing it for a compiler construction course, it gets a bit more involved. Nobody's going to do your homework for you, so show some work.

nmaillet 97 Posting Whiz in Training

What CLR data type are you using? Should be decimal if I'm not mistaken.

nmaillet 97 Posting Whiz in Training

what is problem ? can you specify ?

I didn't say there was a problem.

nmaillet 97 Posting Whiz in Training

Oh ok, I've only ever heard the term I/O where I've worked. In either case, yes you could cast it to a floating point number. Personally, I try not to use them unless I need them, but there's no problem with using them.

nmaillet 97 Posting Whiz in Training

I'm not sure what you mean by i/p... but if you want to not include a certain amount of time while something else is happening you could try this:

clock_t ticks;
clock_t ticks_temp;

ticks = clock();

...

ticks_temp = clock();
...
/* don't time this */
...
ticks -= (clock() - ticks_temp);

...

ticks = clock() - ticks;
/* print the time */
nmaillet 97 Posting Whiz in Training

Change this:

for (int j = 0; j < number; j++)
{
    list_nordpool.Add(double.Parse(all_prices[0][j]));
    list_tvh.Add(double.Parse(all_prices[1][j]));
    list_ttoist.Add(double.Parse(all_prices[2][j]));
    list_tarj1v.Add(double.Parse(all_prices[3][j]));
    list_tarj2v.Add(double.Parse(all_prices[4][j]));
}

to this:

for (int j = 0; j < number; j++)
{
    list_nordpool.Add(all_prices[0][j] == "" ? 0.0 : double.Parse(all_prices[0][j]));
    list_tvh.Add(all_prices[1][j] == "" ? 0.0 : double.Parse(all_prices[1][j]));
    list_ttoist.Add(all_prices[2][j] == "" ? 0.0 : double.Parse(all_prices[2][j]));
    list_tarj1v.Add(all_prices[3][j] == "" ? 0.0 : double.Parse(all_prices[3][j]));
    list_tarj2v.Add(all_prices[4][j] == "" ? 0.0 : double.Parse(all_prices[4][j]));
}

This compares the string to the empty string. If they are equal, it passes 0 into the Add() method. Otherwise, it passes the return value from double.Parse() (but does not execute Parse() unless it has to).