gusano79 247 Posting Shark

Hello everyone,

I'm a java programmer writing a half graphical half text rpg. For the moment I read my data from text files, e.g.
Enemies.txt

id
name
hp

and so forth. However, I want to make it a little more clear to handle, as in a database format. I can work with MySQL, but I want all the data to be on the end-user's computer, so without having to connect to the server database.

The only other thing I can think of is Excel, but I'm wondering if there aren't any other alternatives. If you know how real games used to do it, it would be really helpful.

I'd avoid Excel; that's a nightmare waiting to happen.

A proper database might be overkill, though, especially if your data are simple. Does "clear to handle" mean you want it to be human-readable and editable, or are you referring to making it easier for your code to load stuff in? Or is it a balance of the two?

As a step up from plain text, XML might be a good choice for you. It's structured and well-supported by standard libraries, so it helps the machines, but it's also still text, so it's still easy enough to edit by hand.

JSON is another option for text-based structured data.

If you really want a local-only database, I recommend SQLite. It's been widely adopted for use by Web applications and in embedded …

gusano79 247 Posting Shark

A bit of clarification: In a single-threaded application, the main thread handles updating the forms and other user interface elements. If you simply put a long-running task in a button's click handler, the main thread stays busy there, and doesn't get a chance to update the UI until it's done. This is why you can't do anything on the form once it starts. When you call DoEvents on the main thread, it processes any pending messages to the application, so the UI remains responsive. The trick is you have to call it repeatedly while your task is running.

So. You could sprinkle your "start" task with calls to DoEvents, have the "abort" handler set some Boolean variable when clicked, and have your "start" task check this variable periodically and stop when it's set.

If you search the Internet, you'll find a variety of opinions about DoEvents. Here's mine: It's fine for simple tasks you want to happen in the main thread, and lets you avoid the complexity of multithreading. As your tasks get longer and more involved, though, it can get ugly.

I don't use DoEvents, and I don't recommend it to anyone, either. Instead, consider the BackgroundWorker class. All you have to do is add an event handler to do your work, and this class takes care of the multithreading for you. To abort, you would use the CancelAsync method; your "do work" event handler has to check the

nick.crane commented: Exactly what I do. +10
gusano79 247 Posting Shark

This is your problem:

void putvalue(X a)
{
    a.x=30; //
}

You're passing a by value, not by reference, so when you pass test to putvalue , you're actually modifying a copy of test , not the original object itself, and your modified copy gets lost when putvalue returns.

You can do it with a pointer:

class X
{
    int x;
public:
    void showdata()
    {
        cout << "x =" << x << endl;
    }

    friend void putvalue(X* a);
};

void putvalue(X* a)
{
    a->x = 30;
}

int main()
{
    X test;
    putvalue(&test);
    test.showdata();
    getch();
    return 0;
}

You can do it with a reference:

class X
{
    int x;
public:
    void showdata()
    {
        cout << "x =" << x << endl;
    }

    friend void putvalue(X& a);
};

void putvalue(X& a)
{
    a.x = 30;
}

int main()
{
    X test;
    putvalue(test);
    test.showdata();
    getch();
    return 0;
}
gusano79 247 Posting Shark
#include <iostream.h>

Try this instead:

#include <iostream>
gusano79 247 Posting Shark

In my opinion, it doesn't matter which language you choose. The challenges and problems you will face are going to be independent of the implementation language. The major difference between languages as they relate to graphing functions will be in how you draw the graph and show it to the user. Java and VB.NET are different, but for your purposes, they're roughly equivalent.

If you're looking for a Java/VB.NET comparison, I'm sure a quick Internet search will turn up a wide variety of opinions.

gusano79 247 Posting Shark

sfuo provided some concrete code examples; here's some theory:

Hi, I already tried searching through the array of tiles/pipes,
but I encountered a problem, since my current loop only searches downward,
I thought, what if the fuel is .. flowing up/ going northward(caused by tile/pipe orientation)

Right. This is why you should start thinking of your tiles as a graph, not an array. The actual implementation might be an array, but the graph concept provides a better perspective for spreading fuel throughout the system.

I think the solution requires adding another array search, but in a different direction
this requires more "for loops", making the code long/messy, and might make the game run slow.

You're on the right track with the "different direction" idea, but it's not an additional array search with a bunch of for loops. It's one search through the whole system, but not ordered by the shape of the array.

as for breadth-first search, Im still confused and cant think of a way to put my tiles/pipes into a tree...
bec. of the possibility that a child can have 3 parents and the child can also have 3children.

