I would like to track the value of a boolean (not Boolean) variable in the Eclips debugger.
I need to know when it does change and, for this, i need to track it's value through all the execution; not only when it is in scope.
More particularly i have a class (let's call it myClass) with a boolean member variable called isAvailable. My program instantiate 4 or 5 myClass objects. I am expecting that at the end of the execution the isAvailable value of all of my objects is set to true. Contrarily to my excpectation one of myClass objects has isAvailable set to false. I need to know which (in a lot of) methods is setting isAvailable to false.
public class Prime {
public static boolean isPrime1(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrime2(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
public class PrimeTest {
public PrimeTest() {
}
@Test
public void testIsPrime() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Prime prime = new Prime();
TreeMap<Long, String> methodMap = new TreeMap<Long, String>();
for (Method method : Prime.class.getDeclaredMethods()) {
long startTime = System.currentTimeMillis();
int primeCount = 0;
for (int i = 0; i < 1000000; i++) {
if ((Boolean) method.invoke(prime, i)) {
primeCount++;
}
}
long endTime = System.currentTimeMillis();
Assert.assertEquals(method.getName() + " failed ", 78498, primeCount);
methodMap.put(endTime - startTime, method.getName());
}
for (Entry<Long, String> entry : methodMap.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey() + " Milli seconds ");
}
}
}
I am trying to find the fastest way to check whether the given number is prime or not. This
is what is finally came up with. Is there any better way than the second implementation(isPrime2).
If I have a soundbank stored in a JAR, how would I load that soundbank into my application using resource loading...?
I'm trying to consolidate as much of a MIDI program into the jar file as I can, and the last thing I have to add is the soundbank file I'm using, as users won't have the soundbanks installed. I'm trying to put it into my jar file, and then load it with getResource() in the Class class, but I'm getting an InvalidMidiDataException on a soundbank that I know is valid.
Here's the code, it's in the constructor for my synthesizer object:
try {
synth = MidiSystem.getSynthesizer();
channels = synth.getChannels();
instrument = MidiSystem.getSoundbank(this.getClass().getResource("img/soundbank-mid.gm")).getInstruments();
currentInstrument = instrument[0];
synth.loadInstrument(currentInstrument);
synth.open();
} catch (InvalidMidiDataException ex) {
System.out.println("FAIL");
instrument = synth.getAvailableInstruments();
currentInstrument = instrument[0];
synth.loadInstrument(currentInstrument);
try {
synth.open();
} catch (MidiUnavailableException ex1) {
Logger.getLogger(MIDISynth.class.getName()).log(Level.SEVERE, null, ex1);
}
} catch (IOException ex) {
Logger.getLogger(MIDISynth.class.getName()).log(Level.SEVERE, null, ex);
} catch (MidiUnavailableException ex) {
Logger.getLogger(MIDISynth.class.getName()).log(Level.SEVERE, null, ex);
}
Many years ago when I was at uni they said to put a capital i (I) in front of interfaces. Is this still a convention because I see many interfaces that do not follow this.
Why can't I cast a base class instance to a derived class?
For example, if I have a class B which extends a class C, why can't I do this?
B b=(B)(new C());
or this?
C c=new C();
B b=(B)c;
My string looks like;
String values = "I am from UK, and you are from FR";
and my hashtable;
Hashtable countries = new Hashtable();
countries.put("United Kingdom", new String("UK"));
countries.put("France", new String("FR"));
What would be the most effective way to change the values in my string with the values from the hashtable accordingly. These are just 2 values to change, but in my case I will have 100+
I was looking over some code the other day and I came across:
static {
...
}
Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?
I have a function that needs to perfom two operations, one which finishes fast and one which takes a long time to run. I want to be able to delegate the long running operation to a thread and I dont care when the thread finishes, but the threads needs to complete. I implemented this as shown below , but, my secondoperation never gets done as the function exits after the start() call. How I can ensure that the function returns but the second operation thread finishes its execution as well and is not dependent on the parent thread ?
public void someFunction(String data)
{
smallOperation()
Blah a = new Blah();
Thread th = new Thread(a);
th.Start();
}
class SecondOperation implements Runnable
{
public void run(){
// doSomething long running
}
}
How can I use the library to download a file and print out bytes saved? I tried using
import static org.apache.commons.io.FileUtils.copyURLToFile;
public static void Download() {
URL dl = null;
File fl = null;
try {
fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip");
copyURLToFile(dl, fl);
} catch (Exception e) {
System.out.println(e);
}
}
but I cannot display bytes or a progress bar. Which method should I use?
so when casting like in the statement below :-
int randomNumber=(int) (Math.random()*5)
it causes the random no. generated to get converted into an int..
Also there's this method I just came across Integer.parseInt() which does the same !
i.e return an integer
Why two different ways to make a value an int ?
Also I made a search and it says parseInt() takes string as an argument.. So does this mean that parseInt() is ONLY to convert String into integer ?
What about this casting then (int) ?? Can we use this to convert a string to an int too ?
sorry if it sounds like a dumb question..I am just confused and trying to understand
Help ?
Can anyone explain:
Why the two patterns used below give different results? (answered below)
Why the 2nd example gives a group count of 1 but says the start
and end of group 1 is -1?
public void testGroups() throws Exception
{
String TEST_STRING = "After Yes is group 1 End";
{
Pattern p;
Matcher m;
String pattern="(?:Yes|No)(.*)End";
p=Pattern.compile(pattern);
m=p.matcher(TEST_STRING);
boolean f=m.find();
int count=m.groupCount();
int start=m.start(1);
int end=m.end(1);
System.out.println("Pattern=" + pattern + "\t Found=" + f + " Group count=" + count +
" Start of group 1=" + start + " End of group 1=" + end );
}
{
Pattern p;
Matcher m;
String pattern="(?:Yes)|(?:No)(.*)End";
p=Pattern.compile(pattern);
m=p.matcher(TEST_STRING);
boolean f=m.find();
int count=m.groupCount();
int start=m.start(1);
int end=m.end(1);
System.out.println("Pattern=" + pattern + "\t Found=" + f + " Group count=" + count +
" Start of group 1=" + start + " End of group 1=" + end );
}
}
Which gives the following output:
Pattern=(?:Yes|No)(.*)End Found=true Group count=1 Start of group 1=9 End of group 1=21
Pattern=(?:Yes)|(?:No)(.*)End Found=true Group count=1 Start of group 1=-1 End of group 1=-1
My HTML looks like:
<td class="price" valign="top"><font color= "blue"> $ 5.93 </font></td>
I tried:
String result = "";
Pattern p = Pattern.compile("\"blue\"> $ (.*) </font></td>");
Matcher m = p.matcher(text);
if(m.find())
result = m.group(1).trim();
Doesn't seem to be matching.
Am I missing an escape character?
public class DocFilter extends FileFilter {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = Utils.getExtension(f);
if (extension != null) {
if (extension.equals(Utils.doc) ||
extension.equals(Utils.docx) )
{
return true;
} else {
return false;
}
}
return false;
}
//The description of this filter
public String getDescription() { return "Just Document Files"; }
}
Netbeans compiler warned with the error, "No interface expected here" for above code
Anyone has idea what was the problem?? I tried changing the 'extends' to 'implements', however, it didn't seem to work that way.
and when I changed to implements, the following code cannot work,
chooser.addChoosableFileFilter(new DocFilter());
and with this error,
"method addChoosableFileFilter in class javax.swing.JFileChooser cannot be applied to given types required: javax.swing.filechooser.FileFilter"
Can anyone help on this? Thanks..
Using the Basecamp API, is it possible to create a new project? It seems like a simple task, so either I'm missing something or this functionality is not available via the API.
I am using the slick2d library. I want to know how to get the exact tile location so when I click on a tile it only changes that tile and not every tile on the screen.
My tile generation class
public Image[] tiles = new Image[3];
public int width, height;
public int[][] index;
public Image grass, dirt, selection;
boolean selected;
int mouseX, mouseY;
public void init() throws SlickException {
grass = new Image("assets/tiles/grass.png");
dirt = new Image("assets/tiles/dirt.png");
selection = new Image("assets/tiles/selection.png");
tiles[0] = grass;
tiles[1] = dirt;
width = 50;
height = 50;
index = new int[width][height];
Random rand = new Random();
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
index[x][y] = rand.nextInt(2);
}
}
}
public void update(GameContainer gc) {
Input input = gc.getInput();
mouseX = input.getMouseX();
mouseY = input.getMouseY();
if(input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
selected = true;
}
else{
selected = false;
}
}
public void render() {
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
tiles[index[x][y]].draw(x * 64, y *64);
if(IsMouseInsideTile(x, y))
selection.draw(x * 64, y * 64);
}
}
}
public boolean IsMouseInsideTile(int x, int y)
{
return (mouseX >= x * 64 && mouseX <= (x + 1) * 64 &&
mouseY >= y * 64 && mouseY <= (y + 1) * 64);
}
I have tried a couple different ways to change the tile I am clicking on, but I don't understand how to do it.
The RSA implementation that ships with
Bouncy Castle only allows the
encrypting of a single block of data.
The RSA algorithm is not suited to
streaming data and should not be used
that way. In a situation like this you
should encrypt the data using a
randomly generated key and a symmetric
cipher, after that you should encrypt
the randomly generated key using RSA,
and then send the encrypted data and
the encrypted random key to the other
end where they can reverse the process
(ie. decrypt the random key using
their RSA private key and then decrypt
the data).
I can't use the workarond of using symmetric key. So, are there other implementations of RSA than Bouncy Castle?
Hello,
Which implementation is less "heavy": PriorityQueue or a sorted LinkedList (using a Comparator)?
I want to have all the items sorted. The insertion will be very frequent and ocasionally I will have to run all the list to make some operations.
Thank you!
I have been developing a project and in this project i have designed my code to do the same job after a specified time interval continuously. The job that wanted to be done has a lot of distinct cycles. The interval is small to execute them normally thus i used threads. Until that point everything is clear for me.
To decrease the process and information transaction i wanted to put an session like object that holds the given data and provide it to any thread at anytime. With this object i plan to not query the same configuration information from database at everytime but if it exists on the session take it else query and store on session.
I'm not sure how to implement this structure.
Regards,
Hi there!
I've got an XML file that is parsed and written in my application. From within my IDE (Eclipse) I simply address it like this:
Reading:
private String xmlFile = "file.xml";
and then I build the document:
doc = sax.build(xmlFile);
Writing is done like this:
writer = new FileWriter("file.xml");
Runs great so far, but after bundling my application, the file is no longer accessible.
What exactly do I have to do to make it accessible from within an application bundle?
I'm absolutely not familiar with the classpath or whatever I need for that, so please go easy on me!
Thank you very much!
Hello. I have some String[] arrays, for example:
['a1', 'a2']
['b1', 'b2', 'b3', 'b4']
['c1']
How can I mix them, so that I get ['a1', 'b1', 'c1', 'a2', 'b2', 'b3', 'b4'] (0 element of a, then b, c, 1 element of a, b, c and so on)? Thanks
I'm trying out the Runtime.exec() method to run a command line process.
I wrote this sample code, which runs without problems but doesn't produce a file at c:\tmp.txt.
String cmdLine = "echo foo > c:\\tmp.txt";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmdLine);
BufferedReader input = new BufferedReader(
new InputStreamReader(pr.getInputStream()));
String line;
StringBuilder output = new StringBuilder();
while ((line = input.readLine()) != null) {
output.append(line);
}
int exitVal = pr.waitFor();
logger.info(String.format("Ran command '%s', got exit code %d, output:\n%s", cmdLine, exitVal, output));
The output is
INFO 21-04 20:02:03,024 - Ran command
'echo foo c:\tmp.txt', got exit code
0, output: foo c:\tmp.txt
Hi folks:
some methods in our model pojos have been annotated like this:
@Column(name="cli_clipping_id", updatable=false, columnDefinition = "varchar(" + ModelUtils.ID_LENGTH + ") COLLATE utf8_bin")
columnDefinition attribute is database vendor dependant, so when trying to drop schema in HSQLDB using Hibernate it fails:
[ERROR] 16 jun 12:58:42.480 PM main [org.hibernate.tool.hbm2ddl.SchemaExport]
Unexpected token: COLLATE in statement [create table cms.edi_editorial_obj (edi_uuid varchar(23) COLLATE
]
To fix this, i'm thinking on this solution (but don't want to spend time if it isn't possible) , at runtime, for each method column annotated:
Get @Column annotation
Create a copy of the column annotation, setting columnDefinition null using javaassist.
set column method annotation to the copy column annotation object overriding the old one (i don't know it this is possible)
Is it possible to "hack" these methods this way?
Any help would be much appreciated ...