Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Aafter
Apr 14, 2009

A is for After.

Internet Janitor posted:

Aafter: Could you explain why you want to do that? If you want a nestable container for other components you probably want to put a series of JPanels in your JFrame.

I just figured it would be simpler. I initialize the first JFrame in main, the second in my JPanel on button press.

Adbot
ADBOT LOVES YOU

Cubiks
Aug 31, 2005
I wish I had something witty to put here...
So I have a library question for anyone up to the challenge. I'm looking to deserialize a stream of JSON objects coming in over a network connection. I'd like to find a JSON library capable of deserializing these objects, but in a non-blocking fashion: i.e. I feed the library bits of data, and it gives me back complete objects when they're done.

The API I kinda imagine would be similar to this:

code:
String jsonText1 = "{ \"key1\":\"value1\", \"key2-";
String jsonText2 = "broken\":\"value2\" }";

Parser p = new Parser(...);
boolean done = p.parse(jsonText1); // done == false

done = p.parse(jsonText2); // done == true

Object o = p.getResult(); // { "key1":"value1", "key2-broken":"value2" }
Now, the closest I've found is something called async-json-library, but that fails if a token is split between parts, like "key2-broken" in my example.

At this point I'm pretty much resigned to just making something myself, but if there is something that can do this that'd be awesome.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Is there a reason you need to do this drip-feeding instead of, say,

code:
Future<Object> f = p.parseAsync(networkStream);
//do some other stuff
Object o = f.get();
//alternatively hand it off to another thread to do

Cubiks
Aug 31, 2005
I wish I had something witty to put here...

Jabor posted:

Is there a reason you need to do this drip-feeding instead of, say,

code:
Future<Object> f = p.parseAsync(networkStream);
//do some other stuff
Object o = f.get();
//alternatively hand it off to another thread to do

My end goal is to have a single server, many client setup, where creating a thread on the server for each client just wouldn't scale. I'm basically building baby's first networked game, figured I'd use JSON as a transport mechanism because it's fairly easy to understand and I don't care much about the overhead (not much being transmitted anyway).

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Cubiks posted:

My end goal is to have a single server, many client setup, where creating a thread on the server for each client just wouldn't scale.

This is a solved problem. Deal in work items, not threads, and use callbacks instead of synchronous IO.

HFX
Nov 29, 2004

Jabor posted:

This is a solved problem. Deal in work items, not threads, and use callbacks instead of synchronous IO.

Where are these callback mechanisms for non blocking i/o. Specifically, is there a way I could use them with stuff from concurrent and maybe show an example / tutorial?

All the tutorials I looked at seemed rather basic. So I ended up doing what I always do in low level languages, and implemented the items to do them myself. Which is painful of course.

Brain Candy
May 18, 2006

HFX posted:

Where are these callback mechanisms for non blocking i/o. Specifically, is there a way I could use them with stuff from concurrent and maybe show an example / tutorial?

All the tutorials I looked at seemed rather basic. So I ended up doing what I always do in low level languages, and implemented the items to do them myself. Which is painful of course.

Look at http://java.sun.com/developer/technicalArticles/releases/nio/, use the links at the bottom if you need more.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Since NIO was just brought up and I'm an idiot, is there anything wrong with this code? It reads a file into memory.
code:
private ByteBuffer readWorld() throws FileNotFoundException, IOException {
	FileInputStream fis = new FileInputStream(world); // instance File
	FileChannel fc = fis.getChannel();
	ByteBuffer bbuf = ByteBuffer.allocate((int) world.length());
	while (bbuf.hasRemaining())
		fc.read(bbuf);
	fc.close();
	fis.close();
	bbuf.rewind();
	return bbuf;
}
It works, I'm just paranoid I'm doing something wrong and it'll randomly fail or leak resources.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Aleksei Vasiliev posted:

Since NIO was just brought up and I'm an idiot, is there anything wrong with this code? It reads a file into memory.
code:
It works, I'm just paranoid I'm doing something wrong and it'll randomly fail or leak resources.

It should work fine. Though honestly if you're just looking to slurp the whole file into memory there are easier ways:

code:
RandomAccessFile f = new RandomAccessFile(world, "r");
byte[] b = new byte[world.length()];
f.readFully(b);
f.close();
return ByteBuffer.wrap(b);

HFX
Nov 29, 2004