It's not a tree, it's a graph. A tree is a type of graph, but it's not what you want. A graph has no explicit root node, and there are no children, just connections between nodes. The article on graphs I linked above has a nice example of …

daniel955 commented: thanks for taking the time to help +2
gusano79 247 Posting Shark

But what I want to know is what is << doing exactly, I read something about moving the binary number

<< is a left shift. From the linked article: "Shifting left by n bits on a signed or unsigned binary number has the effect of multiplying it by 2^n."

but since 1 is 1 in binary wouldn't this make it 1? And then the other 1 would not be 1 000 000? Why is that that it becomes 64?

In your example, the value of bits[i] is always 0 or 1, and i is the position of each bit, so shifting bits[i] left by i will get you the numeric value that bit represents in a byte.

Break it down:

The statement bits[] = {1, 0, 0, 0, 0, 0, 1, 0} is the same as

bits[0] = 1;
bits[1] = 0;
bits[2] = 0;
bits[3] = 0;
bits[4] = 0;
bits[5] = 0;
bits[6] = 1;
bits[7] = 0;

And the loop with character += bits[i] << i; is the same as

char character = 0;
character += bits[0] << 0;
character += bits[1] << 1;
character += bits[2] << 2
character += bits[3] << 3;
character += bits[4] << 4;
character += bits[5] << 5;
character += bits[6] << 6;
character += bits[7] << 7;

Substituting the values of the bits array:

char character = 0;
character += 1 << 0;
character += 0 << 1;
character += 0 …
gusano79 247 Posting Shark

You probably want a breadth-first search, with the tiles as nodes and edges between adjacent tiles in each of the four cardinal directions.

If you only have one fuel source in the game, that's your root node. If you have multiple fuel sources, just mark each of them as 'visited' to start with.

daniel955 commented: thanks for the information +1
gusano79 247 Posting Shark

I recommend that you decouple your drawing from the actual framerate. Basically, you keep track of how much time has elapsed since the last frame, and then draw only the part of the waveform that should have been drawn in that amount of time. That way, your framerate can be imprecise or even highly variable, but the effect is that the waveform appears to be drawn at a constant speed.

You might want to read Glenn Fiedler's article on this topic, especially starting at the "Free the physics" section. It's written with a focus on physics engines, but the concept applies just as well here.

vijayan121 commented: Yes +11
gusano79 247 Posting Shark

Not using looping could mean recursion or goto label, depending on definition.

Or you could just put one "round" in a function, and call it 10 times explicitly, returning any information you need to track across the whole game.

TrustyTony commented: Good thinking. +13
gusano79 247 Posting Shark

Thanks for reply.But please explain how I produce asm code through that command.I mean where to put that command in c::b , as I always use "run and build" button.

"Project" menu > "Build Options..." item > "Compiler settings" tab > "Other options" sub-tab > Add compiler options to the text area.

What you type in depends on your compiler. If you're using GCC, try "-save-temps"--it will both compile your program and preserve the generated assembly files.

gusano79 247 Posting Shark

The readme on the fnv hash page lists an example usage:

//For example to perform a 64 bit FNV-1 hash:

	#include "fnv.h"

	Fnv64_t hash_val;
	hash_val = fnv_64_str("a string", FNV1_64_INIT);
	hash_val = fnv_64_str("more string", hash_val);

// Produces the same final hash value as:

	hash_val = fnv_64_str("a stringmore string", FNV1_64_INIT);

...

I have not encountered anything that explains why you would send the previous hash value to calculate the next.

I'm not familiar with the specifics of the FNV hash, but looking at the code you quoted, here's what I think is going on:

In your example code, the fnv_64_str function takes two parameters; first, the string to hash, and second, an initialization value. This appears to be representative of the internal state of the FNV hash function, which also the result that is returned from the hash.

The first call to fnv_64_str starts with an internal hash value of FNV1_64_INIT , which you can consider a sort of "null hash"--I would expect this value to be returned if you tried to hash the empty string ( "" ). Then for each character in the string to be hashed, it updates the internal hash value, until it reaches the end of the string, then it returns the internal hash value.

So the two-line example is just a way to show you can "interrupt" the hash and finish it later. This might be useful, for example, if you're hashing some sort of input stream as it comes across a network connection, …

gusano79 247 Posting Shark

if I have a new linked list element I would like to hash into my array, my hash array size must be 2^(Bit size of hash)?

