 |
 |
Index ‹ java-programmer
|
- Previous
- 1
- implicit <? super T> when an array is a parameter in a generic methodi'm making some adjustments to previous code to utilize generics in java
1.5 or 5.0 or whatever it is called. something seems inconsistent,
though:
let us say i have a method that operates on two collections:
public <T> void testMethod(Collection<T> c1, Collection<T> c2){...}
if i call this method with the following line, a compile-time error
occurs:
testMethod(new HashSet<Integer>(), new HashSet<Number>());
and rightly so. in this case T != T (i.e. Integer != Number).
the method would have to be rewritten to:
public <T> void testMethod(Collection<T> c1, Collection<? super T>
c2){...}
and this indeed works. this is fine and quite logical.
now the problem. let us assume i have a method that copies elements
from an array into a collection:
public <T> void testMethod(T[] a, Collection<T> c){...}
suddenly i'm allowed to call this method with T != T, as in:
testMethod(new Integer[100], new HashSet<Number>());
the official word from sun is: "it will generally infer the most
specific type argument that will make the call type-correct." apparently this
line is only in reference to arrays (although they don't mention that).
so when this "inferring" occurs, is there basically a re-writing going
on the background that equates to changing the function to:
public <T> void testMethod(T[] a, Collection<? super T> c){...}
?
i guess the true root of the question is, which of the parameters (and
indeed there may be many) will be going through the inferring process?
there must be at least one "baseline" argument type parameter in calls
like these that remains fixed (i.e. cannot go through an inferring
process), because otherwise every type argument could just be inferred to be
Object, making all calls legit and ruining the advantage of generics.
wow, that may have been a bit confusing, but if anyone would point me to
a general good source on java's version of generics (not sun's
documents, as i've already tried to read those and they don't clear up this
confusion at all), it would be greatly appreciated.
thanks,
murat
- 6
- how do I use String's format? not working on XPimport java.lang.String;
...
public void paint(Graphics g) {
Graphics2D comp2d = (Graphics2D)g;
Dimension appletSize = this.getSize();
appletsize_x = appletSize.width;
appletsize_y = appletSize.height;
String sx=String.format("%d", appletsize_x);
String sy=String.format("%d", appletsize_y);
g.drawString(sx, 200,30);
g.drawString(sy, 200,60);
g.setColor(Color.red);
g.fillOval(x_pos - radius, y_pos - radius, 2*radius, 2*radius);
}
...
}
ballapplet.java:101: cannot resolve symbol
symbol : method format (java.lang.String,int)
location: class java.lang.String
String sx=String.format("%d", appletsize_x);
^
ballapplet.java:102: cannot resolve symbol
symbol : method format (java.lang.String,int)
location: class java.lang.String
String sy=String.format("%d", appletsize_y);
^
2 errors
--
------------------------------------
Jim Michaels
for email, edit the address
RAM Disk is *not* an installation method.
- 6
- this is a known bug (bug_id=6263423)
Hi,
after some research in the bug database i found that this is a
known bug with the print margins.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6263423
It seems that it doesnt matter whether one uses the native page
setup dialog (PrinterJob.pageDialog(PageFormat)) or whether
one uses the cross-platform Java page setup dialog
(PrinterJob.pageDialog(PrintRequestAttributeSet)).
Now i dont use a page setup dialog anymore, and use fix margins.
:)
regards
Oliver
- 6
- Where did Castor go?The www.castor.org project seems to be gone. I loved this XML-Java
binding framework and I am wondering if anyone are aware of what has
happened to it?!
Thanks,
Casper
- 6
- 6
- Applet Issues!!Hey, Im Attempting to create an applet that will open a connection to my
application server, the application server WILL be on the same machine
that the applet will be loaded from, i.e. the app server is on the same
machine as the web server. here is my code (sorry for the bad standards)
public class ClientConference extends Applet {
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String chatServer;
private Socket client;
//----------------------------------------------------------------------//
public ClientConference( String host ) {
chatServer = host;
ClientConference application;
application = new ClientConference( "149.153.130.2" );
application.runClient();
}
//----------------------------------------------------------------------//
private void runClient() {
try {
connectToServer(); // Step 1: Create a Socket to make connection
getStreams(); // Step 2: Get the input and output streams
processConnection(); // Step 3: Process connection
}
// server closed connection
catch ( EOFException eofException ) {
System.err.println( "Client terminated connection" );
}
// process problems communicating with server
catch ( IOException ioException ) {
ioException.printStackTrace();
}
finally {
closeConnection(); // Step 4: Close connection
}
} // end method runClient
//----------------------------------------------------------------------//
private void connectToServer() throws IOException{
client = new Socket( InetAddress.getByName(chatServer), 8000 );
}
//----------------------------------------------------------------------//
private void getStreams() throws IOException{
output = new ObjectOutputStream( client.getOutputStream() );
output.flush();
input = new ObjectInputStream( client.getInputStream() );
output.writeObject( "Client Connected" );
output.flush();
}
//----------------------------------------------------------------------//
private void processConnection() throws IOException{
do { // process messages sent from server
// read message and display it
try {
message = ( String ) input.readObject();
}
catch ( ClassNotFoundException classNotFoundException ) { }
} while ( !message.equals( "TERMINATE" ) );
}
//----------------------------------------------------------------------//
private void closeConnection(){
try {
output.close();
input.close();
client.close();
}
catch( IOException ioException ) {
ioException.printStackTrace();
}
}
//----------------------------------------------------------------------//
private void sendData( String message )
{
// send object to server
try {
output.writeObject( "CLIENT>>> " + message );
output.flush();
}
// process problems sending object
catch ( IOException ioException ) { }
}
//----------------------------------------------------------------------//
} // end class Client
If anyone could even hasard a guess at the issue I would appreceate it,
also here is output from the java console if its anyhelp.
load: ClientConference.class can't be instantiated.
java.lang.InstantiationException: ClientConference
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.plugin.AppletViewer.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Thanks in advance I really appreceate any help
Niall
- 6
- Hibernate and Date objectsHi everyone,
I'm having a frustrating time working with Date objects and Hibernate
with an Oracle database.
I have a Patient class containing a Date field (java.util.Date)
and the mapping in the hbm.xml file:
<property name="regDate" type="date">
<column name="REGISTRATION_DATE" />
</property>
When I try and commit a new object to the database, I get a
ClassCastException with the following backtrace:
java.lang.ClassCastException
at
net.sf.hibernate.type.TimestampType.deepCopyNotNull(TimestampType.java:63)
at
net.sf.hibernate.type.NullableType.deepCopy(NullableType.java:96)
at net.sf.hibernate.type.TypeFactory.deepCopy(TypeFactory.java:212)
at net.sf.hibernate.impl.SessionImpl.doSave(SessionImpl.java:935)
at net.sf.hibernate.impl.SessionImpl.doSave(SessionImpl.java:866)
at
net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:788)
at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:747)
at com.sleep.PatientHandler.doPost(PatientHandler.java:96)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:825)
at
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:731)
at
org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:526)
at
org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at
org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:534)
Is this something to do with casting (and failing) an java.sql.Date to a
java.util.Date or something similar?
If anyone can shed any light on this, or has had a similar problem, it
would be greatly appreciated!
Cheers,
Chris.
- 6
- SwingUtilities.getRoot() in a javax.swing.ActionAfter reading
http://www.exampledepot.com/egs/javax.swing/frame_FrameFind.html
I wrote a small test program in which I found that
SwingUtilities.getRoot() returns null. getRoot() works well for me in
other programs when I feed it a container (e.g. JPanel).
What am I doing wrong? Cannot SwingUtilities trace the JFrame to which
the JMenuItems are ultimately attached? Why not?
------------------------------------8<-------------------------------
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class EnumAction {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EnumAction();
}
});
}
EnumAction() {
JMenu m = new JMenu("Menu");
for (Command c : Command.values())
m.add(new JMenuItem(c.action));
JMenuBar mb = new JMenuBar();
mb.add(m);
JPanel p = new JPanel();
p.add(new JLabel("EnumAction"));
JFrame f = new JFrame("EnumAction");
f.setJMenuBar(mb);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
enum Command {
CMD_THIS("This"), CMD_THAT("That");
Action action;
Command(final String label) {
action = new AbstractAction() {
{
putValue(Action.ACTION_COMMAND_KEY, name());
putValue(Action.NAME, label);
}
public void actionPerformed(ActionEvent event) {
System.out.println(event.getActionCommand());
Object o = event.getSource();
if (o instanceof JMenuItem) {
Component c = SwingUtilities.getRoot((JMenuItem)o);
System.out.println("Root: "+c);
}
}
};
}
}
------------------------------------8<-------------------------------
- 7
- squeezing the use of memoryHi,
Qick question about the use of int Vs. the use of short,char,byte
in 'for' loops. Will it affect the memory utilization/performance at all ?
If yes, to what extent, especially considering a program which uses
looping extensively and doesn't need the entire 'int' range.
Generally people just go ahead and use 'int' in loops...
Awaiting your thoughts,
Asif
- 11
- [iText] template or watermarkHi,
I remember that with iText it is possible to use an existing PDF
document als template or "background image" for a new PDF document. IIRC
it could be done using some watermark- or template-functions?
(Unfortunately, the old documentation has ben abandoned...)
Anyway, I've got a document, and I could add a template to its
PdfContentByte. Furthermore, I have a PDFReader with which I've read the
existing document. But I don't know, how to get a template from the reader.
Or can this only be solved in a completely differnt way?
Ciao,
Ingo
- 11
- SAX: continue parsing in included file(s)Currently I use <include>foo.xml</include> [1] in order to include foo.xml
into bar.xml (for example). Since I am moving the parsing to Java, using
SAX I was wondering what the best way is to implement this feature. How do
I "redirect" the reading to another file via a handler?
IIRC, another option might be to use &foo; [2] and include the file that
way, possible combined with a SAX filter to translate <include>foo.xml
</include> into &foo; ?
Any suggestions?
[1] I used in the past a parser (not with Java) that as far as I know was
not able to handle this:
[2] <!ENTITY foo SYSTEM "foo.xml"> , see
http://xml.silmaril.ie/authors/includes/
--
John MexIT: http://johnbokma.com/mexit/
personal page: http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
- 12
- synchronized confusion!hi all!
If a method is synchronized like this:
public synchronized void broadcast (String message) {
I have like 10 threads calling the broadcast method.
What happens to all threads calling this method?
Does the threads halt/wait and line up in a qeueue??
Is it like when one use the Wait-notify system or what.
Does the threads stop what they are doing when they
try to get access to the synchronized method and the method
is locked.
I know that when I use the wait() it will put
thread's in the Wait mode. I can then do a notify/all
and the waiting threds will continue. This is easy to
understand. But the synchronized is not like that I guess
Hope you understand what I mean!
- 12
- Creating a pop-up messageIs there a way to have a text file or an excel file and in it list
dates and a message, then having my web page reference that file and
pop up with the message if the current date matches a date in my file.
- 15
- Wholesale Swiss Rolex Oyster Perpetual DateJust White Gold-ss Men's Watches SRX024 Discount, Fake WatchWholesale Swiss Rolex Oyster Perpetual DateJust White Gold-ss Men's
Watches SRX024 Discount, Fake Watch
Wholesale Watches at www.watchec.com
Browse our Swiss Rolex Oyster Perpetual DateJust White Gold-ss Men's
Watches fake watch, which is sure the watch you are looking for at low
price. There are more high quality designer watch replicas for
selection
Swiss Rolex Oyster Perpetual DateJust White Gold-ss Men's Watches
SRX024 Link :
http://www.watchec.com/swiss-rolex-datejust-replica-watches-srx024.html
Model : SRX024
Description : 100% Genuine Replica Swiss Rolex Watches,
Sale Price : $ 319.00
Swiss Rolex Oyster Perpetual DateJust White Gold-ss Men's Watches
SRX024 Details :
Automatic movement
Hack mechanism (second hand stops when crown is pulled out to set the
time ?standard feature on all genuine Rolex watches)
Sapphire crystal watchglass
Screws in the links, not pins
Rubber seal at trip-lock winding crown
Serial band/number on last link/lugs
Standard Jubilee-band clasp, with serial number and steelinox markings
on clasp
Full Stainless Steel band/case, and will never fade or wear
Solid back with characteristic Rolex green sticker
Screw-in watch crown
All the appropriate Rolex markings in the correct places
We are leading supplier of Wholesale watches including rolex watches,
rolex submariner, rolex daytona, rolex thunderbird, rolex tudor, rolex
oyster, rolex yacht master, swiss pendant watch, rolex sea dweller and
rolex air king etc. We are specialized fashion Watches wholesaler.
If you are looking for the well know brand watch and information about
it, you came to the right place. Here you can find such fine you I top
brand-name watches as Well know brand Rolex Watches, Well know brand
Alain Silberstein Watch,Fake A.Lange & Sohne watch,Well know brand
Audemars Piguet Watches, Baume & Mercier watches, Replica Jacob & Co
watches, well know brand Breitling watches, Well know brand Breguet
watch, Bvlgari, Jaeger leCoultre, and other.
Man watch is the most important accessory a man can own - it is an
essential style element. Well know brand watches are invented for the
people who want to look good, to impress everybody, but they don't
have so much money to buy original expensive watch. Our well know
brand watches are well known for their impeccable quality, the
precision engineering of the watches. Nobody will ever know that it is
not real. Also, it is a very good, pleasant and not expensive present
for your friend, father, husband, wife or any other close person,
witch will serve for many years. This great present will remind about
you to your close man every time. If you are looking for luxury, the
latest watch technology and excellent design take a look at our
collection of well know brand watches.
If you have any other questions please check our other pages or feel
free to email us by email***@***.com
Wholesale Swiss Rolex Oyster Perpetual DateJust White Gold-ss Men's
Watches SRX024 Discount, Fake Watch
- 15
- void method? Hello,
I am not sure were to put the return, i want to return the sum of the 3
digits, but it gives me an error becouse, it expect a void method
Irlan
public static void main(String[] args) {
//declareer getal
long getal = 456;
//invoke method
Sumdigits(getal);
}
//method declaration
public static int Sumdigits(long n){
int num2 = (int)n % 10;
int num1 = (int)n / 10;
int num0 = (int)num1 % 10;
int num100 = (int)n / 100;
return
System.out.println("de sum is" +num2+ "+" + num0 + "+" +num100);
}
}
|
| Author |
Message |
Kenneth P. Turvey

|
Posted: 2005-10-8 7:38:00 |
Top |
java-programmer, Binomial Simulation
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
I'm taking a class in Evolutionary Computation. I just turned in an
assignment that implements a simple genetic algorithm based on bit
strings. For mutation I simply check each bit in the population and
flip it with some constant probability. For a population of 10,000
individuals of 100 bits that means that I have to execute the method
Random.nextDouble() 1,000,000 times. I thought about this a bit and I
could do the same operation by getting a single value from a binomial
distribution and then selecting that number of bits at random. This
would require far fewer operations that the current brute force method.
For real problems this might not matter that much since mutation would
take a small percentage of the time spent in the algorithm, but for my
test problems mutation is the biggest contributor to run time.
So, now to the question. Is there an open source implementation of
nextBinomial() out there somewhere? I did a quick search of the web and
didn't find one. I could implement my own, but it probably wouldn't be
as fast as a widely used open source implementation and I don't want to
spend the time on something that is really a library function if I don't
have to.
Note that I'm not trying to cheat here. If I end up using it in an
assignment I will credit the author and the prof won't mind. This is a
graduate course.
Thank you.
- --
Kenneth P. Turvey <email***@***.com>
http://kt.squeakydolphin.com (not much there yet)
Jabber IM: email***@***.com
Phone: (314) 255-2199
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
iD8DBQFDRwbHi2ZgbrTULjoRAkxhAJsEm9g5EfvsY9P7bnE9E3czsTgsDQCg9Glz
pS2dmdxSYVmjUcfpFpUSt9A=
=vcUC
-----END PGP SIGNATURE-----
|
| |
|
| |
 |
zero

|
Posted: 2005-10-8 10:04:00 |
Top |
java-programmer >> Binomial Simulation
"Kenneth P. Turvey" <email***@***.com> wrote in
news:email***@***.com:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> I'm taking a class in Evolutionary Computation. I just turned in an
> assignment that implements a simple genetic algorithm based on bit
> strings. For mutation I simply check each bit in the population and
> flip it with some constant probability. For a population of 10,000
> individuals of 100 bits that means that I have to execute the method
> Random.nextDouble() 1,000,000 times. I thought about this a bit and I
> could do the same operation by getting a single value from a binomial
> distribution and then selecting that number of bits at random. This
> would require far fewer operations that the current brute force method.
> For real problems this might not matter that much since mutation would
> take a small percentage of the time spent in the algorithm, but for my
> test problems mutation is the biggest contributor to run time.
I'm not sure I understand all of this. Why would you need 1,000,000 random
values? Can't you do something like this:
for each individual
if nextDouble < probability
pick a random bit and flip it
here you would only need 10,000 random values + a fraction defined by the
probability, and not a value per bit for each of the individuals.
Typically the probability is very low, so you wouldn't have much more
random values than there are individuals in the population.
Feel free to poke fun at me if I'm missing the whole point here.
|
| |
|
| |
 |
Kenneth P. Turvey

|
Posted: 2005-10-8 10:46:00 |
Top |
java-programmer >> Binomial Simulation
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Sat, 08 Oct 2005 02:04:10 +0000, zero wrote:
> I'm not sure I understand all of this. Why would you need 1,000,000
> random values? Can't you do something like this:
>
> for each individual
> if nextDouble < probability
> pick a random bit and flip it
This works as a form of mutation, but it isn't equivalent to randomly
flipping each bit with a given probability. Using this a given
individual will only have a maximum of a single bit flip.
> here you would only need 10,000 random values + a fraction defined by
> the
> probability, and not a value per bit for each of the individuals.
> Typically the probability is very low, so you wouldn't have much more
> random values than there are individuals in the population.
It works, and it is certainly faster, but it isn't really the same
algorithm, and for some problems it would never help you toward a
solution. What if you really need two or three consecutive bit flips to
move you closer to the optimum. This could never happen using your
algorithm.
> Feel free to poke fun at me if I'm missing the whole point here.
No, you're not. It just isn't quite what I need.
I've looked around on the web quite a bit and I haven't found anything.
I think I'm going to take the easy way out and implement it by
approximation using a normal distribution unless np and n(1-p) are less
than 5 in which case I will do it the long way, by actually pulling out
n random numbers and checking.
I hope that somebody has a better way. At least it doesn't take long to
implement.
- --
Kenneth P. Turvey <email***@***.com>
http://kt.squeakydolphin.com (not much there yet)
Jabber IM: email***@***.com
Phone: (314) 255-2199
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
iD8DBQFDRzLci2ZgbrTULjoRAgGjAJ40SkmhSIgyckutJt1ELZNaZn2/iwCgnp1R
Nk3Qg7z3OqK1SRmPkwn+5nw=
=S8+J
-----END PGP SIGNATURE-----
|
| |
|
| |
 |
Googmeister

|
Posted: 2005-10-8 10:55:00 |
Top |
java-programmer >> Binomial Simulation
Kenneth P. Turvey wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> I'm taking a class in Evolutionary Computation. I just turned in an
> assignment that implements a simple genetic algorithm based on bit
> strings. For mutation I simply check each bit in the population and
> flip it with some constant probability. For a population of 10,000
> individuals of 100 bits that means that I have to execute the method
> Random.nextDouble() 1,000,000 times. I thought about this a bit and I
> could do the same operation by getting a single value from a binomial
> distribution and then selecting that number of bits at random. This
> would require far fewer operations that the current brute force method.
> For real problems this might not matter that much since mutation would
> take a small percentage of the time spent in the algorithm, but for my
> test problems mutation is the biggest contributor to run time.
Here's my understanding of your problem: given N bits, flip each
one independently with probability p, where p is some small constant.
Here's how I would approach it. Repeatedly use Geometric(p)
random variable to determine the number of bits to skip before
choosing one to flip. That is, if X_i are random geometric
random variables, then flip bits X_1, X_1 + X_2, X_1 + X_2 + X_3,
and so on. Now, each bit gets flipped with probability p,
and the memoryless property of the geometric distribution
ensures that everything is independent.
To generate a Geometric(p) variable , use
X_i = ceil(ln U / ln (1 - p)), where U is uniformly between
0 and 1. Obviously, precompute ln (1-p). Assuming p is
very small, this will be substantially more efficient than
the brute force approach.
|
| |
|
| |
 |
Kenneth P. Turvey

|
Posted: 2005-10-8 12:47:00 |
Top |
java-programmer >> Binomial Simulation
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Fri, 07 Oct 2005 19:55:19 -0700, Googmeister wrote:
> Here's my understanding of your problem: given N bits, flip each
> one independently with probability p, where p is some small constant.
>
> Here's how I would approach it. Repeatedly use Geometric(p)
> random variable to determine the number of bits to skip before
> choosing one to flip. That is, if X_i are random geometric
> random variables, then flip bits X_1, X_1 + X_2, X_1 + X_2 + X_3,
> and so on. Now, each bit gets flipped with probability p,
> and the memoryless property of the geometric distribution
> ensures that everything is independent.
That works. Now for cases where n p > 5 and n (1-p) > 5 I
can use a normal approximation and then select which bits to
flip at random. I don't know which of these two methods would
be faster. It looks like we would need the same number of
random variables roughly.
For cases where n*p < 5 or n*(1-p) < 5 then I'm looking at a very
small number of cases.
Looking at this closer, there really isn't any need to worry
about those cases I can't approximate as normal. I'm never going
to have a case where it can't be approximated. I was thinking of
n as the number of individuals in the population, but it is really
the total number of bits in the population.
Thanks for your help. I think I'll test it out the way I've
already written the nextBinomial() method and if it is too
slow, I'll try it your way.
- --
Kenneth P. Turvey <email***@***.com>
http://kt.squeakydolphin.com (not much there yet)
Jabber IM: email***@***.com
Phone: (314) 255-2199
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
iD8DBQFDR09Ci2ZgbrTULjoRAsi8AKDhMkTbP6wG2Ax6rBugDoRBFqP33ACgjtaY
DgfrD93vqY/bbACeGAbwnr0=
=cD39
-----END PGP SIGNATURE-----
|
| |
|
| |
 |
Roedy Green

|
Posted: 2005-10-8 13:51:00 |
Top |
java-programmer >> Binomial Simulation
On Fri, 07 Oct 2005 18:37:57 -0500, "Kenneth P. Turvey"
<email***@***.com> wrote or quoted :
>I'm taking a class in Evolutionary Computation. I just turned in an
>assignment that implements a simple genetic algorithm based on bit
>strings. For mutation I simply check each bit in the population and
>flip it with some constant probability. For a population of 10,000
>individuals of 100 bits that means that I have to execute the method
>Random.nextDouble() 1,000,000 times. I thought about this a bit and I
>could do the same operation by getting a single value from a binomial
>distribution and then selecting that number of bits at random. This
>would require far fewer operations that the current brute force method.
>For real problems this might not matter that much since mutation would
>take a small percentage of the time spent in the algorithm, but for my
>test problems mutation is the biggest contributor to run time.
You want a bell shaped distribution, that similar to nextGaussian but
is actually a binomial. It seems to me for large n you can
approximate the binomial with a continuous function. Intuitively, I
think what you do is take the derivative of that bell shaped curve and
invert it - exchange y and x. That becomes your warping function. You
put your random 0..1 into it to get a warped random. The curve you
want is like an S lying on its side, with an arm swooping down on the
left and up on the right. It tends to move the numbers around .5 to
the mean .5 with very few near the ends mapping to numbers near 0 or
1.
If you can't solve it analytically, perhaps you can at least get the
shape of that curve through numerical methods. Then you warp your
random number to determine how many genes flipped by a table lookup
and interpolation.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
|
| |
|
| |
 |
Roedy Green

|
Posted: 2005-10-8 16:21:00 |
Top |
java-programmer >> Binomial Simulation
On Fri, 07 Oct 2005 23:47:06 -0500, "Kenneth P. Turvey"
<email***@***.com> wrote or quoted :
>Thanks for your help. I think I'll test it out the way I've
>already written the nextBinomial() method and if it is too
>slow, I'll try it your way.
it would be interesting to hear back on a speed comparison.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
|
| |
|
| |
 |
Chris Uppal

|
Posted: 2005-10-8 18:14:00 |
Top |
java-programmer >> Binomial Simulation
Kenneth P. Turvey wrote:
> For mutation I simply check each bit in the population and
> flip it with some constant probability. For a population of 10,000
> individuals of 100 bits that means that I have to execute the method
> Random.nextDouble() 1,000,000 times. I thought about this a bit and I
> could do the same operation by getting a single value from a binomial
> distribution and then selecting that number of bits at random.
Do you actually need that level of statistical integrity for this application ?
It seems to me (sitting here, far away from you prof ;-) that you'd probably
get very similar results by just choosing 100*p bits (randomly) and flipping
them. Or, if that's /too/ crude, approximate it with a normal distribution ?
(Actually, it might be more interesting to try all three to see what quantitive
differences, if any, different approximations make...)
-- chris
|
| |
|
| |
 |
Wibble

|
Posted: 2005-10-8 20:04:00 |
Top |
java-programmer >> Binomial Simulation
Chris Uppal wrote:
> Kenneth P. Turvey wrote:
>
>
>> For mutation I simply check each bit in the population and
>>flip it with some constant probability. For a population of 10,000
>>individuals of 100 bits that means that I have to execute the method
>>Random.nextDouble() 1,000,000 times. I thought about this a bit and I
>>could do the same operation by getting a single value from a binomial
>>distribution and then selecting that number of bits at random.
>
>
> Do you actually need that level of statistical integrity for this application ?
> It seems to me (sitting here, far away from you prof ;-) that you'd probably
> get very similar results by just choosing 100*p bits (randomly) and flipping
> them. Or, if that's /too/ crude, approximate it with a normal distribution ?
> (Actually, it might be more interesting to try all three to see what quantitive
> differences, if any, different approximations make...)
>
> -- chris
>
>
You could treat your random as a bitmask.
hashToWidth(100, random(2^100)*probalilty)
and then just xor that with your bit population.
That would require only 10000 randoms, if you had 100 bit numbers.
Chop that into batches of 32 for 100*10000/32 randoms for 32 bit integers.
Theres some loss in statistical integrity since a given random will
hash to the same bitmap in its range, but it should be fast.
|
| |
|
| |
 |
Googmeister

|
Posted: 2005-10-8 20:26:00 |
Top |
java-programmer >> Binomial Simulation
Kenneth P. Turvey wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> On Fri, 07 Oct 2005 19:55:19 -0700, Googmeister wrote:
>
> > Here's my understanding of your problem: given N bits, flip each
> > one independently with probability p, where p is some small constant.
> >
> > Here's how I would approach it. Repeatedly use Geometric(p)
> > random variable to determine the number of bits to skip before
> > choosing one to flip. That is, if X_i are random geometric
> > random variables, then flip bits X_1, X_1 + X_2, X_1 + X_2 + X_3,
> > and so on. Now, each bit gets flipped with probability p,
> > and the memoryless property of the geometric distribution
> > ensures that everything is independent.
>
> That works. Now for cases where n p > 5 and n (1-p) > 5 I
> can use a normal approximation and then select which bits to
> flip at random. I don't know which of these two methods would
> be faster. It looks like we would need the same number of
> random variables roughly.
I strongly suspect the Binomial approach (where you approximate
the Binomial with a Normal or Poisson) will be faster than the
Geometric approach I proposed since you only need a couple of
transcendental function calls instead one per bit flipped. The
advantage of the Geometric approach is that it samples from
the exact distribution (up to the randomness of random()). As
others have pointed out, such an approximation probably won't
make any difference in your application as long as np is sufficiently
large.
|
| |
|
| |
 |
Wibble

|
Posted: 2005-10-8 21:07:00 |
Top |
java-programmer >> Binomial Simulation
Wibble wrote:
> Chris Uppal wrote:
>
>> Kenneth P. Turvey wrote:
>>
>>
>>> For mutation I simply check each bit in the population and
>>> flip it with some constant probability. For a population of 10,000
>>> individuals of 100 bits that means that I have to execute the method
>>> Random.nextDouble() 1,000,000 times. I thought about this a bit and I
>>> could do the same operation by getting a single value from a binomial
>>> distribution and then selecting that number of bits at random.
>>
>>
>>
>> Do you actually need that level of statistical integrity for this
>> application ?
>> It seems to me (sitting here, far away from you prof ;-) that you'd
>> probably
>> get very similar results by just choosing 100*p bits (randomly) and
>> flipping
>> them. Or, if that's /too/ crude, approximate it with a normal
>> distribution ?
>> (Actually, it might be more interesting to try all three to see what
>> quantitive
>> differences, if any, different approximations make...)
>>
>> -- chris
>>
>>
> You could treat your random as a bitmask.
>
> hashToWidth(100, random(2^100)*probalilty)
>
> and then just xor that with your bit population.
>
> That would require only 10000 randoms, if you had 100 bit numbers.
> Chop that into batches of 32 for 100*10000/32 randoms for 32 bit integers.
>
> Theres some loss in statistical integrity since a given random will
> hash to the same bitmap in its range, but it should be fast.
>
I couldn't resist
public final class Bits {
/* untested */
private final static int BITS_PER_WORD = 32;
private final java.util.Random r_ = new java.util.Random();
private final java.util.Random h_ = new java.util.Random();
private final float probability_;
private int bits_ = 0;
private int avail_ = 0;
public Bits(float probability) { probability_ = probability; }
public final int nextBits(int count) {
if (count<=0 || count>BITS_PER_WORD)
throw new IllegalArgumentException();
if (avail_==0) {
final int r = (int)(r_.nextInt() * probability_);
h_.setSeed(r);
bits_ = h_.nextInt();
avail_ = BITS_PER_WORD;
}
final int use = avail_<count ? avail_ : count;
final int bits = bits_ & ((1<<use)-1);
bits_ >>= use;
avail_ -= use;
return(count==use ? bits : (bits<<count)|nextBits(count-use));
}
public static void main(String argv[]) {
final int[][] population = new int[10000][];
for(int i=0;i<10000;++i) population[i] = new int[4];
final Bits b = new Bits(0.2F/*probability*/);
for(int i=0;i<10000;++i) // process population
for(int j=0;j<4;++j) // process 100 bits
population[i][j] ^= b.nextBits(j<3 ? 32 : 4);
}
}
|
| |
|
| |
 |
Wibble

|
Posted: 2005-10-8 21:19:00 |
Top |
java-programmer >> Binomial Simulation
Wibble wrote:
> Wibble wrote:
>
>> Chris Uppal wrote:
>>
>>> Kenneth P. Turvey wrote:
>>>
>>>
>>>> For mutation I simply check each bit in the population and
>>>> flip it with some constant probability. For a population of 10,000
>>>> individuals of 100 bits that means that I have to execute the method
>>>> Random.nextDouble() 1,000,000 times. I thought about this a bit and I
>>>> could do the same operation by getting a single value from a binomial
>>>> distribution and then selecting that number of bits at random.
>>>
>>>
>>>
>>>
>>> Do you actually need that level of statistical integrity for this
>>> application ?
>>> It seems to me (sitting here, far away from you prof ;-) that you'd
>>> probably
>>> get very similar results by just choosing 100*p bits (randomly) and
>>> flipping
>>> them. Or, if that's /too/ crude, approximate it with a normal
>>> distribution ?
>>> (Actually, it might be more interesting to try all three to see what
>>> quantitive
>>> differences, if any, different approximations make...)
>>>
>>> -- chris
>>>
>>>
>> You could treat your random as a bitmask.
>>
>> hashToWidth(100, random(2^100)*probalilty)
>>
>> and then just xor that with your bit population.
>>
>> That would require only 10000 randoms, if you had 100 bit numbers.
>> Chop that into batches of 32 for 100*10000/32 randoms for 32 bit
>> integers.
>>
>> Theres some loss in statistical integrity since a given random will
>> hash to the same bitmap in its range, but it should be fast.
>>
> I couldn't resist
>
> public final class Bits {
> /* untested */
> private final static int BITS_PER_WORD = 32;
> private final java.util.Random r_ = new java.util.Random();
> private final java.util.Random h_ = new java.util.Random();
> private final float probability_;
> private int bits_ = 0;
> private int avail_ = 0;
> public Bits(float probability) { probability_ = probability; }
>
> public final int nextBits(int count) {
> if (count<=0 || count>BITS_PER_WORD)
> throw new IllegalArgumentException();
> if (avail_==0) {
> final int r = (int)(r_.nextInt() * probability_);
> h_.setSeed(r);
> bits_ = h_.nextInt();
> avail_ = BITS_PER_WORD;
> }
> final int use = avail_<count ? avail_ : count;
> final int bits = bits_ & ((1<<use)-1);
> bits_ >>= use;
> avail_ -= use;
> return(count==use ? bits : (bits<<count)|nextBits(count-use));
> }
> public static void main(String argv[]) {
> final int[][] population = new int[10000][];
> for(int i=0;i<10000;++i) population[i] = new int[4];
> final Bits b = new Bits(0.2F/*probability*/);
> for(int i=0;i<10000;++i) // process population
> for(int j=0;j<4;++j) // process 100 bits
> population[i][j] ^= b.nextBits(j<3 ? 32 : 4);
> }
> }
oops should be
return(count==use ? bits(bits<<use/*NotCount*/)|nextBits(count-use));
|
| |
|
| |
 |
Kenneth P. Turvey

|
Posted: 2005-10-9 0:09:00 |
Top |
java-programmer >> Binomial Simulation
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Sat, 08 Oct 2005 05:25:58 -0700, Googmeister wrote:
> I strongly suspect the Binomial approach (where you approximate
> the Binomial with a Normal or Poisson) will be faster than the
> Geometric approach I proposed since you only need a couple of
> transcendental function calls instead one per bit flipped. The
> advantage of the Geometric approach is that it samples from
> the exact distribution (up to the randomness of random()). As
> others have pointed out, such an approximation probably won't
> make any difference in your application as long as np is sufficiently
> large.
I looked at it closer and np doesn't really have to be very big at all.
For my purposes if I use a population of over five individuals I'm
there. This will always be the case. Since others have posted code,
I'll post mine. I doubt anyone will need this, and it isn't clean, but
it passes my tests.
- --
Kenneth P. Turvey <email***@***.com>
http://kt.squeakydolphin.com (not much there yet)
Jabber IM: email***@***.com
Phone: (314) 255-2199
/**
* The following code has been granted to the public by the author. It
* is not covered by copyright and you have the right to do with it as
* you please.
*/
import java.util.Random;
/**
* This class implements a random number generator with some features that the
* standard Java random number generator doesn't have.
*
* @author Kenneth P. Turvey
* @version $Revision: 293 $
*/
public class ExtendedRandom extends Random {
/** Creates a new instance of ExtendedRandom */
public ExtendedRandom() {
super();
}
public ExtendedRandom(long seed) {
super(seed);
}
/**
* Returns the number of successful trials from a series of Bernouli trials
* each with the given probability.
*
* @probability the probability of each Bernouli trial.
* @trials the number of trials executed.
* @return the number of successful Bernouli trials.
*/
public int nextBinomial(int trials, double probability) {
if (trials * probability < 5.0
|| trials * (1.0 - probability) < 5.0) {
// Not enough trials for a normal approximation.
// Special case of probablity = 1/2.
// This might take less time than using nextDouble(), I
// haven't checked.
if (probability == 0.5) {
int successes = 0;
for (int count = 0; count < trials; count++) {
successes += nextBoolean() ? 1 : 0;
}
return successes;
}
else {
int successes = 0;
for (int count = 0; count < trials; count++) {
successes += super.nextDouble() < probability ? 1 : 0;
}
return successes;
}
}
else {
// We can use a normal approximation
return (int) Math.floor(
Math.sqrt(trials * probability * (1.0 - probability))
* nextGaussian()+ 0.5 + probability * trials);
}
}
}
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
iD8DBQFDR+78i2ZgbrTULjoRAt59AKCkYTmweBWjR1cbFNsoaGZ6rabEVwCfRpBY
AwSsxvcxoLTKo11YEaDOg2w=
=FhjX
-----END PGP SIGNATURE-----
|
| |
|
| |
 |
Chris Uppal

|
Posted: 2005-10-9 16:36:00 |
Top |
java-programmer >> Binomial Simulation
Kenneth P. Turvey wrote:
> // We can use a normal approximation
> return (int) Math.floor(
> Math.sqrt(trials * probability * (1.0 - probability))
> * nextGaussian()+ 0.5 + probability * trials);
I think this can evaluate to a negative number, which is perhaps not what your
want.
-- chris
|
| |
|
| |
 |
Chris Uppal

|
Posted: 2005-10-9 17:50:00 |
Top |
java-programmer >> Binomial Simulation
Wibble wrote:
> final int r = (int)(r_.nextInt() * probability_);
> h_.setSeed(r);
> bits_ = h_.nextInt();
> avail_ = BITS_PER_WORD;
I don't fully understand what you are trying to do here but I'm fairly sure it
isn't doing what you expect.
final int r = (int)(r_.nextInt() * probability_);
nextInt() returns a value randomly chosen in the full range of signed 32-bit
integers, and then you multiply that by the probability, thus cutting down the
range. E.g if probability_ is 0.005, then the range will be roughly -10
million to +10 million.
h_.setSeed(r);
this just sets the state of the other random stream. The fact that you have
given it a restricted range of seed has no significant effect on the
subsequently generated numbers.(except to reduce the number of possible
different /streams/ of numbers that _h can produce).
bits_ = h_.nextInt();
this will, again, return a value randomly chosen in the full range of signed
32-bit integers. So each bit has the same probability (1/2) of being set. In
the case where probability_ is 0.005, there are only 20 million different seed
values that you can have used, and so there are only 20 million different
possible sequences of 32 bits, and hence only that many possible values for
bits_ (instead of roughly 4 billion -- which isn't ideal, but is probably not
terribly important here).
I /think/ that what you are intending to do is generate an integer such that
each bit has a 'probability_' chance of being set, but I don't know how to do
that except by generating each bit separately, or using one of the
approximations we've been discussing.
-- chris
|
| |
|
| |
 |
Kenneth P. Turvey

|
Posted: 2005-10-10 5:24:00 |
Top |
java-programmer >> Binomial Simulation
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Sun, 09 Oct 2005 09:36:04 +0100, Chris Uppal wrote:
> Kenneth P. Turvey wrote:
>
>> // We can use a normal approximation
>> return (int) Math.floor(
>> Math.sqrt(trials * probability * (1.0 - probability))
>> * nextGaussian()+ 0.5 + probability * trials);
>
> I think this can evaluate to a negative number, which is perhaps not
> what your want.
You're right. It is unlikely, but possible. I'll have to look at this
again.
Thanks for the tip.
I added the check to my unit tests and it immediately failed.
Apparently it isn't as unlikely as I would have thought intuitively.
The other problem is that the result can be larger than the number of
trials, which we really don't want either. I'll have to play with the
math a little bit before I decide how to handle this. I'm not sure
simple truncation of the tails (returning either 0 or the number of
trials) is really a good way to handle this.
You know, I haven't really played with any statistics in years and I'm
enjoying it. I'm not sure what that says about me. :-)
- --
Kenneth P. Turvey <email***@***.com>
http://kt.squeakydolphin.com (not much there yet)
Jabber IM: email***@***.com
Phone: (314) 255-2199
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
iD8DBQFDSYp3i2ZgbrTULjoRAve/AKCGXP00KZo+daz4C94znTK8DQeEeQCfYTzn
fukhD8FV0kh+fx6l1UxRtTg=
=iwij
-----END PGP SIGNATURE-----
|
| |
|
| |
 |
Chris Uppal

|
Posted: 2005-10-10 14:01:00 |
Top |
java-programmer >> Binomial Simulation
Kenneth P. Turvey wrote:
> You know, I haven't really played with any statistics in years and I'm
> enjoying it. I'm not sure what that says about me. :-)
<chuckle/>
I always had great difficulty with the subject myself (so beware of my
reasoning in what follows !).
> The other problem is that the result can be larger than the number of
> trials, which we really don't want either. I'll have to play with the
> math a little bit before I decide how to handle this. I'm not sure
> simple truncation of the tails (returning either 0 or the number of
> trials) is really a good way to handle this.
A way of thinking about this that appeals to me is to anthropomorphise the
situation a bit (as, of course, we OO programmers always do). Imagine that one
of your creatures (lineages, bitmaps, whatever you want to call 'em) is --
unlike me -- a minimally competent statistician. It knows that God hands out
mutations at random, but that's /all/ it knows, except how many times it has
been zapped in each generation. So if in one generation it finds itself with
three mutations, it knows that God must have decreed that there be at least
three mutations in the population as a whole, but it doesn't now any more than
that. In particular it doesn't know how God choose the total number (call it
M), nor how M is distributed. M could, for instance, be a constant if God
didn't care for mucking around with complex code.
The question is, how long would it take the statistician to be able to tell
that God wasn't choosing M according to a pure binomial distribution ? And
would it be able to amass that much data in one run of your simulation ?
Because if it can't tell, then the difference can't be effecting its behaviour
(to a statistically significant degree) -- and its behaviour is all that
matters.
If God were using a constant value for M, then the tail of the distribution it
saw (of the number of hits it took per generation) would drop to zero
anomalously quickly (it would, for instance, /never/ take M+1 hits). My guess
is that the effect would be pretty subtle, and hard to detect in the limited
amount of data it could collect. I'm sure you will enjoy working out the exact
details ;-) If God were using a normal distribution for M (with more-or-less
arbitrary truncation), then presumably the divergence would be even harder for
the creature to measure, and would require more data (and a longer run) to
detect. If God went even further (as might not be a bad idea) and simply
pre-populated a largish array with integer values drawn from a binomial
distribution, and then chose an arbitrary[*] value from that array to use as M
for each generation, then it would -- I think -- be still harder to detect.
([*] cycle through 'em, choose one at random, I doubt whether it would make
much difference...)
-- chris
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- Loading jdbc jars and classes in the application default classloader dynamically..In our application, the JDBC jar files are stored in pre configured
location. say c:\server\libs\1.jar, 2.jar
We don't want to include these jars file in the class path. However,
whenever, we receive a jdbc request, we want to be able to load all the
jars located in this location and then do the basic jdbc call
sequence...
e.g. Class.forname("com.mydriver.SQLServerDriver");
Connection conn = DriverManager.getConnection(
"jdbc:mydriver:sqlserver://sqlserver1:1433;DatabaseName=Mydb;User=****t;Password=*****"
);
How ca i do this?
I tried the following code but doesn't help... I keep getting the
java.sql.SQLException: No suitable driver error. After somedebugging, I
found that the Drivermanager uses some getCallerClassLoader and that
doesn't match the class loader of com.mydriver.SQLServerDriver.
How do i make the loading using the default class loader at the same
time including those jar files?
String x = "kjds";
File f = new File("D:/server/libs");
File[] jarFiles = f.listFiles(new ExtentionFilter("jar"));
URL[] urls = new URL[jarFiles.length+1];
int i=0;
for(;i< jarFiles.length;i++){
try{
urls[i] = jarFiles [i].toURL();
}catch(Exception ex){}
}
ClassLoader z = new URLClassLoader(urls,
x.getClass().getClassLoader());
try
{
//Class DriverClass =
z.loadClass("com.mydriver.SQLServerDriver");
//Driver dd = (Driver)DriverClass.newInstance();
// DriverManager.registerDriver(dd);
Driver x =
(Driver)Class.forName("com.actuate.actuatedd.jdbc.sqlserver.SQLServerDriver",
true, z);
String cnstr =
"jdbc:mydriver:sqlserver://sqlserver1:1433;DatabaseName=Mydb;User=****t;Password=*****"
Connection conn = DriverManager.getConnection( cnstr );
}
catch (Exception e)
{
e.printStackTrace();
}
- 2
- OOM detectionHi,
I'm looking for a way to detect that the JVM is reaching an out of
memory situation. But, I don't want to do this by means of catching
an OutOfMemoryError, because by that time the ship is already
sinking. I came up with a solution that uses the Reference Objects
API, but I don't know if it will do the job correctly.
Below is a demo. Please give me some feedback on this.
I also tried it out using a SoftReference, but then it gives an
OutOfMemoryError eventually. Is this behavior JVM dependent?
CC me,
Frank.
/*
* Run with: java -verbose:gc Test
*/
import java.lang.ref.*;
import java.util.*;
public class Test extends Thread {
private ReferenceQueue queue = new ReferenceQueue();
private Reference pr;
private static Stack stack;
public void run() {
while(true) {
Object o = new Object(); // dummy object
pr = new WeakReference(o, queue);
o = null;
try {
queue.remove(); // when our dummy object gets finalised we continue here...
}
catch(InterruptedException e) { }
System.out.println("OOM");
stack.clear(); // prevent OutOfMemoryError here...
}
}
public static void main(String [] args) {
stack = new Stack();
new Test().start();
while (true) {
stack.push(new Object());
}
}
}
- 3
- Writing a generic InputBoxHi,
I wont tell my old way but I have rewritten my InputBox class as having
the following important snippets:
public class InputBox extends JDialog {
private ActionListener okAction;
public InputBox(ActionListener a, JFrame f, String label, String
title, String defaultText) {
okAction = a;
getMyOkButton().addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
okAction.actionPerformed(e);
dispose();
}
});
public String inputText() {
return control.getText();
}
}
Code uses it as follows
ActionListener okAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
myObject.setURLName(hyperlinkInputBox.getInputText());
} catch (Exception ex) {
Debug.LogException(this, ex);
}
}
};
hyperlinkInputBox = new UIInputBox(okAction, "Insert
Hyperlink",parentFrame,"URL:",null,300);
hyperlinkInputBox.setVisible(true);
I dislike having to make hyperlinkInputBox a private variable in the
calling class in order to reference it within the okAction
ActionListener. Same goes for myObject.
I guess it is not *too* shabby but can anyone improve my architecture?
thanks
Tim
- 4
- question concerning downcasthello guys,
Curiosity made me take a look at the tomcat 's implementation of the servlet
API.
The HttpServlet class, which can be subclassed by http servlets, contains
the "service" method that is invoked by the servlet container in order to
pass a web request to a particular servlet. The method accepts a
ServletRequest and ServletResponse object as arguments, and downcasts them
to HttpServletRequest and HttpServletResponse respectively and then calls a
"service" method implemented by the same class:
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException
{
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) { throw new ServletException("non-HTTP
request or response"); }
service(request, response);
}
}
How is it possible to do so, as the ServletRequest interface is more generic
than the HttpServletRequest (they have a hereditary relationship
HttpServletRequest== extends ServletRequest)?
TIA
- 5
- problem with methods on a bound classHi,
I've been fiddling around with JavaScript.pm, which is very cool, I have to
say, I've bound a class, and sucessfully bound an object, and i can read
from the object's properties, and execute it's getter/setter functions, but
for some reason i cannot get the object's methods to work..
here's a cleaned up version of what i've been testing with:
$js->bind_class(
name=>'Foo',
methods=>{
test => \&Foo::test
},
properties=>{
testy =>{
flags => JS_PROP_READONLY | JS_PROP_ACCESSOR,
getter => \&Foo::test_getter,
}
}
);
my $obj = new Foo();
$js->bind_object('obj', $obj)
(where package Foo has a 'test' method)
....
now in js: 'obj.testy' (the property) works fine, but 'obj.test()' (method)
just doesn't.. there seems to be no indication that it's successfully bound
(everything just says it's not defined).. getters and setters work, but
methods just don't seem to..
Any clues as to what's going on?
Dan
- 6
- Signed code runs using WebStart in 1.4 but not 1.5I have a signed application that runs flawlessly under WebStart in 1.4
JDKs/JREs (on WinXP/2K, Linux and MacOS X) that refuses to run under
WebStart in 1.5 JDKs (on both Windows and Linux; haven't tried on MacOS).
The error occurs when the certificate is validated (this is from 1.5.0_03):
java.security.cert.CeritificateException: Check leaf key usage failed in
certificate
at
com.sun.deploy.security.CertUtils.checkUsageForCodeSigning(CertUtils.java:102)
...
I've tried 1.5.0 (Windows & Linux) and 1.5.0_03 (Linux), with the same
error each time. I know of several others who have also been unable to
run my application under 1.5.0; I don't know of anyone who has been able
to run it under 1.5.0.
I'm using a code-signing certificate bought from Thawte. I've tried
using jarsigner from both 1.4 and 1.5, but get the same results each
time. From the exception, it seems likely that 1.5.0 doesn't believe
that the certificate used to sign the code can be used for code-signing,
but I don't know why it would come to this conclusion.
I've successfully run this app using WebStart under 1.4.2_01, 1.4.2_03
and 1.4.2_06, on Linux and WinXP/2K (ie these JDKs all successfully
validate the certificate used to sign the app and prompt the user as
expected), plus various Apple 1.4 JVMs.
Google hasn't been of any assistance, so any help would be greatly
appreciated.
Cheers,
Damian
- 7
- Getting value of variable from Thread to main classI have a problem, with getting value of a variable that is set in
thread. I start the Thread in a main class, thread gets the value from
server and sets it as static variable. After starting the thread I try
to print the value of " threadObjetc.staticvariable " but every time
it has a null value. I suppose that the reason for that is that thread
works in a background and functions of main class continues anyway. If
someone had a similar problem and could help me to avoid it I would be
gratefull for help, Thanks
- 8
- why it doest draw ???in the below short write
i try to write an Thread examle that try to draw lines in every second
from (0,0) to (x, y).
x and y are random between 0..255
with first come to tWork (Thread) it draws, but next second and next
seconds it doesnt do any thing.
g and gr are the same and initalized
i cheked them with this command :
System.out.println(gr.equals(g)); //it prints "true"
question is why it doesnt draw line after second 1 ?
polat
------------------------------------------------------------
package mypackage1;
import java.applet.*;
import java.awt.*;
import javax.swing.JButton;
class tWork extends Thread
{
Graphics gr;
public tWork(Graphics g)
{
gr = g;
System.out.println(gr.equals(g)); //it prints "true"
}
public void run()
{
int x, y;
while (true)
{
x = (int)(Math.random()*255);
y = (int)(Math.random()*255);
gr.drawLine(0, 0, x, y);
try
{
this.sleep(1000);
}
catch (Exception e) {}
}
}
}
public class Basla extends Applet
{
Thread t;
public Basla()
{
this.setSize(300,300);
}
public void paint(Graphics g)
{
t = new tWork(g);
t.start();
}
}
- 9
- Generating excel sheets through JSPHi,
I have previously created excel sheets in JSP in weblogic, and i get
the result accurately.
I had used;
<%@ page contentType="application/vnd.ms-excel" import="java.sql.*"
language="java"%>
at the top of the page and,
<meta http-equi="Content-Type" content="application/vnd.ms-excel;
charset=iso-8859-1">
in the head tag of my page.
Now I'm using tomcat 5.5 and this is just not working....
Can someone help me out with this?
- 10
- Java developer needed (Open Source project)Java developer needed, pref. with socket prog exp
---------------------------------------------------
Programming Language :: Java Competent 6 Mo - 2 yr
Socket programming(Java):: Want to learn < 6 Months
Project page: http://freelancebot.sourceforge.net/
- 11
- networking problemIm connecting an applet to my own simeple server useing
connection = new Socket( getCodeBase().getHost(), 2001, true );
But no matter where I open the applet, it allways say's the same ip is
connecting, the ip the simple server is running on. any idea's?
- 12
- [JSF] How to determine the WEB-INF path of the current web application?Hello everybody,
I'm new to the Java world writing my first Java web application with JSF 1.1
and Tomcat 5.5. I have the following problem:
I've created a Properties file and placed it in the WEB-INF directory of the
web application. The file contains several configuration options like
database parameters. I want to open this file within my web application
with a FileInputStream which I pass to the load() method of a Properties
object. Unfortunately I was unable to determine the path of the WEB-INF
directory of the current web application. I don't want to write the path
hard coded into the source code.
Maybe my way is not the correct "Java way" of solving this kind of problem
so I'm not only interested in an answer to my question but also in
suggestions how to solve this problem in a better way.
Thank you!
--
Sincerely
Sven Jacobs
- 13
- JDBC DriverHello,
How can I find out which JDBC driver is available on my system? I
am working on a linux server. I am trying to learn JDBC programming and
am having problems about which JDBC driver to use.
Regards
Marmagya
- 14
- ClassDefNotFoundI'm having a lot of trouble trying to run small applications that have compiled
fine. No matter what I try attempting to execute any class file gives me this
message:
java -classpath "." TryWindow.class
Exception in thread "main" java.lang.NoClassDefFoundError: TryWindow/class
I've tried setting my class path the the current working directory in my
environment, specifying the current directory with the -classpath switch,
specifying "" with the class path switch, running it as an unprivileged
user, running it as root, and manipulating the permissions and the result
has been the same. I also rebooted to Windows and tried it with the
NetBeans ide. What am I doing wrong? According to what I have read
java should be able to find classes in the current working directory.
Here is the code for the example I tried:
import javax.swing.*;
public class TryWindow{
static JFrame aWindow = new JFrame("This is the Window Title.");
public static void main()
{
aWindow.setBounds(50, 100, 400, 150);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.setVisible(true);
}
}
Thanks in advance.
Mitch_M
- 15
- struts or expresso or turbine?hi..
i've been reading the struts developer and it mentions that i want to
create a web application from scratch i should use either turbine or
expresso..
i'm looking for a free, main stream web framework, that can be used
with eclipse.
can anyone tell me about any of these and how they compare?
|
|
|