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 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!
I am trying to create a database of users with connection between users (friends list).
There are 2 main tables: UserEntity (main field id) and FriendEntity with fields:
- initiatorId - id of user who initiated the friendship
- friendId - id of user who has been invited.
Now I am trying to fetch all friends of one particular user and encountered some problems with using subqueries in JDO here.
Logically the query should be something like this:
SQL: SELECT * FROM UserEntity WHERE EXISTS (SELECT * FORM FriendEntity WHERE (initiatorId == UserEntity.id && friendId == userId) || (friendId == UserEntity.id && initiatorId == userId))
or SELECT * FROM UserEntity WHERE userId IN (SELECT * FROM FriendEntity WHERE initiatorId == UserEntity.id) OR userId IN (SELECT * FROM FriendEntity WHERE friendId == UserEntity.id)
So to replicate the last query in JDOQL, I tried to do the following:
Query friendQuery = pm.newQuery(FriendEntity.class);
friendQuery.setFilter("initiatorId == uidParam");
friendQuery.setResult("friendId");
Query initiatorQuery = pm.newQuery(FriendEntity.class);
initiatorQuery.setFilter("friendId == uidParam");
initiatorQuery.setResult("initiatorId");
Query query = pm.newQuery(UserEntity.class);
query.setFilter("initiatorQuery.contains(id) || friendQuery.contains(id)");
query.addSubquery(initiatorQuery, "List initiatorQuery", null, "String uidParam");
query.addSubquery(friendQuery, "List friendQuery", null, "String uidParam");
query.declareParameters("String uidParam");
List<UserEntity> friends = (List<UserEntity>) query.execute(userId);
In result I get the following error:
Unsupported method while parsing expression.
Could anyone help with this query please?
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 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
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?
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.
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.
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! :)
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
<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]");
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
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 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.
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??
Recently i've found myself writing a lot of methods with what i can only think to call debugging scaffolding. Here's an example:
public static void printArray (String[] array, boolean bug)
{
for (int i = 0; i<array.lenght; i++)
{
if (bug) System.out.print (i) ; //this line is what i'm calling the debugging scaffolding i guess.
System.out.println(array[i]) ;
}
}
in this method if i set bug to true, wherever its being called from maybe by some kind of user imput, then i get the special debugging text to let me know what index the string being printed as at just in case i needed to know for the sake of my debugging (pretend a state of affairs exists where its helpful).
All of my questions more or less boil down to the question: is this a good idea? but with a tad bit more objectivity:
Is this an effective way to test my
methods and debug them? i mean effective in terms of efficiency and not messing up my code.
Is it acceptable to leave the if
(bug) stuff ; code in place after
i've got my method up and working?
(if a definition of "acceptability"
is needed to make this question
objective then use "is not a matter
of programing controversy such as
ommiting brackets in an if(boolean)
with only one line after it, though
if you've got something better go
ahead and use your definition i won't
mind)
Is there a more effective way to
accomplish the gole of making
debugging easier than what i'm doing?
Anything you know i mean to ask but
that i have forgotten too (as much
information as makes sense is
appreciated).
I'm trying to make a program that uploads a image to a webserver that accepts multipart file-uploads.
More specificly i want to make a http POST request to http://iqs.me that sends a file in the variable "pic".
I've made a lot of tries but i don't know if i've even been close. The hardest part seems to be to get a HttpURLConnection to make a request of the type POST. The response i get looks like it makes a GET.
(And i want to do this without any third party libs)
UPDATE: non-working code goes here (no errors but doesn't seem to do a POST):
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = "myScreenShot.png";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://iqs.local.com/index.php";
try{
FileInputStream fileInputStream = new FileInputStream( new File(exsistingFileName) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"pic\";" + " filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
}catch (MalformedURLException ex){
System.out.println("Error:"+ex);
}catch (IOException ioe){
System.out.println("Error:"+ioe);
}
try{
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null){
System.out.println(str);
}
inStream.close();
}catch (IOException ioex){
System.out.println("Error: "+ioex);
}
Hello!
I'm referring to this Nimbus reference.
I tried to set global Font to be slightly larger:
UIManager.put("defaultFont", new Font(Font.SANS_SERIF, 0, 16));
...works only for the menu but nothing else (buttons, labels).
I tried to change labels and buttons fonts with
UIManager.put("Button.font", new Font(Font.SANS_SERIF, 0, 16));
UIManager.put("Label.font", new Font(Font.SANS_SERIF, 0, 16));
but the font remains.
The only thing that worked for me was deriving a font:
someButton.setFont(someButton.getFont().deriveFont(16f));
But this is not an option, since this must be done for each
element manually.
Note, that deriving a font for UIManager doesn't work either:
UIManager.put("Label.font",
UIManager.getFont("Label.font").deriveFont(16f));
I tested everything under Linux and Windows: same behavior.
I just can't understand how an API can be so messy. If a method is called
setFont(..) then I expect it to set the font. If this method fails to
set the font in any thinkable circumstances, then it should be deprecated.
EDIT:
The problem not only applies to Nimbus, but also to the default LAF.
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?