Conceptually, yes... your hash table should be able to accommodate every possible hash value.

In practice, though, you wouldn't normally allocate the entire hash table at once. This can work for short hash functions, but (for example) a 32-bit hash table storing 32-bit pointers would need (2^32)*4 bytes = 16 GB of storage. Hash tables are typically implemented using some kind of dynamic array.

--smg

gusano79 247 Posting Shark

I would take that to mean that the hash function has two operating modes, one that produces a 32-bit hash, and another that produces a 64-bit hash. The FNV hash you linked actually has six different hash lengths.

Better terminology might be that you have a family of hash functions that represent the same basic hashing technique, and the individual hash functions are variations that produce different hash sizes.

gusano79 247 Posting Shark

There are a variety of ways to do this; see these links for some ideas to get you started.

gusano79 247 Posting Shark

You can read a file with code that looks like this:

String infile1 = @"c:\ipAddresses.txt";
                StringBuilder currentWords = new StringBuilder();

                StreamReader sr = new StreamReader(infile1);

                try //read the file into lines of data
                {
                    do
                    {
                        currentWords.AppendLine(sr.ReadLine());
                    } while (sr.Peek() != -1);
                }
                catch
                {
                    MessageBox.Show("File [" + infile1 + "] is empty");
                }
                sr.Close(); //close the file
                String final = currentWords.ToString()

infile1 is the directory of your text file. StringBuilder is a special class designed for doing a lot of string concatenations. If you were to concatenate just a normal string many times, it would be very slow.
Once you have your final string, you can use the Split method to split the string into two strings around the colon.

I don't think StringBuilder is appropriate here, as we need to treat each line as a separate IP endpoint... all this does is cram the contents of the file into a string without separating them. A List<string> would be much more useful. But you're going to want to build IPEndpoints anyway, so why not convert inline? Also, StreamReader.ReadLine will actually tell you when the file's done; no need to peek.

Improved code:

List<IPEndPoint> endpoints = new List<IPEndPoint>();
StreamReader reader = new StreamReader("filename.txt");

