Why do you have this line in the Order class?
Order order = new Order( 0 );
Why do you have this line in the Order class?
Order order = new Order( 0 );
A member gains a 'banned' status if he ends up gathering 10 infraction points. When a member is infracted for breaking the rules (http://www.daniweb.com/forums/faq.php?faq=daniweb_policies), he is "infracted" and "awareded" infraction points based on the severity of the rule broken.
Bans can expire, typically in 6 months or so, unless it's a perma ban, which is normally given to persistent drug/porn spammers and those members who create new accounts for the purpose of avoiding/getting around a ban.
..so, what about the first bit of my question?
That check is a standard way of dealing with objects composed of others objects which can be NULL. Basically, you start off with a prime, keep adding the hash codes of the constituent objects and use 0 if a given field is NULL (since you can't invoke hashCode() on a NULL reference).
Wow, I don't know whether you made that up, or if it is a normal way of handling this, but it's brilliant
Thank you for your help in this thread
You are of course welcome. :-)
Just one last thing: is there away to determine whether an exception has been thrown by in or out?
Yup, there is; I ignored it for examples' sake but good job noticing it. You can print out the toString() representation of the "closeable" and it should print out whether it's an 'in' or 'out'.
public class Utils {
public static void closeAll(final boolean ignoreExceptions, Closeable...closeables) {
for(final Closeable closeable : closeables) {
try {
if(closeable != null) {
closeable.close();
}
} catch(final Throwable t) {
if(!ignoreExceptions) {
// OR LOG.error("Exception closing stream " + closeable, e); in case you are using a logging library
System.out.println("Error closing stream " + closeable);
t.printStackTrace();
}
}
}
}
}
This would print out something like java.io.FileInputStream@19821f
for a FileInputStream and so on.
Simply put, a hash code is ideally a best effort numeric (integer) representation of a Java object. Each Java object which lives in the JVM has a default hashCode() which is mapped to the integer representation of the address of that object (which as you can see is a good enough representation, since objects have unique addresses. This breaks in cases where the underlying address space is more than the range of an integer but don't worry about that for now).
But why allow the hashCode() to be overridden? The short answer is: because it can be used in a clever way to implement hash tables in Java. The logic used in the hashCode() method can be thought of as a hash function used to generate hash codes for the given object.
As an example, let's suppose you decide to put the hashCode() method to good use for the String object. The objective here would be to make sure that we almost always get the same hashCode() for equal strings. The most logical way here would to consider the characters of the string to generate the hash code since if a string has same characters and same length, it has to be same. But, we have to make sure that the order of the characters are also taken into consideration when generating the hash code (we don't want 'sad' and 'das' to end up having the same hash code). But be warned, it is quite *possible* …
~sos~:
That seems very reasonable.
About closing the streams:
would using IOUtils.closeQuietly(); make sure the second stream is closed, even if the first stream fails to close?I have rewritten my code snippet now, (no error handling yet)
could you maybe give it quick look and tell me if I'm doing anything stupid?
One thing that irritates me is that I think it would be best to open the in- and output streams in the same try-catch block,
but that makes error handling difficult, as there is no telling which of the streams throws an IOException for instance.
Or am I mistaken?import java.io.*; public class TextMan { public static void main (String[] args) { try { BufferedReader in = null; BufferedWriter out = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream("bhaarat.txt"), "UTF-8")); } catch (Exception e) { e.printStackTrace(); } try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("out.txt"), "UTF-8")); String strCache; strCache = in.readLine(); int count = 1; //Silly string manipulation, you can probably just ignore this :) while (strCache != null) { strCache = strCache.split(" ", 0)[1]; if (strCache.charAt(0) == 'H' || strCache.charAt(0) == 'S') { out.write(count + ". " + strCache + "\n"); count++; } strCache = in.readLine(); } } finally { if(in != null) in.close(); if (out != null) out.close(); } }catch (Exception e) { e.printStackTrace(); } } }
I realize this could be done with a one-liner using awk and grep, but I'm trying to learn a little programming …
@ ~s.o.s~
maybe you still around
Not sure what you are trying to say here?
<OffTopic> where I can find something similair http://forums.oracle.com/forums/thread.jspa?threadID=2175486&tstart=15 'cos last two days were full of zoobies and spammers </OffTopic>
If I'm not wrong, you need a feature wherein you can report necromancers and spammers? Yes, there is; click on the "Flag Bad Post" button which is present to the left of every post and that post will be shown in the Reported Posts forum and be brought to the attention of the moderators.
So the 'trick' is to instantiate (correct term?) the in/out objects outside the try block, and then open the actual streams inside it?
The correct term is "declare".
f I may ask: why shouldn't I handle errors?
For debugging, printing the stacktrace, as you suggest,
is obviously more exact than my own guesses as to what causes the exception to be thrown.
But shouldn't the final program be able to handle the exceptions appropriately?
And I'm guessing you then want me to log the exceptions for potential 'bug-reports'
(which will of course never be relevant for my little hobby-project but nevertheless, it's probably a good idea to get into the habit of doing it)
I never mentioned "not to handle errors". To re-quote myself:
BTW, make sure that in your first attempt of code, you don't end up catching each and every exception
I am a big fan of "start small and make it big" methodology. The first attempt of *any* code should be to get the functionality right and then move on to other important things. Your code right now has more error handling and less important stuff (copying the contents of a file?).
And yes, you are right, *every* exception in the system should be logged unless you know what you are doing.
maaaaan in all due respect to you, don't do it, never, never... , sure you have to (maybe) wrote lots of code without, you are probably wrong, …
The try-catch-finally (try-catch) is a well known vicious cycle when dealing with closeable resources. There are two ways around this:
* Using the nested-try method (NOT RECOMMENDED, since multiple resources can make the code ugly and this doesn't handle closing of 'out' in case closing of 'in' fails)
public static void main(final String[] args) {
try {
Scanner in = null;
BufferedWriter out = null;
try {
in = new Scanner(new File("bhaarat.txt"), "UTF-8");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("output.txt")), "UTF-8")); // yuck
while(in.hasNextLine()) {
out.write(in.nextLine());
out.newLine();
}
} finally {
if(in != null) in.close();
if(out != null) out.close();
}
} catch(final Exception e) {
e.printStackTrace();
}
}
* Creating helper methods or using external libraries which take care of exception handling (RECOMMENDED):
public static void main(final String[] args) {
Scanner in = null;
BufferedWriter out = null;
try {
in = new Scanner(new File("bhaarat.txt"), "UTF-8");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("output.txt")), "UTF-8")); // yuck
while(in.hasNextLine()) {
out.write(in.nextLine());
out.newLine();
}
} finally {
// http://commons.apache.org/io/api-1.2/org/apache/commons/io/IOUtils.html#closeQuietly%28java.io.InputStream%29
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
BTW, make sure that in your first attempt of code, you don't end up catching each and every exception. Just let them propagate to the main thread so that the JVM automatically exits by spitting out a stack trace. Add helpful error messages only in case where in the user doesn't need to see the trace but at the same time do make sure that the original exception is "logged" somewhere and not eaten up.
The FilenameFilter is used to filter out files in visual components (e.g. when you navigate to a folder, only *.java files would be seen) and in cases where you need to return file names which satisfy a given criteria. Basically for filtering needs based on "file names", FilenameFilter is used.
FileFilter on the other hand deals with "File" objects i.e. filtering based on a given File attributes like; is the file hidden, is it read only; something which a file name can't give you.
Of course, it's pretty trivial to create a File object based on its name and parent directory so I guess these "two" filters are more of convenient wrappers over the same concept but slightly different use cases.
Sprinkling a lot of "static" constructs (variables/methods) throughout your code normally leads to hard to maintain code. Regarding the question of running the race multiple times, simply moving the Thread instantiation to the main() method and looping over it should do the job.
// untested
public static void main(final String[] args) {
for(int i = 0; i < 10; ++i) {
Thread hare = new Thread(/* */);
Thread tortoise = new Thread(/* */);
hare.start();
tortoise.start();
hare.join();
tortoise.join();
}
}
The join() call ensures that new "races" are not started as long as a race is in progress.
BTW, I think that this design can be made much more simpler and logical. You can have a Racer class which has the attributes like speed, chance, name etc. Tortoise and Hare would be subclasses of this Racer class. Your ThreadRunner (better name would be RacingSimulator) would take a Racer along with a RaceCompletonHandler (which is basically a class with a single method finished()). So, the code would look something like this:
// untested
public class Main {
public static void main(final String[] args) {
RaceCompletionHandler handler = new RaceCompletionHandler();
Hare h = new Hare();
Tortoise t = new Tortoise();
RacingSimulator simulatorHare = new RacingSimulator(h, handler);
RacingSimulator simulatorTor = new RacingSimulator(t, handler);
for(int i = 0; i < 10; ++i) {
Thread hThread = new Thread(simulatorHare);
Thread tThraed = new Thread(simulatorTor);
// start threads
hThread.start();
tThread.start();
// join them
hThread.join();
tThread.join();
}
}
}
class Racer() {
// attributes
} …
You are missing a `return` statement in your catch block:
try {
Thread.sleep(100);
} catch(InterruptedException e) {
// print win
return;
}
Basically, when the 'loser' thread is interrupted by the main class, you catch the exception, log the message but continue with the loop and hence the program keeps going on.
You need to improve your 'google-fu' :-)
http://www.mkyong.com/applet/jmf-unable-to-handle-format-mpeglayer3/
I haven't used JMF but as per this thread JMF is horrible. You have been warned, or something like that...
AFAIK, RSS/Atom readers only show feeds which were exposed by the site in consideration. So if the feeds published by Daniweb don't show the entire thread, no feed reader would be able to show the entire thread.
As an example, consider this feed exposed by Github which shows the entire blog post with images since that's how they expose their feed to be.
Yeah, the first item of the array will be the object on which the method was invoked and the second item would be the newly created Cell with the same attributes as that of the original Cell object.
It returns an array of two C objects; one object is the object on which the 'action' method is invoked and the second one been a clone of the first one. Your mitosis method can use the same trick i.e. return return Pair.newPair(this, new Cell(this))
.
You can return a Pair object which contains a pair of Cell instances. A sample Pair class implementation can be found here.
Also, cloning in Java is pretty much broken (read the experts view here) and you would be better off creating a copy constructor which does the same stuff.
class Pair<F, S> {
final F first;
final S second;
private Pair(final F first, final S second) {
this.first = first;
this.second = second;
}
public static <A, B> Pair<A, B> newPair(final A first, final B second) {
return new Pair<A, B>(first, second);
}
// getters here i.e. getFirst() and getSecond()
}
class Cell {
private final String name;
private Cell(final String name) {
this.name = name;
}
// copy constructor
public Cell(final Cell other) {
this.name = other.name;
}
public static Cell newCell(final String name) {
return new Cell(name);
}
public Pair<Cell, Cell> mitosis() {
return Pair.newPair(new Cell(this), new Cell(this));
}
}
Yes, you definitely can do it. If I've captured your requirements correctly, you basically want to "invoke" the functionality implemented by native extensions in your Java code. In that case, look into JNI (the actual specification) and a easier way to go about it using JNA (JNI is too much chore and boilerplate code).
Your problem is that you are using 'long' type where 'double' is desirable. For e.g. what should be power of 10.1^2 ? What does your invocation of 'power(10.1, 2)' print? Your power method is broken but it doesn't throw a compile time error because of your use of `*=` construct. Try replacing it with `result = result * x` and you'll notice where you are going wrong.
This is because each thread spawned is effectively a garbage collection root i.e. the central point at which the GC starts working. As far as an official source is concerned, the same is mentioned (but in a bit cryptic way) here (read the unreachable section).
I'm not sure I buy into this idea that if one provides code, they "deprive" or "ruin" anybody's thinking process. Maybe it's because I'm older, have already "been there, done that" as far as formal schooling goes, and I'm a professional programmer now. I've already proved myself and hence no longer need the "if I just give it you, you'll never learn to think for yourself" lecture. I give that lecture to my ten year old nephew, but I know him and feel somewhat responsible for instilling good habits in him. Yeah, I know all sorts of students come here with homework dumps and, if given the verbatim code, won't put any effort into it and hence never learn to think.
IMO it's got nothing to do with age (after all almost everyone advocating it in this thread is a middle aged bloke [rude assumption? maybe :>); it's just a matter of whether you want to give a solution to the OP or want to go out of your way and help him reach the solution, nothing more, nothing less.
There are all kinds of students who post here; those who already have the solution and want to understand how it works, those who don't have the solution and won't mind a ready solution but at the same time have a desire to learn something new and those who have no intention of learning. Posting code is a much bigger problem in a thread which already has an ongoing …
It wasn't meant to sound like an attack and i apologise.After you sent me that message i've re read the rules and i couldn't find myself breaking any.I'm not saying i don't deserve my down-reps but i definitely don't deserve all of them.I apologise for my bad english and i would like to see you handling with my language .I didn't know you had a forum for complains so my bad again.My personal opinion is that you should have a rule saying you can't post full solutions and i will try to stick with this not yet implemented rule if that's ok with you.I didn't really think i should take it from anyone else but a moderator since you're the person in charge here but i did mind the 8 down reps before telling me what i did wrong.Anyway i'm sorry for this and i hope i didn't offended you in any way.
No one can infract you for posting complete solutions (the reason why you haven't received an infraction till now). Reputation, is a different matter. Unless you have a member specifically targeting you with -ve rep, there is little we can do; after all, reputation was meant to be a measure of how individual members feel about the post. If most of the regulars of C++ forum are against posting complete solutions, you would get downvoted.
You have two choices:
Are you using a redirect on the server side when serving the excel file? How exactly is the download feature implemented? Also, what's the code you are using to download the excel file?
Why the reluctance to create more forums, does having more forums affect something that we aren't aware of?
At least from a moderation viewpoint, it amounts to more house keeping which needs to be taken care of. Plus, it's not like it was always this way in the past. Forums *were* created based on user request. But it turns out that the forum is created, it receives little or no activity and becomes target for link spam which might go on unnoticed for a long time.
Another point is having expertise in a given area. Most of the times it turns out that a new forum is created, the member who requested the forum creation actively answers questions on that forum and suddenly disappears. This results in the forum being filled with regulars who are seeking help rather than someone who is capable of resolving them. I know it has to start *somewhere* and it is worth a try but our previous experience has been pretty bad with this stuff.
I personally don't like placing the image writing code in the PhotoFile class. Plus, you should not write raw bytes but the PhotoFile object to the ObjectOutputStream. The algorithm for writing should be:
For reading:
Not that I know of; on the contrary, PreparedStatements are capable of being compiled down to an efficient representation since the structure of the query remains the same with the variables being parametrized. This is much better than creating a SQL query for each request by concatenating the values of x and y to the original SELECT query which can't be compiled down to an optimized form.
It does not matter whether x and y are from the user or not. You can set it in the prepared statement as you do it for username and password. As long as 'x' and 'y' are variables which are available in the scope of the method, you can use them as you would use your username and password.
If you need to pass them for every call to prepared statement, then they are not constant and should be part of prepare statement. If they really are constants, you can embed those values in the query itself. Or you can combine both the approaches:
var pStmt = "select * from tbl where u=? and p=? and x=? and y=?";
pStmt.setString(1, user); pStmt.setString(2, pwd);
pStmt.setString(3, CONST1); pStmt.setString(4, CONST2);
Rename the class to something more logical rather than naming it Serialize. Ensure that your class has a serialVersionUID field (google for it). Also, no need to make name and format as a byte array, let them be strings. As far as writing images to ser file is concerned:
Three ways I can think of:
I would personally go with the second method.
A serialized image written to a file is not the same as an image written to a file. Java serialization uses a specific binary format for writing out Java objects. Also, your post isn't clear. What exactly does "serialize[x]" contains i.e. what kind of object? What is locaties?
Generally, you don't want to write code this way - exceptions should handle exceptional conditions, not expected ones - but that's the way the Integer class is written.
I know that, but if the API exposed by the core library says that parsing an invalid input for integer results in an exception, that's how the client should handle it rather than trying to find ways to get around this fact, unless there is a good reason to believe that a custom implementation would make much more sense than the de-facto approach.
If you want to learn something more about why this is, do some reading about exception handling. A little quality time with google should see you sorted on this.
Not sure if this was intended for me or the OP but if it's for me, I think I've done a good amount of reading and am aware of *when* and *how* exceptions should be used. :-)
Try to parse the user input as a number; if it fails, the given string is not a valid number, otherwise it is. Look into the parseXXX method of the wrapper classes (Integer, Long, Float etc.).
First, don't mess with your Tomcat lib directory; all application related jars should ideally go in the WEB-INF/lib directory of your web application, unless you have a good reason to not do so.
Regarding the error message, I think what is happening here is that when you are logged in successfully, you are assigned a session token (which looks like the output of a hash algorithm like MD5 or SHA etc.) which has a fixed validity. Given that you were trying to use the same token in the morning (a token which was generated sometime in night), the token validity check must have failed on the server resulting in the given error message.
But this still leaves us with the question as to why the original post wasn't successful which I think Dani might be a better position to answer.
Why are you using DataOutputStream for writing out textual content? Use PrintWriter by passing in the FileOutputStream created, invoke its println() method and you should be good to go.
Always make sure that you use XxxWriter for writing out textual content rather than streams.
Of all the posts in this thread, I am in complete agreement with Progr4mmer's post.
To someone beginning programming (not just Java), I'd neither recommend a full-blown IDE or a stupid text editor like Notepad. I mean come on, if you want to test your vision, there are better things to do that "try" to program in Notepad. :-)
I wouldn't recommend a specific text editor but any editor which does smart indentation, syntax highlighting, has the option of converting tabs to spaces, a regex based search/replace and multiple encoding support is worth its weight in gold.
OK, here we go.
Thread_1 outputs values from 1 to 1000. Thread_1 waits. Thread_2 outputs values from 1 to 1000. Thread_2 now waits. Thread_1 outputs values from 1000 to 2000. Thread_1 is done. Thread_2 outputs values from 1000 to 2000. Thread_1 exits followed by Thread_2.
I'm not really convinced with the scenario you have presented since it can easily be solved by a single thread, esp given your requirement that while thread1 is counting, thread 2 shouldn't do anything. The answer I'm presenting here is assuming that you have a valid scenario which justifies this approach i.e. thread 1 does task A which thread 2 depends on (task B), thread 2 does task B which thread 1 depends on (task C), thread 1 does task C on which thread 2 depends (task D). Maybe if you posted the real requirement I might try to help you with an even better solution.
One way of doing this would be to use a SynchronousQueue as a sequencer here. The unique thing about this queue is that its "put" and "take" operations for an item block as long as there is nothing on the other side (i.e. another task aka thread) to "take" or "put" the item respectively.
The way we use this class is pass it to the two work unit classes which we have (worker 1 and 2) and ensure that the sequencing is orchestrated between them using this queue. Here when I say worker 1, I mean …
Is it necessary for you to write your own lock implementation for this or are you free to use any standard classes for the same?
Glad to hear that a long time lurker finally decided to join Daniweb and help out others. Welcome to Daniweb. :)
Are you using some sort of collection to store the related buttons which you need to enable/disable? If not, use a List or an array and enabling/disabling would just be a matter of looping over the buttons and setting the appropriate flag.
EDIT: Slooow :-)
On a related note, something which you should always keep in mind when writing code is to follow the principle of least intrusion when it comes to defining contracts; be it between methods of the same class or when exposing an external API.
Let's take a trivial example of printing the contents of a String array. You can of course write a method which would loop over all the strings and print them, but what happens when you need to print out "Foo" objects? Taking a step back, we realize that the "print" method really need not know about the real type of the object it would be printing. Given that every Object inherits the 'toString' method from the Object superclass, you can simply loop over any type of list and just output its string representation using the toString() method.
So basically, never ever define external contracts in terms of implementation/specific classes; they would make your code needlessly inflexible. Be as generic as possible i.e. make sure the method being called doesn't know "too" much about the caller and vice-versa.
Oh and BTW, apologies for the near-offtopic rant. :-)
You are missing the assignment to "value" field of your object i.e. this.value = s
.
I've never used Swing/AWT but I suppose the answer to this question is pretty generic; you basically "append" the new value to the existing value rather than setting the new value as it is. So if "txtBox" is your text field, after a key is pressed, you might want to do txtBox.value += keyValue
as opposed to txtBox.value = keyValue
.
What do you think? Are you still getting compile time errors? Have you tried running it with a sample tree? Does it give out correct values? Wrong values?
That's because you ignored Jon's reply:
max is a shorthand for "a function returning the maximum of two numbers". You'll find an implementation of such a function in java.Math.
Also, when the node is NULL, don't return -1 but 0 if you want the height of a single node tree to be 1.
What kind of error? Compile time? Run time? Post the latest code and highlight the line which gives the error along with the complete error description.
Sir can i asked question max(height(node.L), height(node.R)) + 1 for what is this for just curious?
This expression inspects the heights of the left and right sub-tress (look at the recursive call "height") and returns the maximum of them. So basically, the first invocation of this method would be by passing in the "root" of the tree and this method would in turn invoke the same method for the nodes of the right/left subtree of the root node.
The best way here would be to "draw" a tree using pencil and paper and trace the output of the calls.
As per this, the basic algorithm for calculating the height of a binary tree is:
height(node):
if node == null:
return 0
else:
max(height(node.L), height(node.R)) + 1
Now come up with an implementation and post your updated code if it still doesn't work.
Thank you in advance hoping for your positive response...sir if this is correct how can i get the height of the tree and the leaves and level of the tree...like i send you a while the problem
Post what you've got till now (regarding the tree height) and we'll pick it from there.