Hi I was wondering if someone could help me with this problem.
Thanks!!
Show how to use a stack S and a queue Q to generate all possible subsets of a set nonrecursively.
I have a class Foo which overrides equals() and hashCode() properly.
I would like to also would like to use a HashSet<Foo> to keep track of "canonical values" e.g. I have a class that I would like to write like this, so that if I have two separate objects that are equivalent I can coalesce them into references to the same object:
class Canonicalizer<T>
{
final private Set<T> values = new HashSet<T>();
public T findCanonicalValue(T value)
{
T canonical = this.values.get(value);
if (canonical == null)
{
// not in the set, so put it there for the future
this.values.add(value);
return value;
}
else
{
return canonical;
}
}
}
except that Set doesn't have a "get" method that would return the actual value stored in the set, just the "contains" method that returns true or false. (I guess that it assumes that if you have an object that is equal to a separate object in the set, you don't need to retrieve the one in the set)
Is there a convenient way to do this? The only other thing I can think of is to use a map and a list:
class Canonicalizer<T>
{
// warning: neglects concurrency issues
final private Map<T, Integer> valueIndex = new HashMap<T, Integer>();
final private List<T> values = new ArrayList<T>();
public T findCanonicalValue(T value)
{
Integer i = this.valueIndex.get(value);
if (i == null)
{
// not in the set, so put it there for the future
i = this.values.size();
this.values.add(value);
this.valueIndex.put(value, i);
return value;
}
else
{
// in the set
return this.values.get(i);
}
}
}
I am trying to get the KeyListener working for Blackberry, but none of the Dialogs pop up indicating that a key has been pressed (see code below, each action has a dialog popup in them).
Any ideas on what i might be doing wrong?
public class CityInfo extends UiApplication implements KeyListener
{
static CityInfo application;
public static void main(String[] args)
{
//create a new instance of the application
//and start the application on the event thread
application.enterEventDispatcher();
}
public CityInfo()
{
//display a new screen
application = new CityInfo();
pushScreen(new WorkflowDisplayScreen());
this.addKeyListener(this);
}
public boolean keyChar(char arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
Dialog.alert("key pressed : " + arg0);
return true;
}
public boolean keyDown(int keycode, int time) {
// TODO Auto-generated method stub
Dialog.alert("keyDown : " + keycode);
return false;
}
public boolean keyRepeat(int keycode, int time) {
// TODO Auto-generated method stub
Dialog.alert("keyRepeat : " + keycode);
return false;
}
public boolean keyStatus(int keycode, int time) {
// TODO Auto-generated method stub
Dialog.alert("keyStatus : " + keycode);
return false;
}
public boolean keyUp(int keycode, int time) {
Dialog.alert("keyUp : " + keycode);
// TODO Auto-generated method stub
return false;
}
}
I also tried implementing keyChar on the MainScreen class but that did not yield any results either.
Consider this line:
if (object.getAttribute("someAttr").equals("true")) { // ....
Obviously this line is a potential bug, the attribute might be null and we will get a NullPointerException. So we need to refactor it to one of two choices:
First option:
if ("true".equals(object.getAttribute("someAttr"))) { // ....
Second option:
String attr = object.getAttribute("someAttr");
if (attr != null) {
if (attr.equals("true")) { // ....
The first option is awkward to read but more concise, while the second one is clear in intent, but verbose.
Which option do you prefer in terms of readability?
If I have a try/catch block with returns inside it, will the finally block be called?
For example:
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println "i don't know if this will get printed out."
}
I know I can just type this in an see what happens (which is what I'm about to do, actually) but when I googled for answers nothing came up, so I figured I'd throw this up as a question.
Thanks!
I'm trying to zip a large number of pdf files (stored as BLOBs in the DB) and then return the zip as an attachment to the user.
What's the best way to do this without running into memory issues?
Another note: I actually need to merge some PDFs prior to adding them to the ZipOutputStream. Therefore, a couple PDFs will need to be stored in memory at a time.
I assume it would be best to then store them as temporary files on the server before zipping them all?
type first integer , type second integer, , program repeatedly outputs the second value of the number of times indicated by the first value. Example use inputs 4 and 2, 222 2 displayed. another example user inputs 3 and 8 , 88 8 displayed
Hy ,what i`m trying to do is something like this:
private class aClass
{
private ArrayList idProd;
aClass(ArrayList prd)
{
this.idProd=new ArrayList(prd);
}
public ArrayList getIdProd()
{
return this.idProd;
}
}
So if i have multiple instances of ArrayLIst (st1 ,st2 ,st3) and I want to make new objects of aClass :
{
aClass obj1,obj2,obj3;
obj1=new aClass(st1);
obj2=new aClass(st2);
obj3=new aClass(st3);
}why all of the aClass objects will return st3 if I access the method getIdProd() for each of them(obj1..obj3)? is an arraylist as a instance variable automatically declared static?
Hi,
I know how to use Ant to copy files and folders but what I'm interested in is if, and how, I can have the javac task copy the same sources it's compiling to the output directory.
Basically, it's very similar to the option to include your sources in the jar task.
Thanks in advance,
Ittai
I know this question has be asked before generic comes out. Array does win out a bit given Array enforces the return type, it's more type-safe.
But now, with latest JDK 7, every time when I design this type of APIs:
public String[] getElements(String type)
vs
public List<String> getElements(String type)
I am always struggling to think of some good reasons to return A Collection over An Array or another way around. What's the best practice when it comes to the case of choosing String[] or List as the API's return type? Or it's courses for horses.
I don't have a special case in my mind, I am more looking for a generic pros/cons comparison.
I want a simple class that implements a fixed-size circular buffer. It should be efficient, easy on the eyes, generically typed.
EDIT: It need not be MT-capable, for now. I can always add a lock later, it won't be high-concurrency in any case.
Methods should be: .Add and I guess .List, where I retrieve all the entries. On second thought, Retrieval I think should be done via an indexer. At any moment I will want to be able to retrieve any element in the buffer by index. But keep in mind that from one moment to the next Element[n] may be different, as the Circular buffer fills up and rolls over.
This isn't a stack, it's a circular buffer. Regarding "overflow": I would expect internally there would be an array holding the items, and over time the head and tail of the buffer will rotate around that fixed array. But that should be invisible from the user. There should be no externally-detectable "overflow" event or behavior.
This is not a school assignment - it is most commonly going to be used for a MRU cache or a fixed-size transaction or event log.
Hello,
I want to optimize this code:
InputStream is = rp.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String text = "";
String aux = "";
while ((aux = reader.readLine()) != null) {
text += aux;
}
The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above.
I need to spend as little time as possible.
Thank you
about = new JMenuItem("About");
about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A((Toolkit.getDefaultToolkit().getMenuShortcutMask()))));
JMenu help = new JMenu("Help");
help.add(about);
I was wondering why my aaccelerators were not working. I am running this in snow leopard with JavaSe-1.6 VM. They do work if I pull the menu down then try the key sequence. Thanks
Im a bit unsure and have to get advice.
I have the:
public class MyApp extends JFrame{
And from there i do;
MyServer = new MyServer (this);
MyServer.execute();
MyServer is a:
public class MyServer extends SwingWorker<String, Object> {
MyServer is doing listen_socket.accept() in the doInBackground()
and on connection it create a new
class Connection implements Runnable {
I have the belove DbHelper that are a singleton.
It holds an Sqlite connected. Im initiating it in the above MyApp
and passing references all the way in to my runnable:
class Connection implements Runnable {
My question is what will happen if there are two simultaneous read or `write?
My thought here was the all methods in the singleton are synchronized and
would put all calls in the queue waiting to get a lock on the synchronized method.
Will this work or what can i change?
public final class DbHelper {
private boolean initalized = false;
private String HomePath = "";
private File DBFile;
private static final String SYSTEM_TABLE = "systemtable";
Connection con = null;
private Statement stmt;
private static final ContentProviderHelper instance = new ContentProviderHelper ();
public static ContentProviderHelper getInstance() {
return instance;
}
private DbHelper () {
if (!initalized)
{
initDB();
initalized = true;
}
}
private void initDB()
{
DBFile = locateDBFile();
try {
Class.forName("org.sqlite.JDBC");
// create a database connection
con = DriverManager.getConnection("jdbc:sqlite:J:/workspace/workComputer/user_ptpp");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private File locateDBFile()
{
File f = null;
try{
HomePath = System.getProperty("user.dir");
System.out.println("HomePath: " + HomePath);
f = new File(HomePath + "/user_ptpp");
if (f.canRead())
return f;
else
{
boolean success = f.createNewFile();
if (success) {
System.out.println("File did not exist and was created " + HomePath);
// File did not exist and was created
} else {
System.out.println("File already exists " + HomePath);
// File already exists
}
}
} catch (IOException e) {
System.out.println("Maybe try a new directory. " + HomePath);
//Maybe try a new directory.
}
return f;
}
public String getHomePath()
{
return HomePath;
}
private synchronized String getDate(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public synchronized String getSelectedSystemTableColumn( String column) {
String query = "select "+ column + " from " + SYSTEM_TABLE ;
try {
stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String value = rs.getString(column);
if(value == null || value == "")
return "";
else
return value;
}
} catch (SQLException e ) {
e.printStackTrace();
return "";
} finally {
}
return "";
}
}
I want to create a program for generating the series for the given base-n. ,
for example if my input is 2,then series shuould be, 00,01,10,11,etc.,(binary)
if my input is 10,then series shuould be,1,2,3,4,5,etc.,(decimal)
is there any general mechanism to find these numbers so that I can program for base-n.,
I need to upload a .csv file and save the records in bigtable.
My application successfully parse 200 the records in the csv files and save to table.
Here is my code to save the data.
for (int i=0;i<lines.length -1;i++) //lines hold total records in csv file
{
String line = lines[i];
//The record have 3 columns integer,integer,Text
if(line.length() > 15)
{
int n = line.indexOf(",");
if (n>0)
{
int ID = lInteger.parseInt(ine.substring(0,n));
int n1 = line.indexOf(",", n + 2);
if(n1 > n)
{
int Col1 = Integer.parseInt(line.substring(n + 1, n1));
String Col2 = line.substring(n1 + 1);
myTable uu = new myTable();
uu.setId(ID);
uu.setCol1(MobNo);
Text t = new Text(Col2);
uu.setCol2(t);
PersistenceManager pm = PMF.get().getPersistenceManager();
pm.makePersistent(uu);
pm.close();
}
}
}
}
But when no of records grow it gives timeout error.
The csv file may have upto 800 records.
Is it possible to do that in App-Engine?
(something like batch update)
This is my code...
class info{
public static void main (String[]args) throws IOException{
char gen;
while(true) { //problem occurs with this while
System.out.print("\nENTER YOUR GENDER (M/F) : ");
gen=(char)System.in.read();
if(gen=='M' || gen=='F' || gen=='m' || gen=='f'){
break;
}
}
System.out.println("\nGENDER = "+gen);
}
}
This is my output...
ENTER YOUR GENDER (M/F) : h
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) : m
GENDER = m
Could someone please help me understand why it is asking for the gender so many times.
A JSpinner is used to store a number in my application (with a SpinnerNumberModel).
As expected, the spinner doesn't allow invalid characters (letters, symbols, etc.) to be stored. However, those characters do appear in the spinner component when I type them in. As soon as I switch the focus to another component, they disappear.
Is there a way to prevent invalid characters from appearing in the spinner?
Hello,
what behaviour can I expect when I run this code:
do while(testA) {
// do stuff
} while(testB);
Will it behave like:
do {
while(testA) {
// do stuff
}
} while(testB);
Or:
if(testA) {
do {
// do stuff
} while(testA && testB);
}
Or something totally unexpected?
I ask this question because I think this is quite ambiguous, and for other people searching on this topic, not because I am lazy to test it out.
Hello Folks
I have this new requirement to develop a software which is a large scale image up loader in a web application. I was able to do the same using swing contains several feature like drag and drop, progress bar, remove file / files , modify, limit file size, verify file information, timer, verify at run time ..and its a very powerful tool which uploads images.
I would like to do the same in web based app, like user selects 200 images process it and click upload and it should start uploading, like to know any feasible frameworks or any API's which help me do this faster and achieve the same kind of functionality. Please point me in correct direction.
-PD
What I mean is like servers on video games. You can run an application and it will set up a server on your computer with an IP and a port.
For example, how would you make an application where one host application sets up a thing where it has an IP and a port, and another computer that has access to the internet as well can type in the IP and port and it would be able to communicate with the host? I mean simple communication, like sending a boolean or String.
And would there be any security problems that would be needed to fix?
I have
public class QuantityType {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String type;
}
I am trying to setup a query to get the right QuantityType by it's key
gql = "select * from QuantityType where __key__='aght52oobW1hIHTWVzc2FnZRiyAQw'";
But its not working because
BadFilterError: BadFilterError: invalid filter: key filter value must be a Key; received aght52oobW1hIHTWVzc2FnZRiyAQw (a str).
I have also tried to use
gql = "select * from QuantityType where __key__=='" + KeyFactory.stringToKey(qTypeKey)+"'";
but it's now working..
How can I get a specific object from my datastore by it's key?
I want to get a list of dates between start and end date.If i give the start and end date means, it give the result as the list of all dates including the start and end date.
Thanks in advance.
Hi,
I am using simple date format to allow users to specify which time zone they are sending data in:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,z");
This works fine:
e.g.
df.parse("2009-05-16 11:07:41,GMT");
However, if someone is always sending time in London time (i.e. taking into account daylight savings), what would be the approriate time zone String to add?
e.g. this doesnt work:
df.parse("2009-05-16 11:07:41,Europe/London");
Thanks.