What complexity are the methods multiply, divide and pow in BigInteger currently? There is no mention of the computational complexity in the documentation (nor anywhere else).
I am a building a console Sudoku Solver where the main objective is raw speed.
I now have a ManagerThread that starts WorkerThreads to compute the neibhbors of each cell. So one WorkerThread is started for each cell right now. How can I re-use an existing thread that has completed its work?
The Thread Pool Pattern seems to be the solution, but I don't understand what to do to prevent the thread from dying once its job has been completed.
ps : I do not expect to gain much performance for this particular task, just want to experiment how multi-threading works before applying it to the more complex parts of the code.
Thanks
Here's what I am looking to accomplish, I have a class that has an enum of some values and I want to subclass that and add more values to the enum. This is a bad example, but:
public class Digits
{
public enum Digit
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
}
}
public class HexDigits extends Digits
{
public enum Digit
{
A, B, C, D, E, F
}
}
so that HexDigits.Digit contains all Hex Digits. Is that possible?
I am writing a simple multithreaded socketserver and I am wondering how best to handle incoming connections:
create a new thread for each new connection. The number of concurrent threads would be limited and waiting connections limited by specifying a backlog
add all incoming connections into a queue and have a pool of worker threads that process the queue
I am inclined to go for option 2 because I really don't want to refuse any connections, even under high loads, but I am wondering if there are any considerations I should be aware of with accepting effectively unlimited connections?
I have the following code in struts.xml:
<interceptor-ref name="checkTabsStack">
<param name="tabName">availability</param>
</interceptor-ref>
and I want to access the parameter tabName in the interceptor routine, how do i do that? i tried
Map params = ActionContext.getContext().getParameters();
but params comes empty...
Thanks!
Suppose I have a string that contains '¿'. How would I find all those unicode characters? Should I test for their code? How would I do that?
I want to detect it to avoid sax parser exception which I am getting it while parsing the xml
saved as a clob in oracle 10g database.
Exception
javax.servlet.ServletException: org.xml.sax.SAXParseException: Invalid byte 1 of 1-byte UTF-8 sequence.
Hi,
I have an arraylist set up. I have input instuctions set up too, so that the user can enter one string, then one integer, then one string (the first name, the age, and the last name).
I need to sort the arraylist by the last name. The code I have entered so far is all under the main method:-
public static void main(String[] args) {
Name Name[] = new Name[50];
int count = 0;
for (int i=0; i<50; i++)
NewName[i] = new Name();
//ADD NEW TO ARRAYLIST NAME
String FName = JOptionPane.showInputDialog("first name");
int age = Integer.parseInt(JOptionPane.showInputDialog("age"));
String LName = JOptionPane.showInputDialog("last name");
NewName[count] = new Name(FName, age, LName);
count = count++;
}
//ITEMS SORT BY LAST NAME
//CODE FOR SORT GOES HERE
when looping, for instance:
for ( int j = 0; j < 1000; j++) {}; and I need to instantiate 1000 objects, how does it differ when I declare the object inside the loop from declaring it outside the loop ??
for ( int j = 0; j < 1000; j++) {Object obj; obj =}
vs
Object obj;
for ( int j = 0; j < 1000; j++) {obj =}
It's obvious that the object is accessible either only from the loop scope or from the scope that is surrounding it. But I don't understand the performance question, garbage collection etc.
What is the best practice ? Thank you
I need to split a text using the separator ". ". For example I want this string :
Washington is the U.S Capital. Barack is living there.
To be cut into two parts:
Washington is the U.S Capital.
Barack is living there.
Here is my code :
// Initialize the tokenizer
StringTokenizer tokenizer = new StringTokenizer("Washington is the U.S Capital. Barack is living there.", ". ");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
And the output is unfortunately :
Washington
is
the
U
S
Capital
Barack
is
living
there
Can someone explain what's going on?
Right, this is from an older exam which i'm using to prepare my own exam in january. We are given the following method:
public static void Oorspronkelijk()
{
String bs = "Dit is een boodschap aan de wereld";
int max = -1;
char let = '*';
for (int i=0;i<bs.length();i++) {
int tel = 1;
for (int j=i+1;j<bs.length();j++) {
if (bs.charAt(j) == bs.charAt(i)) tel++;
}
if (tel > max) {
max = tel;
let = bs.charAt(i);
}
}
System.out.println(max + " keer " + let);
}
The questions are:
what is the output? - Since the code is just an algorithm to determine the most occuring character, the output is "6 keer " (6 times space)
What is the time complexity of this code?
Fairly sure it's O(n²), unless someone thinks otherwise?
Can you reduce the time complexity, and if so, how?
Well, you can. I've received some help already and managed to get the following code:
public static void Nieuw()
{
String bs = "Dit is een boodschap aan de wereld";
HashMap<Character, Integer> letters = new HashMap<Character, Integer>();
char max = bs.charAt(0);
for (int i=0;i<bs.length();i++) {
char let = bs.charAt(i);
if(!letters.containsKey(let)) {
letters.put(let,0);
}
int tel = letters.get(let)+1;
letters.put(let,tel);
if(letters.get(max)<tel) {
max = let;
}
}
System.out.println(letters.get(max) + " keer " + max);
}
However, I'm uncertain of the time complexity of this new code: Is it O(n) because you only use one for-loop, or does the fact we require the use of the HashMap's get methods make it O(n log n) ?
And if someone knows an even better way of reducing the time complexity, please do tell! :)
I am relatively new to multi-threading and want to execute a background task using a Swingworker thread - the method that is called does not actually return anything but I would like to be notified when it has completed.
The code I have so far doesn't appear to be working:
private void crawl(ActionEvent evt)
{
try
{
SwingWorker<Void, Void> crawler = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
Discoverer discover = new Discoverer();
discover.crawl();
return null;
}
@Override
protected void done()
{
JOptionPane.showMessageDialog(jfThis, "Finished Crawling", "Success", JOptionPane.INFORMATION_MESSAGE);
}
};
crawler.execute();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
}
}
Any feedback/advice would be greatly appreciated as multi-threading is a big area of programming that I am weak in.
<resource name="cde.xml" status="updated" isCollection="false">
<mediaType>xml</mediaType>
<creator>admin</creator>
<createdTime>1352783477964</createdTime>
<lastUpdater>admin</lastUpdater>
<lastModified>1352783477964</lastModified>
<description />
<version>0</version>
<content>ZGFza2QgbGQgbGt2Zmx3ZGFzamQgYWRsa2ogYWxramRrbGEgamQK
</content>
</resource>
i want to catch nodes which are having status using xpath here is the xpath expression other part of the code is correct. I have problem with xpath expression
AXIOMXPath xpathExpression = new AXIOMXPath ( "//resourse[@name]");
Hello,
Im using Collections.sort() to sort a LinkedList whose elements implements Comparable interface, so they are sorted in a natural order. In the javadoc documentation its said this method uses mergesort algorithm wich has n*log(n) performance.
My question is if there is a more efficient algorithm to sort my LinkedList?
The size of that list could be very high and sort will be also very frequent.
Thanks!
I would like to know what is the best, fastest and easiest way to compare between 2-dimension arrays of integer.
the length of arrays is the same. (one of the array's is temporary array)
thanks.
I have a program where I am generating two double numbers by adding several input prices from a file based on a condition.
String str;
double one = 0.00;
double two = 0.00;
BufferedReader in = new BufferedReader(new FileReader(myFile));
while((str = in.readLine()) != null){
if(str.charAt(21) == '1'){
one += Double.parseDouble(str.substring(38, 49) + "." + str.substring(49, 51));
}
else{
two += Double.parseDouble(str.substring(38, 49) + "." + str.substring(49, 51));
}
}
in.close();
System.out.println("One: " + one);
System.out.println("Two: " + two);
The output is like:
One: 2773554.02
Two: 6.302505836000001E7
Question:
None of the input have more then two decimals in them. The way one and two are getting calculated exactly same.
Then why the output format is like this.
What I am expecting is:
One: 2773554.02
Two: 63025058.36
Why the printing is in two different formats ? I want to write the outputs again to a file and thus there must be only two digits after decimal.
I have written this piece of code to break an image into 9 pieces and it gives me runtime error. There is no error in LogCat and I am stuck. The error comes at line 7 line from bottom (Bitmap.createBitmap(...);).
public Bitmap[] getPieces(Bitmap bmp) {
Bitmap[] bmps = new Bitmap[9];
int width = bmp.getWidth();
int height = bmp.getHeight();
int rows = 3;
int cols = 3;
int cellHeight = height / rows;
int cellWidth = width / cols;
int piece = 0;
for (int x = 0; x <= width; x += cellWidth) {
for (int y = 0; y <= height; y += cellHeight) {
Bitmap b = Bitmap.createBitmap(bmp, x, y, cellWidth,
cellHeight, null, false);
bmps[piece] = b;
piece++;
}
}
return bmps;
}
hi,
first time dealing with xml, so please be patient. the code below is probably evil in a million ways (I'd be very happy to hear about all of them), but the main problem is of course that it doesn't work :-)
public class Test {
private static final String JSDL_SCHEMA_URL = "http://schemas.ggf.org/jsdl/2005/11/jsdl";
private static final String JSDL_POSIX_APPLICATION_SCHEMA_URL = "http://schemas.ggf.org/jsdl/2005/11/jsdl-posix";
public static void main(String[] args) {
System.out.println(Test.createJSDLDescription("/bin/echo", "hello world"));
}
private static String createJSDLDescription(String execName, String args) {
Document jsdlJobDefinitionDocument = getJSDLJobDefinitionDocument();
String xmlString = null;
// create the elements
Element jobDescription = jsdlJobDefinitionDocument.createElement("JobDescription");
Element application = jsdlJobDefinitionDocument.createElement("Application");
Element posixApplication = jsdlJobDefinitionDocument.createElementNS(JSDL_POSIX_APPLICATION_SCHEMA_URL, "POSIXApplication");
Element executable = jsdlJobDefinitionDocument.createElement("Executable");
executable.setTextContent(execName);
Element argument = jsdlJobDefinitionDocument.createElement("Argument");
argument.setTextContent(args);
//join them into a tree
posixApplication.appendChild(executable);
posixApplication.appendChild(argument);
application.appendChild(posixApplication);
jobDescription.appendChild(application);
jsdlJobDefinitionDocument.getDocumentElement().appendChild(jobDescription);
DOMSource source = new DOMSource(jsdlJobDefinitionDocument);
validateXML(source);
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
xmlString = result.getWriter().toString();
} catch (Exception e) {
e.printStackTrace();
}
return xmlString;
}
private static Document getJSDLJobDefinitionDocument() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (Exception e) {
e.printStackTrace();
}
DOMImplementation domImpl = builder.getDOMImplementation();
Document theDocument = domImpl.createDocument(JSDL_SCHEMA_URL, "JobDefinition", null);
return theDocument;
}
private static void validateXML(DOMSource source) {
try {
URL schemaFile = new URL(JSDL_SCHEMA_URL);
Sche maFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
DOMResult result = new DOMResult();
validator.validate(source, result);
System.out.println("is valid");
} catch (Exception e) {
e.printStackTrace();
}
}
}
it spits out a somewhat odd message:
org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'JobDescription'. One of '{"http://schemas.ggf.org/jsdl/2005/11/jsdl":JobDescription}' is expected.
Where am I going wrong here?
Thanks a lot
i have installed open cms on my local machine and it perfectly works fine.
But in order to work it corre,ty it is mentioned that i have to modify the my.ini file and set max_alllowed_packed site to 32
I have done it and it works perfectly fine
but can i modify this file if i use a third party hosting provider for tomcat and mysql??
I have created a servlet which displays a form having some fields and a submit button and also created a web service having methods which are needed in my servlet.
I have deployed the web service on Tomcat 5.5.9/Axis and servlet web application on Tomcat ( same instance of Tomcat) using eclipse. Since one is web service and other is web application both are running on separate instances of tomcat, so when i run them separately i.e servlet without the call to web service and a client that access that webservice it works fine but when i integrate them both i get a error like
exception: javax.servlet.ServletException
I would like to call the web service and return the result when i press the button
Please advice me on how to implement that.
Hey all!
For part of a project I'm working on I am implementing a RTPpacket where I have to fill the header array of byte with RTP header fields.
//size of the RTP header:
static int HEADER_SIZE = 12; // bytes
//Fields that compose the RTP header
public int Version; // 2 bits
public int Padding; // 1 bit
public int Extension; // 1 bit
public int CC; // 4 bits
public int Marker; // 1 bit
public int PayloadType; // 7 bits
public int SequenceNumber; // 16 bits
public int TimeStamp; // 32 bits
public int Ssrc; // 32 bits
//Bitstream of the RTP header
public byte[] header = new byte[ HEADER_SIZE ];
This was my approach:
/*
* bits 0-1: Version
* bit 2: Padding
* bit 3: Extension
* bits 4-7: CC
*/
header[0] = new Integer( (Version << 6)|(Padding << 5)|(Extension << 6)|CC ).byteValue();
/*
* bit 0: Marker
* bits 1-7: PayloadType
*/
header[1] = new Integer( (Marker << 7)|PayloadType ).byteValue();
/* SequenceNumber takes 2 bytes = 16 bits */
header[2] = new Integer( SequenceNumber >> 8 ).byteValue();
header[3] = new Integer( SequenceNumber ).byteValue();
/* TimeStamp takes 4 bytes = 32 bits */
for ( int i = 0; i < 4; i++ )
header[7-i] = new Integer( TimeStamp >> (8*i) ).byteValue();
/* Ssrc takes 4 bytes = 32 bits */
for ( int i = 0; i < 4; i++ )
header[11-i] = new Integer( Ssrc >> (8*i) ).byteValue();
Any other, maybe 'better' ways to do this?