string line;
while((line = reader.ReadLine()) != null)
{
    string[] parts = line.Split(':');
    
    if(parts.Length == 2)
    {
        // We have two parts, which are hopefully an IP
        // address and a port number. Let's see...
        
        IPAddress address;
        int …
gusano79 247 Posting Shark

What is void * ?

It's the type of a void pointer; essentially, a pointer to somewhere in memory without an associated data type. I'm just using it to demonstrate the size of a pointer on your machine.

Am I right in saying that the first two lines were looking at the actual values stored (the short is 2 bytes, and so is the struct because all it contains is the short ), where as the last two were looking at pointers, and pointers are 4 bytes?

There are no actual values involved; I'm just printing out the number of bytes required to store values of each of those data types. You have the right idea, though--my fake BigInteger should normally be the same size as a short since that's all it contains. Same goes for the three pointer types. The idea there is to show that big_integer_t is clearly not the same thing as a BigInteger (because their sizes are different).

With the add and subtract lines:

big_integer_t add(big_integer_t a, big_integer_t); 
big_integer_t subtract(big_integer_t a, big_integer_t);

What is the second big_integer_t doing? The function is using a parameter called a of type big_integer_t , as well as just the type big_integer_t . I'm sorry, but I don't understand what this second parameter is for.

Those lines are declarations. Essentially they're saying that somewhere later in the code, there will be definitions for two functions, add and subtract , which both take two parameters …

gusano79 247 Posting Shark

The first step in solving that problem is to know what the problem is. I know of at least three different problems that mention a monkey and a banana.

No one knows the solution? I want detailed information about the complexity & heuristic function which we have to choose for the problem & not jokes!

You need to read people's responses more carefully.

Nobody knows the solution because you haven't expressed a clear problem. You ask "How to solve monkey and banana problem"--we're asking you to clearly define the problem first. If you can't do that, any answer we give you won't be very helpful.

gusano79 247 Posting Shark

Another useful method that only requires one line is Directory.GetFiles:

string[] matchingFiles = Directory.GetFiles("F:\\", "student_*.xml", SearchOption.AllDirectories);
var RootDir = new System.IO.DirectoryInfo("F:\\")

Just be aware that you need to specify a doube backslash in order to be interpreted a s a single one.

I recommend using @-style string literal for the search path in this case, as it results in code that in my opinion is a little clearer and easier to read:

string[] matchingFiles = Directory.GetFiles(@"F:\", "student_*.xml", SearchOption.AllDirectories);
ChrisHunter commented: Straight to the point and a great help +1
gusano79 247 Posting Shark

A quick comment on the 3 elements listed by chrjs: Do them in that order as much as possible. It's especially useful to make programming the last thing that actually happens, for a variety of reasons--notably that you'll be able to take advantage of newer technologies without having to rewrite older code.

gusano79 247 Posting Shark

I was trying to get at what you meant by your original question--is it just that you're trying to get a handle on polymorphism in general, or do you have some idea of what "multiple polymorphism" is supposed to mean, and you're looking for that feature in C#?

first i will tell what is polymorphism

there are two types of polymorphism:static and dynamic

static::which take place during compile time

dynamic::take place at run time,which is appreciated by virtual function

eg::float area(float a,float b)
{
return A*b;
}

function name is same where arguments only change A and b are arguments;

That's a poor explanation.

Exact meaning in simple word::one name having different forms or different behaviour of an instance depending upon the situations.

Getting there. How about:

"Polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface."

friend these are basics if u want more about polymorphism means i will provide you ok

...or you could take the extra five seconds and link something:

http://en.wikipedia.org/wiki/Type_polymorphism

http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming


You get polymorphism in C# with abstract classes, interfaces, and generic types. C# doesn't have multiple inheritance, but you can implement multiple interfaces if you want.

vedro-compota commented: ++++++ +1
kvprajapati commented: Correct! +11
gusano79 247 Posting Shark

When switching from 'wireframe' to 'solid', what would be a basic algorithm to render surfaces of an object? In a cube, for example, what surfaces are visible, and what surfaces are not?

You're talking about back-face culling. One way to do this: Don't draw surfaces that have a normal vector that points away from the camera position.

TotoTitus commented: He gave me a mathematically sound answer. +1
gusano79 247 Posting Shark

Oh my. That's one ridiculous infomercial website.

What do you think it was coded in?

If you take the time to read the page, it's right there in the middle of his sales pitch: "...all the software I develop is created using Adobe Flash."

And how long do you think it would take to make something similar to it?

IMO, it wouldn't take very long. The application is neither large nor complex. Mr. Ken Reno is claiming 5 days from concept to version 1.0, and another 19 to get from there to 2.0, and I don't get the impression that he's any kind of lightning-fast software genius. A couple of weeks should be plenty of time, even for a lone developer. I would also expect most of that time would be spent on design and requirements-like activities--actual coding would be very quick.

PythonNewbie2 commented: Great answer! Everything I asked was answered! +1
gusano79 247 Posting Shark

Strings in C# are reference types, as indicated by the C# Reference on MSDN.

Maximum string length will depend on your machine's architecture and memory allocation situation, but the String.Length property is a 32-bit integer, so there's an effective upper bound of Int32.MaxValue.

Running (and developing) .NET applications on Linux can be done with Mono.

I'm not sure what you mean by "which web server we had to use", but if you want an ASP.NET equivalent, see Mono's ASP.NET page.

Ketsuekiame commented: Good answer +1
gusano79 247 Posting Shark

I am working with g++. I always remove warning before running it. I don't know what happened. Thanks anyways.

Turn on warnings; they are useful. If you actually bother to read and understand compiler warnings, it will help you understand what you're doing when you write code.

gusano79 247 Posting Shark

when i try to validate it it gives an invalidCastException.(the line is bolded, this is tha place where the error occurs)

...

how can i solve this.

Rephrasing your question: "Why isn't e.FormattedValue a DateTime ?"

A good next step is to figure out what type of object it really is. Try something like this:

private void dgvActions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
  if (e.ColumnIndex == 2)
  {
    if (e.FormattedValue != null)
    {
      MessageBox.Show(e.FormattedValue.GetType().FullName);
    }
  }
}

Once you know what type e.FormattedValue really is, your new question can be: "Why is e.FormattedValue this type?" With luck, knowing what type it is will give you some idea of where it came from.

ddanbe commented: Good thinking! +6
gusano79 247 Posting Shark

When i run it, ALL objects have the same dying age, so weird. So I added a breakpoint in the function that generates the dying age and guess what, it works perfectly when debugging but not in a normal run. So it's like the function doesn't have enough time to generate different values everytime the constructor calls it (10 times in a row) but it does have the time to generate different values if i'm debugging the program (going instruction by instruction).

How can i fix this? Why does it seems to not work properly when working without stopping everytime i call this function?

I think your problem is in here:

private int CalcularEdadFinal(int eF)
{
  Random randNum = new Random();
  diferencia = randNum.Next(0, 10);
  if (diferencia % 2 == 0) return eF - diferencia;
  else return eF + diferencia;
}

Every time you're getting a new final age, you're creating a new Random object. You're on the right track; the Random classes are getting created fast enough that each Random object gets the same seed, and therefore generates the same random numbers.

The MSDN documentation for Random says: "The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers."

The solution to your problem …

gusano79 247 Posting Shark

What you have described is called "rejection sampling". That sounds like a reasonable way to go about this to me. If you use std::vector to to store the elements you can then use find() from the stl to do the search. It shouldn't be that bad for something as small as a sudoku game.

I'd use rejection sampling if the sample space were much larger than the number of samples I needed, but for this, it seems like overkill.

So far we've been approaching this as a "generate some random numbers" problem, when it really isn't. You already know which numbers you want, i.e., 1-9 inclusive. What you want to be random is the order of these numbers; you're looking for a random permutation.

One way to do this is to start with a list of the numbers, and then walk through the list, exchanging each element with a random other element, which mixes them up nicely. This is called the Fisher-Yates shuffle.

Also, remember that the diagonals and each of the 3x3 square regions can't have the same number twice. Simply generating random permutations for each row doesn't guarantee these constraints will be met.

gusano79 247 Posting Shark

no one uses C these days

Says who? C is alive and well. For example, here's a list of free software written in C.

gusano79 247 Posting Shark

int a; counts as a tentative declaration in C. If you don't write in a default value, you can declare the variable again later. Try providing a value both times you declare it and you should get an error:

#include <stdio.h>

int a = 42;
int a = 42;

int main()
{
  a = 100;

  printf("fdfsa");
  scanf(&a);
}

You get the error in C++ because C++ doesn't have tentative declarations.

Also: Best practice in C is to only declare variables once. Otherwise, things can get funky really fast, especially if you have multiple declarations in different files... yuck.

gusano79 247 Posting Shark

So if I'm reading this right, you have a file handle that was returned by io.open at some previous point, but you need the filename that was used to create the handle so you can truncate it. Yes?

For now, I'm assuming that we're talking about Lua 5.1.4 because it's the current release. Are you using anything older than 5.1?

The io library doesn't provide anything that can truncate a file, so it looks like you're on the right track with io.open("somefile.ext", "w+") if you need a 100% standard Lua solution.

I don't think Lua can help you directly on this one. io.open doesn't keep the filename around, so you'll need to keep track of the filename when you open it. The file handles that io.open returns are userdata objects, which you can't modify from Lua, so you can't just stick the filename string in the file handle, either. I think we're left with creating some sort of custom file object--at its simplest, it could be a table with two entries, one for the filename, and one for the file handle.

gusano79 247 Posting Shark

it give a value "System.Data.DataRowView" in the combo box.The code i wrote is added below.

cmbPI.DisplayMember = "FirstName" + " " + "LastName";

This is happening because there is no property of DataRowView called "FirstName LastName". It couldn't, because there's a space in there.

If you read the MSDN documentation for the DisplayMember property, you'll see that you have to specify the name of an actual property of the object you're putting in the combo box. The DisplayMember property doesn't actually do anything, it just tells the combo box where to get its value.

If there's a property of your DataRowView that will provide the text you want to show in the combo box, specify the name of that property here. If there isn't one, you can create your own class to wrap the DataRowView which provides a string-valued property that is formatted how you want, then put those objects in the combo box instead of using the DataRowView directly.

gusano79 247 Posting Shark

The project will basically need to track changes that occur within a string so they can be highlighted.

It looks like you need some kind of diff feature for your project.

This is a well-understood problem, and you should be able to find an implementation that meets your needs. One example is the Diff.NET, which includes a library called "MeneesDiffUtils" that may work well for you.

Ideally the application would spot that change in the string and prehaps inside a new word at the index of the change, say '<span class="Change">' and then the closing tag at the end of the change.

A diff library will tell you where all of the changes are, but you're on your own for deciding what to do with them. If you expect to be performing lots of string operations, I recommend you use a StringBuilder.

gusano79 247 Posting Shark

why in this code the "codeArray[]" is used??
what does its really means??

void FunctionTwo (int codeArray[]){
     cout<<codeArray[1];
}

When you declare a function parameter as an array, what really happens is that a pointer to the first element of the array is passed, not the entire array. It's basically the same as this:

void FunctionTwo (int* codeArray){
     cout<<codeArray[1];
}

Here's a page with some more explanation.

tux4life commented: It's all good :) +6
gusano79 247 Posting Shark

Please explain about the Right and Left shift operators in java.. I am new to programming concepts.. So please explain me with examples..

Google is your friend.

They are bitwise shift operators. Here are some links to get you started.

thariqrasheed commented: thanks for the post +0
gusano79 247 Posting Shark

Your original "if" statement mutated into a loop there... let's look at the "if" by itself first.

A basic assembly "if" block might look like this:

cmp a, 80
  jne notequal
  ; a == 80, do something here
  jmp done
notequal:
  ; a != 80, do something else here
done:
  ; program continues...

In your case, it can be a little simpler:

cmp a, 80
  je equal
  inc a  ; only increment when a != 80
equal:
  ; program continues...

You could write your loop using similar code, but the 8086 instruction set includes a LOOP instruction.

A basic assembly "for" loop block might look like this, using CX as your loop counter:

push cx
  mov cx, 80
label:
  ; do something here
  loop label
  pop cx

Note that LOOP counts down to zero.

gusano79 247 Posting Shark
string host = this.HostAddress.Text.Replace(@"\", @"\\");

Immediate reports host as:
"C:\\\\Program Files (x86)"
When it should report it as:
"C:\\Program Files (x86)"
the original text was:
"C:\Program Files (x86)"

Any thoughts?

Your call to Replace is correct, as you can demonstrate by running the following tests (the third one is supposed to be incorrect):

using System;

class Program
{
    public static void Main(string[] args)
    {
        // No @, double \
        WriteReplacement("C:\\Program Files (x86)");
        
        // With @, single \
        WriteReplacement(@"C:\Program Files (x86)");

        // With @, double \
        WriteReplacement(@"C:\\Program Files (x86)");
        
        Console.ReadKey(true);
    }
    
    private static void WriteReplacement(string text)
    {
        Console.WriteLine(
            "\"{0}\" --> \"{1}\"",
            text,
            text.Replace(@"\", @"\\"));
    }
}

...so I imagine there's something going on with the text in HostAddress .

I have to ask, though--why do you need to escape the slash in the first place? You only have to escape them when you're writing string literals in code. If you're getting typed input from the user, HostAddress.Text will be the correct path string, and doubling them up will confuse the standard IO classes.

gusano79 247 Posting Shark

If you're only adding .1 or .25 etc, but the result shows up as something which isn't a multiple of .1 or .25, then y was clearly not equal to a multiple of .1 or .25 to begin with. In other words your initial y value must have been something weird; how was y initially set?

More likely it's due to floating point representation, in particular: The decimal value 0.1 has an infinite binary expansion, so it's impossible to represent accurately in a floating-point number.

gusano79 247 Posting Shark

This is the algorithm I am working on, however, I believe it is not working properly because it chooses points that are very close to each other to be centers:

If anyone can offer any insight on this, I would greatly appreciate it. The algorithm seems to only be selecting points far away from the first center (which is chosen randomly outside of the above loop.)

The pseudocode looks okay; I've attached a quick little .NET console program that appears to confirm your approach. This suggests to me that there might be some errors in your implementation of that algorithm. If you post actual code, we could have a look at it.

I am trying to write a clustering algorithm where, given location of certain points (I.e, latitude and longitude) I need to choose 50 of these to be cluster centers such that the diameter of each cluster is minimized. To that end, I believe that the program should choose the next center to be the point that is farthest away from all the previous centers.

Questions:

  • Are you assigning non-center points to the cluster with the nearest center?
  • Are you limited to choosing existing points as cluster centers, or can you use any lat./long. coordinate for a center?
  • Does "diameter" mean the distance from a cluster's center to the farthest point in each cluster?

It sounds like an iterative approach--something like Lloyd's algorithm--might be appropriate:

  1. Pick an initial set of centers (randomly, …
Agni commented: like the spirit :) ... +2
gusano79 247 Posting Shark
<Root><Subject>xyz</Subject></Root>
<Root><Subjects><Subject>xyz</Subject></Subjects></Root>
<Root><Hierarchy><Subjects><Subject>xyz</Subject></Subjects></Hierarchy></Root>

Adding minOccurs="0" to Hierarchy/Subjects element does not suffice the requirement since then it doesnot expect Subject element.

That's because minOccurs only indicates how many times that element may appear; it doesn't relax any restrictions on the structure of conforming XML documents.

If you want the root element to contain different kinds of elements, you have to say it explicitly in the schema. In this case, it looks like you want a choice element, for example:

<xs:schema xmlns:xs="[schema namespace]">
  <xs:element name="Root">
    <xs:complexType>
      <xs:choice>
        <xs:element name="Hierarchy">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Subjects">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="Subject" type="xs:string" maxOccurs="unbounded" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="Subjects">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Subject" type="xs:string" maxOccurs="unbounded" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:sequence>
          <xs:element name="Subject" type="xs:string" maxOccurs="unbounded" />
        </xs:sequence>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

With this schema, someone writing a conforming XML document can now choose whether to use the "Hierarchy" element, the "Subjects" element, or just write a pile of "Subject" elements into the root element.

At this point, the schema is complex enough that you should start separating out complex types from the structure definition, primarily so you don't have to repeat the "Subjects" element definition:

<xs:schema xmlns:xs="[schema namespace]">
  <xs:element name="Root">
    <xs:complexType>
      <xs:choice>
        <xs:element name="Hierarchy">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Subjects" type="SubjectsType" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="Subjects" type="SubjectsType" />
        <xs:sequence>
          <xs:element name="Subject" type="xs:string" maxOccurs="unbounded" />
        </xs:sequence>
      </xs:choice>
    </xs:complexType>
  </xs:element>
  <xs:complexType name="SubjectsType">
    <xs:sequence>
      <xs:element name="Subject" type="xs:string" maxOccurs="unbounded" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

For further readability and ease of modification/extension and maintentance, I'd …

gusano79 247 Posting Shark

Returning to the original problem, even Java suffers from this risk of falling into infinite loops dues to recursive function calls.

C is designed with the assumption that if the the programmer does something, however strange it seems, it is because he means to do it.

C is notorious for giving you "enough rope to shoot yourself in the foot"--but it doesn't matter what language you're talking about... if it allows you to define a recursive function, you can always define one that never terminates.

Allowing recursion without this possibility is sort of like inventing a language in which untruthful statements aren't grammatical--a warm, fuzzy thought, but such a thing simply doesn't exist.

Sometimes recursion loops are detectable, but no development environment I've ever worked with has even bothered to try.

The halting problem is at the heart of this issue... I recommend you study it if you haven't seen it already. This version is more entertaining.

jbennet commented: thats an interesting link +21
gusano79 247 Posting Shark

AFAIK Normal Windows development (e.g. what you get with normal Visual Studio installations) does not handle multiple key presses, not including modifier keys (ctrl, alt, and shift.)

To clarify, the .NET Framework doesn't provide automatic handling of multiple key presses. You can still handle them yourself.

The problem is Windows supports two types of key press events: KeyDown/Up and Repeat. Key up and down is great, but if you hold a key down, it fires Repeat until that key is let go. Not handy if you are trying to hold 2 keys down at once.

This is what's keeping your code from working right--when you hold one key down and press another at the same time, you stop getting repeats from the first key, and start getting them from the second.

As long as your game logic is coupled to keyboard event handling, you'll always need a new key event to do something in game logic. Because you never get repeats for more than one key at a time, you won't be able to do two actions at once.

The solution? Decouple keyboard event handling from game logic.

First, you need a place to keep track of which keys are currently down. If you only have a few keys you're interested in, you might have a couple of lines like this:

private bool spaceKeyDown = false;

Then, handle the "key down" event:

private void MainFormKeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode == Keys.Space)
    {
        spaceKeyDown …
gusano79 247 Posting Shark

Simple, yes... but not something I'd allow into production code. See these links for some discussion.

Here's an alternative... first, a method to try to create a mutex unique to the application:

private Mutex GetSingleInstanceMutex()
{
    bool createdNewMutex;

    Mutex mutex = new Mutex(false, @"Global\" + SomethingUnique, out createdNewMutex);

    if (!createdNewMutex)
    {
        mutex = null;
    }

    return mutex;
}

SomethingUnique should be something unique to the application, for example, the assembly GUID.

Here's how you'd use the method:

using (Mutex mutex = GetSingleInstanceMutex())
{
    if (mutex != null)
    {
        // This is the only running instance; go ahead and run the application.
    }
    else
    {
        // Another instance is running; notify user and quit.
    }
}
ddanbe commented: Very informative for a learner like me! +5
gusano79 247 Posting Shark

You can't link directly to a COM library; you have to link to a .NET interop library. The VS IDE secretly generates this library for you when you add a COM project reference. Since you're using the command line, you'll have to generate it yourself. Use tlbimp.exe; it comes with the SDK.

bondo commented: Exactly what I needed +2
gusano79 247 Posting Shark

You can do this by capturing keybord interrupt.(09h?yes)
I remember I have seen an article solving this problem.Actually,it is not
an easy stuff,but Im not sure I can check it out.:~)
...

Correct; hardware interrupt 9h is the keyboard interrupt, and it's possible to use that to get keyboard states. But if you're compiling for Win32, then by all means use the API like bdiamond suggests--it's tougher to write your own int 9 handler, and what you get is something that works just like GetAsyncKeyState anyway.

...
I think I have the same problem with you.Im thinking about reading data
from I/O directly,but I havnt done it yet.

Dealing with the keyboard controller directly like that is a couple of orders of magnitude more insane than writing your own handler, trust me.

If you really want to play with hardware, the old, 16-bit DOS edition of the The Art of Assembly Language Programming has a chapter on the IBM PC keyboard and int 9 handling which I think is quite useful, if you don't mind x86 assembly.

--sg

Asif_NSU commented: useful info, I appreciate--- Asif_NSU +1
gusano79 247 Posting Shark

...
And, about the "&&" operator, yeah, it's true.
If the left hand side is false, it will never evaluate the right hand side
...
this differs in some programming languages.

With some languages, it may depend on the compiler as well. Shortcutting an operation like that can be considered an optimization; I've heard of compilers (can't think of any off the top of my head though) that stop evaluating the expression if the LHS is false when optimizations are turned on, but will evaluate everything when they're turned off... this is especially frustrating when the debug build (optimization off) works fine, but the release build (optimization on) doesn't.

You're save with Java, though; the shortcut is written into the language specification.

--sg

red_evolve commented: Good point. I agree with you. +2
gusano79 247 Posting Shark

...
For the void set how would i set the char mer[] to am or pm.
...

The sprintf function should work for that:

#include <stdio.h>

void Set(char string_time[])
{
    sprintf(meridian, string_time);
}

If you do this with string_time larger than meridian, it will crash and burn horribly.

I recommend that you don't store and manipulate that value as a char array. If it's only going to ever have two distinct values, it's a lot easier to handle if you use a simpler type, like an int, for example. Just decide on a meaning for the simpler variable, e.g. a zero int value means "AM" and nonzero means "PM". If you're writing C++, then a bool is even better--it only has two possible values. The only time you need text is when you're displaying the time for a human being, which can be done in a separate function that interprets the numeric values and prints out the textual meaning. This will make your code simpler and easier to work with.

gusano79 247 Posting Shark

I need to create a date updated field for ms sql 2000. The current trigger I have only works for the insertion of data and it is "(getdate())" is there one that I can use for insertion and update of fields?

You can write a trigger that fires on both insert and update:

CREATE TRIGGER <trigger_name>
ON <table_name>
FOR INSERT, UPDATE
AS
<trigger_body>

Here's the T-SQL reference page:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_create2_7eeq.asp

Slade commented: Thanks, here's your reward :P +36
gusano79 247 Posting Shark

can anyone give me a example of a radix sort

Here's an explanation to complement Abu's code example:

A radix sort works with the digits of a number, working from the least significant digit to the most. Here's a sample set of numbers:
423 586 403 171 92 536 234 243

First, sort the numbers by the least siginificant digit (ones). For this algorithm to work, your buckets have to be order-preserving.
171 92 423 403 243 234 586 536

Then, sort them by the next most significant digit (tens):
403 423 234 536 243 171 586 92

Now hundreds:
92 171 234 243 403 423 536 586

...and they're sorted. Each step doesn't have to be a bucket sort; any order-preserving sort will work.

gusano79 247 Posting Shark
...
Thread th_ciz;
...	
th_ciz=new Thread(this);
...
bt_ciz.addActionListener(new ActionListener(){
	public void actionPerformed(ActionEvent ae){
		th_ciz.start();
	}
});

Try this:

Remove the declaration and definition of th_ciz (first two lines quoted above). Roll it all into the ActionListener:

bt_ciz.addActionListener(new ActionListener(){
	public void actionPerformed(ActionEvent ae){
		(new Thread(this)).start();
	}

Hm, that should work. If the anonymous thread isn't quite right, you can always stash it in a local Thread variable instead.

I think that's what you're asking about... So if all you're doing in the Run method is calling repaint(), is there a good reason you can't do that from the button's handler?