Tips on Using Eclipse Effectively

Tips on Using Eclipse Effectively
Useful Eclipse Shortcut Keys



ALT + Left/Right ArrowMove backward/forward in the editor navigation history
CTRL+OShow the quick outline for the editor input
CTRL+KFind next item, no need to ctrl+f, type some words, then search
CTRL+1Activates the quick fix
CTRL+SHIFT+TOpen Type
CTRL+SPACEContent Assist
ALT+/Word completion
ALR+SHIFT+RRename the selected element
ALT+SHIFT+MExtract statements into a new method and use the new method
Ctrl + LGo To Line
CTRL+TShow quick hierarchy of the selected element
CTRL + SHIFT + FFormat code
CTRL+SHIFT+OOrganize imports
Ctrl+Shift+XChange the selection to upper case, useful in declare final variable
Ctrl+Shift+YChange the selection to lower case
Ctrl+Shift+HOpen a type in the type hierarchy view
Ctrl+Shift+SSave all current contents
Ctrl+Shift+WClose all editors
Ctrl+Shift+GSearch for references to the selected element in the workspace
CTRL+EShow a list of all open editors
CTRL + DDelete row
CTRL+MToggle maximize/restore state of active view or editor
Others:
CTRL+SHIFT+U    Shows the Occurrences in File quick menu
Ctrl+Shift+R        Open Resources
CTRL + I               Corrects indentation
Ctrl+M                  Maximize Active View or Editor
Ctrl+Shift+Space
Context Information, If typing a method call with several parameters use this to show the applicable parameter types.
Alt+Left/Right Backward/Forward History
CTRL + I         Corrects indentation
CTL + N            Open new type wizard
CTRL + J           Incremental search
CTRL + SHIFT + L Shows you a list of your currently defined shortcut keys
CTRL+F6          Use to move between open editors
CTRL+F7          Move between views
CTRL+F8          Move between perspectives
To configure the shortcut key, click Window --> Preferences --> General --> Keys


Associate editors with file types:
Window -> Preferences -> General -> Editors -> File Associations

Find: ^\s*\n
Replace with: (empty)



Eclipse plugins:
Code quality:
Checkstyle: http://eclipse-cs.sourceforge.net/update
It is used to enforce Coding Standards in Java Project, such as Naming conventions, Coding problems, Best Practices.


PMD http://pmd.sf.net/eclipse
PMD focuses more on preemptive defect detection.


FindBugs http://findbugs.cs.umd.edu/eclipse/
FindBugs concentrates on detecting potential bugs and performance issues.
Klocwork: http://developer.klocwork.com
Klocwork is aimed at improving software security, quality, and reliability. It is not free, but we can get 30 days free trail. And it is really very cool.


Mylyn: http://www.eclipse.org/mylyn/
Mylyn can integrate with issue management systems such as Bugzilla, and it also provides context management, which can hide much of the detail of projects that is irrelevant to the task at hand.
Mylyn is very helpful, especially your main job is to fix defects, or focus on one component of a big project.


ShellEd: http://sourceforge.net/projects/shelled/
EPIC - Perl Editor and IDE for Eclipse http://e-p-i-c.sf.net/updates
The PyDev Update Site http://pydev.sourceforge.net/updates/
Groovy Eclipse plugin http://dist.codehaus.org/groovy/distributions/update/
Aptana Studio http://update.aptana.com/install/studio/3.2/
http://www.aptana.com


Problem
Recently, I re-downloaded and reinstalled jdk, and Eclipse always shows this error:
'UnsupportedEncodingException: GBK'. After google search, on http://dev.eclipse.org/newslists/news.eclipse.tools/msg30710.html,
I found out this is because I installed a JRE only for US English, and I should choose to download and install Multi-language JRE.

Problem:
When we save file, it may print out the error "Some characters can not be mapped using GBK character encoding".
The solution is to change file encoding to 'utf-8':
Select Window -> Preferences ->General
Select  Workspace , set Text file encoding to 'utf-8'.
Select Content Types, set Default encoding to 'utf-8'

Ignore white space when compare two files in Eclipse IDE
When compare two files in Eclipse, many times lines differ only in white spaces, and we don't want to notice this minor difference.
Solution:
Select Window -> Preference -> Compare/Path, and in 'General' tab, select the checkbox --'Ignore white space'.


Reference:
http://www.javaprogrammingforums.com/eclipse/19-useful-eclipse-shortcut-keys.html
http://www.rossenstoyanchev.org/write/prog/eclipse/eclipse3.html
http://tkramar.blogspot.com/search/label/eclipse
Java Power tools safari online book

Using Trie - Algorithm

When to use trie
- prefix: findByPrefix

- Word search
X. Trie + DFS
LeetCode 212 - Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
https://discuss.leetcode.com/topic/33246/java-15ms-easiest-solution-100-00
public List findWords(char[][] board, String[] words) {
    List res = new ArrayList<>();
    TrieNode root = buildTrie(words);
    for(int i = 0; i < board.length; i++) {
        for(int j = 0; j < board[0].length; j++) {
            dfs(board, i, j, root, res);
        }
    }
    return res;
}

public void dfs(char[][] board, int i, int j, TrieNode p, List res) {
    char c = board[i][j];
    if(c == '#' || p.next[c - 'a'] == null) return;
    p = p.next[c - 'a'];
    if(p.word != null) {   // found one
        res.add(p.word);
        p.word = null;     // de-duplicate
    }

    board[i][j] = '#';
    if(i > 0) dfs(board, i - 1, j ,p, res); 
    if(j > 0) dfs(board, i, j - 1, p, res);
    if(i < board.length - 1) dfs(board, i + 1, j, p, res); 
    if(j < board[0].length - 1) dfs(board, i, j + 1, p, res); 
    board[i][j] = c;
}

public TrieNode buildTrie(String[] words) {
    TrieNode root = new TrieNode();
    for(String w : words) {
        TrieNode p = root;
        for(char c : w.toCharArray()) {
            int i = c - 'a';
            if(p.next[i] == null) p.next[i] = new TrieNode();
            p = p.next[i];
       }
       p.word = w;
    }
    return root;
}

class TrieNode {
    TrieNode[] next = new TrieNode[26];
    String word;
}
https://codesolutiony.wordpress.com/2015/05/20/leetcode-word-search-ii/

LeetCode 425 - Word Squares
Given a set of words (without duplicates), find all word squares you can build from them.

LeetCode 472 - Concatenated Words
Given a list of words, please write a program that returns all concatenated words in the given list of words.

LeetCode 30 - Substring with Concatenation of All Words
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

X. - Sliding window
https://discuss.leetcode.com/topic/6617/an-o-n-solution-with-detailed-explanation/10

LeetCode 30 - Substring with Concatenation of All Words

TODO
LeetCode 336 - Palindrome Pairs
Given a list of unique words. Find all pairs of indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.

LeetCode 421 - Maximum XOR of Two Numbers in an Array
Trie[] children = new Trie[2];
X. https://discuss.leetcode.com/topic/63213/java-o-n-solution-using-bit-manipulation-and-hashmap
O(32n) -> bit by bit

Uber Prepare: Web Address

LeetCode 527 - Word Abbreviation
Given an array of n distinct non-empty strings, you need to generate minimal possible abbreviations for every word following rules.

Airbnb: K Edit Distance
Given a list of word and a target word, output all the words for each the edit distance with the target no greater than k.

Leetcode 211 - Add and Search Word
LeetCode 212 - Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board.

Leetcode 211 - Add and Search Word
Trie: https://discuss.leetcode.com/topic/14030/my-simple-and-clean-java-code