Brain Candy posted:

Look at http://java.sun.com/developer/technicalArticles/releases/nio/, use the links at the bottom if you need more.

Those parts I know and can do well. It appears the features I want are being added in Java 7. That will save me time in the future from having to write callback mechanisms for nio.

crazyfish
Sep 19, 2002

Aleksei Vasiliev posted:

Since NIO was just brought up and I'm an idiot, is there anything wrong with this code? It reads a file into memory.
code:
private ByteBuffer readWorld() throws FileNotFoundException, IOException {
	FileInputStream fis = new FileInputStream(world); // instance File
	FileChannel fc = fis.getChannel();
	ByteBuffer bbuf = ByteBuffer.allocate((int) world.length());
	while (bbuf.hasRemaining())
		fc.read(bbuf);
	fc.close();
	fis.close();
	bbuf.rewind();
	return bbuf;
}
It works, I'm just paranoid I'm doing something wrong and it'll randomly fail or leak resources.


You want to close your resources in a finally block in case read throws an exception.

code:
        FileInputStream fis;
        FileChannel fc;
        try
        {
           fis = new FileInputStream(world); // instance File
	   fc = fis.getChannel();
	   ByteBuffer bbuf = ByteBuffer.allocate((int) world.length());
	   while (bbuf.hasRemaining())
		fc.read(bbuf);
           bbuf.rewind();
	   return bbuf;
	finally
        {
            if (fc != null) 
                fc.close();
	    if (fis != null) 
                fis.close();
        }
Of course you'll probably have to handle the case where fc.close() throws an exception too but I don't feel like writing that out.

epswing
Nov 4, 2003

Soiled Meat

crazyfish posted:

Of course you'll probably have to handle the case where fc.close() throws an exception too but I don't feel like writing that out.

I usually write some sort of static 'silent close' method like...

code:
public class Util {
  public static silentClose(Closeable c) {
    if (c != null) {
      try { c.close(); }
      catch (IOException e) {}
    }
  }
}
...because I often don't care that close() didn't work. I think there's an apache library that contains something similar. So that finally becomes

code:
	finally
        {
            Util.silentClose(fc);
            Util.silentClose(fis);
        }

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I have a similar method for closing SQL connections, statements and result sets.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

epswing posted:

I usually write some sort of static 'silent close' method like...
You can change that to public static silentClose(Closeable... cs) and add a for-loop to save on lines where it's used.

crazyfish posted:

You want to close your resources in a finally block in case read throws an exception.
Thanks! I have trouble with remembering how to properly prevent leaks.
I really want Java 7's try-with-resources thing.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Aleksei Vasiliev posted:

You can change that to public static silentClose(Closeable... cs) and add a for-loop to save on lines where it's used.

What is this called? Everytime I want to google some more information about it, I get stumped because I don't know what to call it.

epswing
Nov 4, 2003

Soiled Meat

Thermopyle posted:

What is this called?

varargs

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Thermopyle posted:

What is this called? Everytime I want to google some more information about it, I get stumped because I don't know what to call it.
You can often find stuff like this by naming the punctuation used.

"java ellipsis" on Google finds varargs, "python asterisk" finds Python's varargs, etc

Now if it doesn't use any symbols then it's a bit harder

Chairman Steve
Mar 9, 2007
Whiter than sour cream

epswing posted:

I think there's an apache library that contains something similar.

IOUtils.

Hidden Under a Hat
May 21, 2003
I just started getting this error when I try to run a program in Netbeans IDE:

Exception in thread "main" java.lang.NoClassDefFoundError: LabRX/GUI
Caused by: java.lang.ClassNotFoundException: LabRX.GUI
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)

I ran this file literally 15 minutes ago and now all of the sudden I get this poo poo. Anyway know how to fix this? The only thing I can think of that may have caused this was I ran the refractor on a field, but that field was only referenced a couple times and it was successfully changed.

Edit: I was able to Clean and Build and run the .jar file, however now when I try to run it in Netbeans I get this:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing method body, or declare abstract
at LabRX.GUI.main(GUI.java:7420)

Edit2: So I found the problem. I had accidentally created an ActionPerformed event from a ComboBox, so I had tried to delete the action but it must have left some actionlistener somewhere, I'm not totally clear on what happened. I fixed it by deleting the combobox entirely then making a new one.

Hidden Under a Hat fucked around with this message at 02:47 on Jun 16, 2011

chippy
Aug 16, 2006

OK I DON'T GET IT
Is there a quick simple way of doing modular subtraction in Java?

For example, if I want an int to go from 0..9 and then "wrap" back to 0 when incremented from 9 it's easy to do with ++i % 10. Is there a quick way of doing it if I want to go the other way, i.e. when i is 0 and is decremented, it goes back to 9?

Obviously there are easy ways of doing it with if statements and the like but I'm looking for a one statement/line solution, more for my own interest than anything.

I'm sure the answer is blindingly obvious but I'm having trouble figuring it out.

chippy fucked around with this message at 13:34 on Jun 16, 2011

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
The simplest approach to your example I can think of would be using the ternary operator: x = (x > 0) ? x-1 : 9;.

Normally when I need to take a modulus I do something like this:
code:
int mod(int a, int b) {
  a %= b;
  return a < 0 ? a+b : a;
}

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

chippy posted:

Is there a quick simple way of doing modular subtraction in Java?

For example, if I want an int to go from 0..9 and then "wrap" back to 0 when incremented from 9 it's easy to do with ++i % 10. Is there a quick way of doing it if I want to go the other way, i.e. when i is 0 and is decremented, it goes back to 9?

Obviously there are easy ways of doing it with if statements and the like but I'm looking for a one statement/line solution, more for my own interest than anything.

I'm sure the answer is blindingly obvious but I'm having trouble figuring it out.

The conditional operator makes if-else logic basically a one-liner:

code:
i = (i > 0) ? i - 1 : 9; 
Alternatively you could use the modulo mechanism by just reversing the direction of the field a couple of times:

code:
i = 9 - (((9 - i) + 1) % 10);

chippy
Aug 16, 2006

OK I DON'T GET IT

Jabor posted:

The conditional operator makes if-else logic basically a one-liner:

code:
i = (i > 0) ? i - 1 : 9; 
Alternatively you could use the modulo mechanism by just reversing the direction of the field a couple of times:

code:
i = 9 - (((9 - i) + 1) % 10);

Thanks, I guess something like the second way was what I was trying to figure out, but I was looking for something nicely elegant and the logic was making my head explode. Looking at that I guess I may as well just use the ternary operator.

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
The ternary operator way to do it would be quite a bit faster, too. Modulus is a pretty long operation for the CPU.

chippy
Aug 16, 2006

OK I DON'T GET IT
Oh cool, I figured the ternary would be slower for some reason.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

Ensign Expendable posted:

The ternary operator way to do it would be quite a bit faster, too. Modulus is a pretty long operation for the CPU.

While your intuition is basically good, I'd be hesitant to choose one over the other without numbers (consider the branch penalty on some hypothetical processor with a fuckoff-huge pipeline)

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
A somewhat philosophical question:

For Maps, why are they both untyped and typed?

e.g. for a Map<String, Integer>, the methods are:
get(Object)
put(String, Integer)
putAll(Map<String, Integer>​)
containsKey(Object)

etc.

Is there some benefit to having Objects instead of typed parameters?

Asking because I have a dumb tendency to accidentally do containsKey with the wrong type.

HFX
Nov 29, 2004

Aleksei Vasiliev posted:

A somewhat philosophical question:

For Maps, why are they both untyped and typed?

e.g. for a Map<String, Integer>, the methods are:
get(Object)
put(String, Integer)
putAll(Map<String, Integer>​)
containsKey(Object)

etc.

Is there some benefit to having Objects instead of typed parameters?

Asking because I have a dumb tendency to accidentally do containsKey with the wrong type.

Because object.equals takes type Object.

Also, consider the case when dealing with super classes of the key type and comparing them. Despite two keys being equal, they would get flagged as an error at compile time because the type is wrong (superclass and not defined class). The second line includes the problem of backwards compatibility.

HFX fucked around with this message at 19:05 on Jun 16, 2011

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Otto Skorzeny posted:

While your intuition is basically good, I'd be hesitant to choose one over the other without numbers (consider the branch penalty on some hypothetical processor with a fuckoff-huge pipeline)

It's deeper than that. The actually interesting questions here are (1) will the optimizer notice that you're using mod just to get wraparound and convert that automatically to control flow and (2) will the code generator be clever enough to do it with a conditional move instead of a branch. The answer to (2) is very likely to be yes, especially if you write it with a ternary.

chippy
Aug 16, 2006

OK I DON'T GET IT
Wow, way over my head. I just really like elegant solutions to things. I used a wraparound in a program I wrote to transpose guitar chords and did a really clumsy job of it with if statements, then I spotted i = ++i % 4 in some code involved with rotating a Tetris piece and it took me ages to figure out what it was actually for. It blew my mind when I realised it was just a really simple way of doing what I'd done with several lines of code. My coding is really clumsy and hacky at the moment but I'm starting a computing degree in October via the Open University and I'm planning to specialise in software engineering so hopefully this will improve matters.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

HFX posted:

Also, consider the case when dealing with super classes of the key type and comparing them. Despite two keys being equal, they would get flagged as an error at compile time because the type is wrong (superclass and not defined class).
Why would you want an instance of a superclass to be equivalent to an instance of a subclass? A canonical implementation of equals() will always return false for such a comparison.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Mustach posted:

Why would you want an instance of a superclass to be equivalent to an instance of a subclass? A canonical implementation of equals() will always return false for such a comparison.

Yes, you would get told "yep, these two objects aren't equal" at runtime when you compared them.

As opposed to you getting a compile error because you're passing a Foo to a method that only accepts a FooImpl.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Mustach posted:

Why would you want an instance of a superclass to be equivalent to an instance of a subclass? A canonical implementation of equals() will always return false for such a comparison.
Except when they don't, for example Lists, Maps, and Sets. Bloch has the view that using instanceof List (or similar) is the proper way to do it.

But I'm not seeing why Object makes sense. A Collection isn't going to accept superclasses of its declared type, only subclasses.
e: I mean, unless you're for some utterly bizarre reason upcasting your keys to Object before you check if they are in the Map, it provides absolutely no benefit, because it will never contain something that isn't of the right type. And if you're doing that then what the gently caress man

And I'm definitely not seeing the "backwards compatibility" issue.

Malloc Voidstar fucked around with this message at 23:44 on Jun 18, 2011

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

Jabor posted:

Yes, you would get told "yep, these two objects aren't equal" at runtime when you compared them.

As opposed to you getting a compile error because you're passing a Foo to a method that only accepts a FooImpl.
If that is a problem for your program, then the method/collection has the wrong type parameter and should be Foo rather than FooImpl.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Part of it is the diagonal inheritance issue with interfaces.

Suppose I have two collections, one containing IFoos and the other containing IBars. Part of the contract of my class is that a given object should only be in one of those sets, even if it implements both interfaces.

Should I go around checking types and casting things myself? Or should we just allow the collection methods to take an Object and if it's not present ... act like it's not present?

What does having looser type constraints on those methods actually cost?

Hidden Under a Hat
May 21, 2003
I have a question regarding using my main class with all the GUI swing components as a superclass, and a subclass which gets information from all the swing components to perform functions. Basically, my main GUI class seems way too big compared to my other classes, because not only does it have all the swing layout component initializations, declarations, and actionperformed methods, is also has all the other methods which manipulate the information I get from doing actions. I basically want to use my main GUI class as a superclass for a new subclass, so the subclass can have access to all the swing components without having to pass them to the class through a constructor. However, since the superclass is the one with the actionPerformed methods, and the subclass has all the other methods that use the information, I run into the problem of trying to call subclass methods from the superclass. What would be the best way to handle this or a better way to design this?

maskenfreiheit
Dec 30, 2004
Edit: Double Post

maskenfreiheit fucked around with this message at 21:33 on Mar 13, 2017

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

GregNorc posted:

What's a good library to create a 3D histogram?

(I realize Python is probably the better choice, but I'm starting a gig as an android developer so I want to brush up on my java by making a couple small toy apps)

http://www.jfree.org/jfreechart/

e: Doesn't look to be active anymore, might be better stuff out there now but JFreeChart is pretty good. I use to abuse the hell out of it for some charting things.

Zewle
Aug 12, 2005
Delaware Defense Force Janitor
How do I add an object to an array inside an object?

Adbot
ADBOT LOVES YOU

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
code:
class Stuff {
	public Object[] things = new Object[1];
}

...

Stuff blah = new Stuff();
blah.things[0] = new Object();
:confused:

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply