Write: close the BufferWriter as well as FileWriter
Code:
//TODO
Wednesday, June 5, 2013
Notes 5 June 2013
SQL
start;
rollback;
commit;
core dump
used for dbx
linux
ls -ltr
C++ string empty
don't use =="' || ==NULL
use str.length()<=0;
Tuesday, June 4, 2013
stringstream to cout
std::stringstream ss;
unsigned long long ll = (unsigned long long)&ss;
cout << ll;
That said when you want to cout a stringstream you should use the str() function as follows:
cout << ss.str();
from DB to C++ util::StringTokenizer
void ADEngine::updateConfigs(map<string, string>& prefMap){
ADYardConfig* config = this->getYardConfig();
///< _deleteShiftCntrI
bool deleteShiftCntrI = DEFAULT_DELETE_SHIFT_CNTR; ///< default value
if(prefMap.find(DELETESHIFTCNTR)!=prefMap.end()){
deleteShiftCntrI = atoi(prefMap[DELETESHIFTCNTR].data());
}
///< _excludeCategory:set<string>
string excludeCategories = DEFAULT_EXCLUDE_CATEGORY_C;
if (prefMap.find(EXCLUDECATEGORYC) != prefMap.end()){
excludeCategories = prefMap[EXCLUDECATEGORYC];
}
util::StringTokenizer stringTokenizer(excludeCategories,",");
while(stringTokenizer.hasMoreTokens()){
config->addExcludeCategory(stringTokenizer.nextToken());
}
}
ADYardConfig* config = this->getYardConfig();
///< _deleteShiftCntrI
bool deleteShiftCntrI = DEFAULT_DELETE_SHIFT_CNTR; ///< default value
if(prefMap.find(DELETESHIFTCNTR)!=prefMap.end()){
deleteShiftCntrI = atoi(prefMap[DELETESHIFTCNTR].data());
}
///< _excludeCategory:set<string>
string excludeCategories = DEFAULT_EXCLUDE_CATEGORY_C;
if (prefMap.find(EXCLUDECATEGORYC) != prefMap.end()){
excludeCategories = prefMap[EXCLUDECATEGORYC];
}
util::StringTokenizer stringTokenizer(excludeCategories,",");
while(stringTokenizer.hasMoreTokens()){
config->addExcludeCategory(stringTokenizer.nextToken());
}
}
Monday, June 3, 2013
Thinking in Java
Cleanup: finalization (finialize()) and garbage collection
- Your object might not get garbage collected
- Garbage collection is not destruction
- Garbage collection is only about memory
Force garbage collection:
System.gc();
use of finalize:
protected void finalize(){
if(some conditions)
errorMessage;
}
Array
int[] a;
Random rand = new Random(47);
a = new int[rand.nextInt(20)];
Inner Class
inner class and surrounding class
public class Parcel1 {
class Contents { //protected, also can be + -;
private int attribute;
public int method() { return 0; }
}
OuterClassName.InnerClassName
Out.Inner inner = out.getInner();
In addition, inner classes have access rights (link) to all the elements in the enclosing class. (different from C++ which does not have links)
done
Saturday, June 1, 2013
CSS Collection 1
Web开发技术每年都在革新,浏览器已逐渐支持CSS3特性,并且网站设计师和前端开发者普遍采用这种新技术进行设计与开发。但仍然有一些开发者迷恋着一些CSS2代码。
本文将分享20段非常专业的CSS2/CSS3代码供大家使用,你可以把它们保存在IDE里、或者存储在CSS文档里,这些代码片段绝对会给你带来意外的惊喜。
1. CSS Resets
网络上关于CSS重置的代码非常多。本段代码是根据Eric Meyer’s reset codes进行改编的,里面包含一点响应式图片和所有核心元素的边界框设置,这样就可以保持页边距和填充可以很好地对齐。
CSS Collection 2
http://www.csdn.net/article/2013-05-29/2815470-css-snippets-for-designers
源码地址: http://css-tricks.com/snippets/css/fancy-ampersand/
上周,研发频道发表了一篇“ Web开发者不容错过的20段CSS代码”,大家一致觉得很实用。该文是笔者对后30个的翻译,希望对大家有帮助。
1.花式连字符(&)
这个类应该在span元素里使用,并且里面包括&字符。它使用经典的serif字体和斜体来增强&符号。
1
2
3
4
5
| .amp { font-family: Baskerville, 'Goudy Old Style', Palatino, 'Book Antiqua', serif; font-style: italic; font-weight: normal;} |
Thursday, May 30, 2013
Wednesday, May 29, 2013
20 core java interview questions
Top 20 Core Java Interview questions answers asked in Investment Bank
JP Morgan, Morgan Stanley, Barclays or Goldman Sachs.
Banks mostly asked core Java interview questions from multi-threading, collection, serialization, coding and OOPS design principles.
@TODO programming interview questions 30 Java C/C++
- (Diamond Problem)
- (multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity.)
1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal
2)String has been widely used as parameter for many Java classes. In case, if String is not immutable, this would lead serious security threat
2)String has been widely used as parameter for many Java classes. In case, if String is not immutable, this would lead serious security threat
3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java
4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String,
5)The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.
4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String,
5)The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.
Security and String pool being primary reason of making String immutable
Core Java Interview Questions Answers in Finance domain
@TODO
String s = new String("Test");
does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.
12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.
13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java
14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here How HashMap works in Java for detailed explanation.
15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)
16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.
18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.
19. Give a simplest way to find out the time a method takes for execution without using any profiling tool?
this questions is suggested by @Mohit
Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code…
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println (“Time taken for execution is ” + (end – start));
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing
Core Java Interview Questions Answers in Finance domain
1. What is immutable object? Can you write immutable object?
Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.
2. Does all property of immutable object needs to be final?
Not necessary as stated above you can achieve same functionality by making member as non final but private and not modifying them except in constructor.
3. What is the difference between creating String as new() and literal?
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.
does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.
4. How does substring () inside String works?
Another good Java interview question, I think answer is not sufficient but here it is “Substring creates new object out of source string by taking a portion of original string”. see my post How SubString works in Java for detailed answer of this Java question.
5. Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java to learn more about equals.
6. Where does these two method comes in picture during get operation?
This core Java interview question is follow-up of previous Java question and candidate should know that once you mention hashCode, people are most likely ask How its used in HashMap. See How HashMap works in Java for detailed explanation.
7. How do you handle error condition while writing stored procedure or accessing stored procedure from java?
This is one of the tough Java interview question and its open for all, my friend didn't know the answer so he didn't mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.
8. What is difference between Executor.submit() and Executer.execute() method ?
This Java interview question is from my list of Top 15 Java multi-threading question answers, Its getting popular day by day because of huge demand of Java developer with good concurrency skill. Answer of this Java interview question is that former returns an object of Futurewhich can be used to find result from worker thread)
By the way @vinit Saini suggested a very good point related to this core Java interview question
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.
9. What is the difference between factory and abstract factory pattern?
This Java interview question is from my list of 20 Java design pattern interview question and its open for all of you to answer.
@Raj suggestedAbstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended byAutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.
You can also refer What is Factory method design pattern in Java to know more details.
10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy. see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and double checked locking which is purpose of this Java interview question.
11. Can you write critical section code for singleton?
This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe. check 10 Interview questions on Singleton Pattern in Java for more details and questions answers
12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.
13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java
14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here How HashMap works in Java for detailed explanation.
15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)
16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.
18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.
19. Give a simplest way to find out the time a method takes for execution without using any profiling tool?
this questions is suggested by @Mohit
Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code…
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println (“Time taken for execution is ” + (end – start));
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing
Read more: http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html#ixzz2Uf9xE7zL
C++ String Tokenizer
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
std::string::npos
static const size_t npos = -1;Maximum value for size_tnpos is a static member constant value with the greatest possible value for an element of type size_t. This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string". As a return value, it is usually used to indicate no matches. This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type. input: 1 2 3 4vector<int> a; string line; getline(cin, line); size_t pos = 0; string token; string delimiter = " "; while ((pos = line.find(delimiter))!=std::string::npos) { token = line.substr(0, pos); a.push_back(atoi(token.c_str())); line.erase(0, pos + delimiter.length()); } a.push_back(atoi(line.c_str()));
Java Template
import java.util.Scanner;
import java.util.Formatter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class XXXXXX{
/**
* @param args the command line arguments
*/
public static void main (String [] args) throws IOException {
Scanner in = new Scanner(new File("./src/input.txt")); // file input
Formatter out = new Formatter(new File("./src/output.txt")); // file output
ArrayList<Integer> a = new ArrayList<Integer>();
while(in.hasNext()){
a.add(in.nextInt());
}
out.format("%s\n", a.toString()); // format() has the same syntax as printf()
out.close(); // flush the output and close the output file
System.exit(0); // likely needed in USACO
}
}
import java.util.Formatter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class XXXXXX{
/**
* @param args the command line arguments
*/
public static void main (String [] args) throws IOException {
Scanner in = new Scanner(new File("./src/input.txt")); // file input
Formatter out = new Formatter(new File("./src/output.txt")); // file output
ArrayList<Integer> a = new ArrayList<Integer>();
while(in.hasNext()){
a.add(in.nextInt());
}
out.format("%s\n", a.toString()); // format() has the same syntax as printf()
out.close(); // flush the output and close the output file
System.exit(0); // likely needed in USACO
}
}
Tuesday, May 28, 2013
JPA Examples
https://glassfish.java.net/javaee5/persistence/persistence-example.html
Note that the association must be set on both sides of the relationship: on the customer side for the orders to be persisted when transaction commits, and on the order side because it is the owning side:
Now let's verify that the orders were also created by navigating from the Customer.
You can print the orders, but we'll just check the size:
Note that merge() is not a void operation. It returns back a managed copy of the argument (and its related objects). Only this copy can be used for EntityManager operations.
The rest of the configuration of the database and the persistence is on the webpage (NetBeans, GlassFish)
done
Part 2
https://schuchert.wikispaces.com/JPA+Tutorial+1+-+Getting+Started
| CUSTOMER |
| ID |
| NAME |
| ORDER_TABLE |
| ORDER_ID |
| SHIPPING_ADDRESS |
| CUSTOMER_ID |
@Entity
public class Customer {
private int id;
private String name;
private Collection<Order> orders;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade=ALL, mappedBy="customer")
public Collection<Order> getOrders() {
return orders;
}
public void setOrders(Collection<Order> newValue) {
this.orders = newValue;
}
}
@Entity
@Table(name="ORDER_TABLE")
public class Order {
private int id;
private String address;
private Customer customer;
@Id
@Column(name="ORDER_ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="SHIPPING_ADDRESS")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@ManyToOne()
@JoinColumn(name="CUSTOMER_ID")
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}Persisting POJO Entities
Now, let's create new instances, set up the relationships and persist all of them together using the CASCADE option that we set on the Customer entity. This code must be executed in a context of an active transaction.
// Create new customer
Customer customer0 = new Customer();
customer0.setId(1);
customer0.setName("Joe Smith");
// Persist the customer
em.persist(customer0);
// Create 2 orders
Order order1 = new Order();
order1.setId(100);
order1.setAddress("123 Main St. Anytown, USA");
Order order2 = new Order();
order2.setId(200);
order2.setAddress("567 1st St. Random City, USA");
// Associate orders with the customer.Note that the association must be set on both sides of the relationship: on the customer side for the orders to be persisted when transaction commits, and on the order side because it is the owning side:
customer0.getOrders().add(order1);
order1.setCustomer(customer0);
customer0.getOrders().add(order2);
order2.setCustomer(customer0);When this transaction commits, all three entities will be persisted in the database.Query and Navigation
We'll use a new EntityManager to do the query, but will execute the query without an active transaction:// Create new EntityManager
em = emf.createEntityManager();
Query q = em.createQuery("select c from Customer c where c.name = :name");
q.setParameter("name", "Joe Smith");
Our query is supposed to return a single customer, so we will use the Query method getSingleResult() to execute the query. This method would throw an exception if there is no or more than one matching customers.
Customer c = (Customer)q.getSingleResult();Now let's verify that the orders were also created by navigating from the Customer.
You can print the orders, but we'll just check the size:
Collection<Order> orders = c.getOrders();
if (orders == null || orders.size() != 2) {
throw new RuntimeException("Unexpected number of orders: "
+ ((orders == null)? "null" : "" + orders.size()));
}Merge and Removal of Persistent Instances
To remove an instance, it must be managed by this EntityManager. The code below uses a customer 'c' that had been detached from its persistence context. Removal of the Customer also removes related orders because of the CASCADE option set on the corresponding relationship. This code must be executed in a context of an active transaction. // Merge the customer to the new persistence context
Customer c0 = em.merge(c); //step1Note that merge() is not a void operation. It returns back a managed copy of the argument (and its related objects). Only this copy can be used for EntityManager operations.
// Delete all records
em.remove(c0); //step2The rest of the configuration of the database and the persistence is on the webpage (NetBeans, GlassFish)
done
Part 2
https://schuchert.wikispaces.com/JPA+Tutorial+1+-+Getting+Started
package entity; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; public class PersonTest { private EntityManagerFactory emf; private EntityManager em; @Before public void initEmfAndEm() { BasicConfigurator.configure(); Logger.getLogger("org").setLevel(Level.ERROR); emf = Persistence.createEntityManagerFactory("examplePersistenceUnit"); em = emf.createEntityManager(); } @After public void cleanup() { em.close(); } @Test public void emptyTest() { } }Person.java
package entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Person { @Id @GeneratedValue private int id; private String firstName; private char middleInitial; private String lastName; private String streetAddress1; private String streetAddress2; private String city; private String state; private String zip; public Person() { } public Person(final String fn, final char mi, final String ln, final String sa1, final String sa2, final String city, final String state, final String zip) { setFirstName(fn); setMiddleInitial(mi); setLastName(ln); setStreetAddress1(sa1); setStreetAddress2(sa2); setCity(city); setState(state); setZip(zip); }
then getters and setters
}
Update persistence.xml
Inserting and Querying
Add an Embedded Entity
When we created Person we directly included address information into them. This is alright, but what if we want to use Address in another class? Let's introduce a new entity, Address, and make it embedded. This means its fields will end up as columns in the table of the entity that contains it.Add an Entity with a One to Many Relationship
@OneToMany
private Collection<Person> employees;
Make a Relationship Bi-Directional
@ManyToOne(optional = true) private Company job; public Company getJob() { return job; } public void setJob(Company job) { this.job = job; } // ...
@OneToMany(mappedBy = "job") private Collection<Person> employees;
// update this method //Referential Integrity public void hire(final Person p) { getEmployees().add(p); p.setJob(this); } // update this method public void fire(final Person p) { getEmployees().remove(p); p.setJob(null); }done
Subscribe to:
Posts (Atom)