LeetCode 30 - Substring with Concatenation of All Words
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
https://discuss.leetcode.com/topic/6593/accepted-recursive-solution-using-trie-tree
      static class TrieNode {
           int value = 0;
           Map children = new HashMap();
       }

       TrieNode trie;

    // build a trie tree
    public List findSubstring(String S, String[] L) {
        trie = buildTrie(L);
        int length = getTotalLength(L);
        List result = new LinkedList();
        for (int i = 0; i < S.length() - length + 1; i++) {
            if (isSubString(S, i, i + length))
                result.add(i);
        }
        return result;
    }
    
    private int getTotalLength(String[] L) {
        int sum = 0;
        for (String l : L)
            sum += l.length();
        return sum;
    }
    
    private TrieNode buildTrie(String[] L) {
        TrieNode root = new TrieNode();
        for (String l : L)
            addWord(root, l);
        return root;
    }
    
    private void addWord(TrieNode root, String s) {
        TrieNode node = root;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            TrieNode next = node.children.get(c);
            if (next == null) {
                next = new TrieNode();
                node.children.put(c, next);
            }
            node = next;
        }
        node.value++;
    }
    
    private boolean isSubString(String S, int start, int end) {
     if (start == end)
      return true;
        // search in the trie tree
        TrieNode node = trie;
        for (int i = start; i < end; i++) {
            char c = S.charAt(i);
            if (node.children.get(c) == null)
                return false;
            node = node.children.get(c);
            if (node.value > 0) {  // leaf & can be used
                node.value--; // mark as used
                if (isSubString(S, i + 1, end)) {
                    node.value++; // mark as unused
                    return true;
                }
                node.value++; // mark as unused
            }
        }
        return false;
    }
X. Using Suffix Trie
Given a string band an array of smaller strings T, design a method to search b for each small string in T.
https://github.com/careercup/CtCI-6th-Edition/blob/master/Java/Ch%2017.%20Hard/Q17_17_Multi_Search/TrieNode.java
https://github.com/careercup/CtCI-6th-Edition/blob/master/Java/Ch%2017.%20Hard/Q17_17_Multi_Search/QuestionB.java
X. https://github.com/careercup/CtCI-6th-Edition/blob/master/Java/Ch%2017.%20Hard/Q17_17_Multi_Search/QuestionC.java

Trie implementation
http://blog.csdn.net/ljiabin/article/details/45846527
  1. class TrieNode {  
  2.     public TrieNode[] children = new TrieNode[26];  
  3.     public String item = "";        
  4.     public TrieNode() {  
  5.     }  
  6. }  
  7.   
  8. class Trie {  
  9.     private TrieNode root;  
  10.   
  11.     public Trie() {  
  12.         root = new TrieNode();  
  13.     }  
  14.   
  15.     // Inserts a word into the trie.  
  16.     public void insert(String word) {  
  17.         TrieNode node = root;  
  18.         for (char c : word.toCharArray()) {  
  19.             if (node.children[c - 'a'] == null) {  
  20.                 node.children[c - 'a'] = new TrieNode();  
  21.             }  
  22.             node = node.children[c - 'a'];  
  23.         }  
  24.         node.item = word;  
  25.     }  
  26.   
  27.     // Returns if the word is in the trie.  
  28.     public boolean search(String word) {  
  29.         TrieNode node = root;  
  30.         for (char c : word.toCharArray()) {  
  31.             if (node.children[c - 'a'] == nullreturn false;  
  32.             node = node.children[c - 'a'];  
  33.         }  
  34.         return node.item.equals(word);  
  35.     }  
  36.   
  37.     // Returns if there is any word in the trie  
  38.     // that starts with the given prefix.  
  39.     public boolean startsWith(String prefix) {  
  40.         TrieNode node = root;  
  41.         for (char c : prefix.toCharArray()) {  
  42.             if (node.children[c - 'a'] == nullreturn false;  
  43.             node = node.children[c - 'a'];  
  44.         }  
  45.         return true;  
  46.     }  
  47. }  

Advanced Data Structures

PriorityQueue
- Related with greedy algorithm
- Use minQueue to get kth max, maxQueue to get kth min
- merge sort with PQ

Misc
- Remove is O(n)

LeetCode 414 - Third Maximum Number
Use PriorityQueue with HashSet to check duplicate
https://discuss.leetcode.com/topic/63086/java-priorityqueue-o-n-o-1
- TreeSet (not PQ as need call contains)
set.add(num);
if(set.size() > 3) {set.remove(set.first());}
- Maitain state: first, second, third

LeetCode 502 - IPO
find a project with max profit and within current capital capability
- 2 PriorityQueue
        PriorityQueue<int[]> pqCap = new PriorityQueue<>((a, b) -> (a[0] - b[0]));
        PriorityQueue<int[]> pqPro  = new PriorityQueue<>((a, b) -> (b[1] - a[1]));        
        for (int i = 0; i < k; i++) {
            while (!pqCap.isEmpty() && pqCap.peek()[0] <= W) {
                pqPro.add(pqCap.poll());
            }
            W += pqPro.poll()[1];
        }

LeetCode 632 - Smallest Range


LeetCode 630 - Course Schedule III
There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dthday. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.
Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.
    public int scheduleCourse(int[][] courses) {
        Arrays.sort(courses,(a,b)->a[1]-b[1]); //Sort the courses by their deadlines (Greedy! We have to deal with courses with early deadlines first)
        PriorityQueue pq=new PriorityQueue<>((a,b)->b-a);
        int time=0;
        for (int[] c:courses) 
        {
            time+=c[0]; // add current course to a priority queue
            pq.add(c[0]);
            if (time>c[1]) time-=pq.poll(); //If time exceeds, drop the previous course which costs the most time. (That must be the best choice!)
        }        
        return pq.size();
    }

LeetCode 378 - Kth Smallest Element in a Sorted Matrix
- Bisection O(nlogm) while m = max - min
https://discuss.leetcode.com/topic/52868/java-heap-klog-k
    public int kthSmallest(final int[][] matrix, int k) {
        int c = 0;
        PriorityQueue<int[]> queue = new PriorityQueue<>(
            k, (o1, o2) -> matrix[o1[0]][o1[1]] - matrix[o2[0]][o2[1]]);
        queue.offer(new int[] {0, 0});
        while (true) {
            int[] pair = queue.poll();
            if (++c == k) {
                return matrix[pair[0]][pair[1]];
            }
            if (pair[0] == 0 && pair[1] + 1 < matrix[0].length) {
                queue.offer(new int[] {0, pair[1] + 1});
            }
            if (pair[0] + 1 < matrix.length) {
                queue.offer(new int[] {pair[0] + 1, pair[1]});
            }
        }
LeetCode 373 - Find K Pairs with Smallest Sums
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.

Find elements more than K times
Given m sorted lists, find out the elements more than k times. If an element appear more than once in a list, count it only once.
- Use PriorityQueue instead of HashMap to save space

POJ 4302 Holedox Eating
- 2 PriorityQueue

LeetCode 621 - Task Scheduler
- Use Priority Queue
- Calculating Idle slots
LeetCode 358 - Rearrange String k Distance Apart
Rearrange Characters in String With No Adjacent Duplicate Characters

LeetCode 632 - Smallest Range
You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the klists.
- Merge k sorted list

LeetCode 407 - Trapping Rain Water II

Queue
Double Monotonic Queue

Deque q = new ArrayDeque<>();
Deque doubleQueue = new LinkedList<>();

LeetCode 239 - Sliding Window Maximum
- Store index instead of the value
- Only keep promising elements in the deque

LeetCode 102 - Binary Tree Level Order Traversal
queue.offer(root);
while(!queue.isEmpty()){
  for(int i=0; i}

LeetCode 127 - Word Ladder I
- BFS, Two-end BFS
Deque queue = new ArrayDeque();
queue.offer(start);
Set visited

LeetCode 111 - Minimum Depth of Binary Tree

Interval tree
http://www.davismol.net/2016/02/07/data-structures-augmented-interval-tree-to-search-for-interval-overlapping/
- augmented self-balancing bst: low, high, max
- logn: add/Remove(interval), overlapping(x)

Google – Toggle Problem
https://reeestart.wordpress.com/2016/06/24/google-toggle-problem/

Using Multiple Data Structures 
Google – Manager Peer Problem
- Tree + Hash Table
Map nodeMap
private class TNode {
  int val;
  TNode parent;
  List neighbors;
}

Design a data structure that supports insert, delete, search and getRandom in constant time
//A hash where keys are array elements and vlaues are ndexes in arr[]
HashMap  hash;
ArrayList arr;

LeetCode 432 - All O`one Data Structure
Inc(Key), Dec(Key), GetMaxKey(), GetMinKey()

    private Bucket head;
    private Bucket tail;
    // for accessing a specific Bucket among the Bucket list in O(1) time
    private Map countBucketMap;
    // keep track of count of keys
    private Map keyCountMap; or the value can be Bucket
    // each Bucket contains all the keys with the same count
    private class Bucket {
        int count;
        Set keySet;
        Bucket next, prev;
    }
LeetCode - LRU Cache
    private int capacity;
    private HashMap hs = new HashMap();
    private Node head = new Node(-1, -1);
    private Node tail = new Node(-1, -1);

    public LRUCache(int capacity) {
        this.capacity = capacity;
        tail.prev = head;
        head.next = tail;
    }

    public int get(int key) {
        if( !hs.containsKey(key)) {
            return -1;
        }

        // remove current
        Node current = hs.get(key);
        current.prev.next = current.next;
        current.next.prev = current.prev;

        // move current to tail
        move_to_tail(current);

        return hs.get(key).value;
    }

    public void set(int key, int value) {
        // this internal `get` method will update the key's position in the linked list.
        if (get(key) != -1) {
            hs.get(key).value = value;
            return;
        }

        if (hs.size() == capacity) {
            hs.remove(head.next.key);
            head.next = head.next.next;
            head.next.prev = head;
        }

        Node insert = new Node(key, value);
        hs.put(key, insert);
        move_to_tail(insert);
    }

    private void move_to_tail(Node current) {
        current.prev = tail.prev;
        tail.prev = current;
        current.prev.next = current;
        current.next = tail;
    }
LeetCode 460 - LFU Cache
when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.
- Doubly Linked List + HashMap
    private Node head = null;
    private int cap = 0;
    private HashMap valueHash = null;
    private HashMap nodeHash = null;
Design Phone Directory
isTaken(String phone) takeNumber(String phone) giveMeANumber()
- Trie

Stock Ticker
  1. void addOrUpdate(String stock, double price) add or update the price of a stock to the data structure.
  2. List> top() return the top k price stocks and their current prices.
- HashMap contains all elements, MinHeap or TreeSet contains top(k)

Sparse Matrix
Implementing Stack using priority queue.
- assign priority to the elements that are being pushed

TimeTravelingHashTable
* insert(key, value, timestamp)
* get(key, timestamp)
//> = =
HashMap> map = new HashMap<>();


Design a stack with operations on middle element
- push, pop
3) findMiddle() which will return middle element of the stack.
4) deleteMiddle() which will delete the middle element.
- Doubly Linked List

Min Stack

Labels

Java (159) Lucene-Solr (112) Interview (61) All (58) J2SE (53) Algorithm (45) Soft Skills (39) Eclipse (33) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Tools (19) Nutch2 (18) Bugs (17) Debug (16) Defects (14) Text Mining (14) J2EE (13) Network (13) Troubleshooting (13) PowerShell (11) Problem Solving (10) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Http Client (8) Maven (8) Security (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) Shell (7) ANT (6) Coding Skills (6) Database (6) Lesson Learned (6) Programmer Skills (6) Scala (6) Tips (6) css (6) Algorithm Series (5) Cache (5) Dynamic Languages (5) IDE (5) System Design (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Life (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) How to Interview (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Logging (2) Python (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) Invest (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts