Java revise

1) Scanner scan = new Scanner(System.in);
scan.close(); –> close the stream opened

2) difference between Stringbuffer and Stringbuilder

3) find duplicate elements in an array.

4) Solving tower of Hanoi problem using an algorithm

 

 

Eclipse useful shortcuts ===>

Ctrl + Shift + T  ==> Open Type in Hierarchy

Ctrl + Shift + U  ==> Find occurrences of expression in current file

Ctrl + Alt + H     ==> Open Call Hierarchy

Ctrl + Shift + R  ==> Open Resource (file, folder or project)

Advertisements

Android To Read

1) Activity, Memory Leaks, Long running task

http://www.androiddesignpatterns.com/2013/04/activitys-threads-memory-leaks.html
http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html

Retained Fragments to handle background tasks.
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
The difference between static and non-static inner classes is subtle, but is something every Android developer should understand. What’s the bottom line? Avoid using non-static inner classes, anonymous inner classes in an activity if instances of the inner class could outlive the activity’s lifecycle.

Instead, prefer static inner classes and hold a weak reference to the activity inside.

 

 

 

2) Handling Configuration Changes with Fragments

http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

https://developer.android.com/guide/topics/resources/runtime-changes.html

Calling Fragment#setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle, signaling the system to retain the current instance of the fragment when the activity is recreated.

It’s not a good practice to use configChanges to prevent destruction and recreation of activity on configuration change.

android:configChanges="orientation|screenSize"

To handle configuration changes you can implement function onConfigurationChanged().

When you declare your activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged().

3) Infinite View Pager

https://developer.android.com/training/animation/screen-slide.html

http://stackoverflow.com/questions/7766630/changing-viewpager-to-enable-infinite-page-scrolling

http://thehayro.blogspot.de/2013/09/infiniteviewpager-infinite-paging.html


4) Caching – How to use DiskLruCache

https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

https://android.googlesource.com/platform/libcore/+/jb-mr2-release/luni/src/main/java/libcore/io/DiskLruCache.java

http://stackoverflow.com/questions/21872028/jakewhartons-disklrucache-how-to-implement-with-volley

 

CKAN, Proxy setting, Virtual box and etc

Set the proxy on the shell:
export ftp_proxy=proxy_url
export http_proxy=proxy_url
export https_proxy=proxy_url

Set proxy on git installation:
git config –global http.proxy  proxy_url
git config –global https.proxy proxy_url

Set proxy for pip:
pip install –proxy proxy_url -r /usr/lib/ckan/default/src/ckan/requirements.txt
sudo /usr/lib/ckan/datapusher/bin/pip install –proxy proxy_url -r requirements.txt

=====================================================================
File Store Backup and Restore

Backup :
paster db dump -c /etc/ckan/default/production.ini my_database_dump.sql

Restore:
paster db clean -c /etc/ckan/default/production.ini
paster db load -c /etc/ckan/default/production.ini my_database_dump.sql

paster db init -c /etc/ckan/default/development.ini

Create Admin:
paster sysadmin add user_name-c /etc/ckan/default/production.ini

Create test data:
paster create-test-data -c /etc/ckan/default/production.ini

tar -czvf /home/user/Desktop/filestore_backup.tar.gz /var/lib/ckan/default
rm -rf /var/lib/ckan/default/*
tar xvf /home/user/Desktop/filestore_backup.tar.gz

cp -r var/lib/ckan/default/* /var/lib/ckan/default/
chmod -R 777 /var/lib/ckan/default/
sudo chown –R apache /var/lib/ckan/default
==================================================================
/var/lib/pgsql

su – postgres
pg_dump -U postgres -W -F p ckan_default > dump_ckan_default.sql

dropdb -U ckan_default -W ckan_default

=================================================================
Mounting in VirtualBox  :
http://serverfault.com/questions/674974/how-to-mount-a-virtualbox-shared-folder/674978

mkdir share
sudo mount -t vboxsf wd ~/share/

================================================================

Datastore

Insert in datastore
curl -X POST http://127.0.0.1:5000/api/3/action/datastore_create -H “Authorization: db125a88-ece7-4f27-9e6b-8a1bbd13faf6” -d ‘{“resource”: {“package_id”: “d0136066-6daf-4791-83b8-3dbbc0513a31”}, “fields”: [ {“id”: “a”}, {“id”: “b”} ], “records”: [ { “a”: 1, “b”: “45”}, {“a”: 2, “b”: “78”}, {“a”: 3, “b”: “8”}
, {“a”: 4, “b”: “38”}, {“a”: 5, “b”: “118”} ]}’

curl -X POST http://127.0.0.1:5000/api/3/action/datastore_create -H “Authorization: 03c076ad-e1a1-41c8-bf9d-2a35678dfd3b” -d ‘{“resource”: {“package_id”: “e00a3583-ae57-4155-bbd1-ae14d54ca4f3”}, “fields”: [ {“id”: “a”}, {“id”: “b”} ], “records”: [ { “a”: 1, “b”: “aaa”}, {“a”: 2, “b”: “bbb”} ]}’

delete a resource
curl -X POST http://127.0.0.1:5000/api/3/action/datastore_delete -H “Authorization: 03c076ad-e1a1-41c8-bf9d-2a35678dfd3b” -d ‘{“resource_id”: “9016e26a-3b56-4ea3-9da3-9283a003c01d”}’

View a resource:
http://127.0.0.1:5000/api/3/action/datastore_search?resource_id=RESOURCE_ID

http://127.0.0.1:5000/api/3/action/datastore_search?resource_id=4cc335d5-62f2-47dc-9894-4b8dad818862

DataPusher Installation:
http://docs.ckan.org/projects/datapusher/en/latest/

#create a virtualenv for datapusher
sudo virtualenv /usr/lib/ckan/datapusher

#create a source directory and switch to it
sudo mkdir /usr/lib/ckan/datapusher/src
cd /usr/lib/ckan/datapusher/src

#clone the source (always target the stable branch)
sudo git clone -b stable https://github.com/ckan/datapusher.git

#install the DataPusher and its requirements
cd datapusher
sudo /usr/lib/ckan/datapusher/bin/pip install -r requirements.txt
sudo /usr/lib/ckan/datapusher/bin/python setup.py develop

#copy the standard Apache config file
# (use deployment/datapusher.apache2-4.conf if you are running under Apache 2.4)
sudo cp deployment/datapusher.conf /etc/httpd/conf.d/datapusher.conf

#copy the standard DataPusher wsgi file
#(see note below if you are not using the default CKAN install location)
sudo cp deployment/datapusher.wsgi /etc/ckan/

#copy the standard DataPusher settings.
sudo cp deployment/datapusher_settings.py /etc/ckan/

#open up port 8800 on Apache where the DataPusher accepts connections.
#make sure you only run these 2 functions once otherwise you will need
#to manually edit /etc/apache2/ports.conf.
sudo sh -c ‘echo “NameVirtualHost *:8800” >> /etc/httpd/ports.conf’
sudo sh -c ‘echo “Listen 8800” >> /etc/httpd/ports.conf’

#enable DataPusher Apache site
sudo a2ensite datapusher

ConcurrentHashMap in Java

Why we need ConcurrentHashMap when we already had Hashtable ?

Hashtable provides concurrent access to the Map.Entries objects by locking the entire map to perform any sort of operation (update,delete,read,create).

ConcurrentHashMap class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details. So the main purpose of this class is to provide the same functionality as of Hashtable but with a performance comparable to HashMap.

 

ConcurrentHashMap:

 

For detail explanation refer to : http://javahungry.blogspot.com/2015/02/how-concurrenthashmap-works-in-java-internal-implementation.html

Union Find

Union Find by rank and path compression
Time complexity of union and find operations is O(log n) by using rank and path compression.

// Detect cycle in an undirected graph.

public class Main {
	
	public static class Edge {
		int v1, v2;
		
		public Edge(int v1, int v2) {
			this.v1 = v1;
			this.v2 = v2;
		}
	}
	
	public static class Graph {
		int v;
		Edge[] e;
		
		public Graph(int v, int edgeCount) {
			this.v = v;
			e = new Edge[edgeCount];
		}
	}	
	
	public static class UnionFind {
		int rank;
		int parent;
		
		public UnionFind(int rank, int parent){
			this.rank = rank;
			this.parent = parent;
		}
	}
	
	public static int find(int x, UnionFind[] uf) {
		if(uf[x].parent != x) {
			uf[x].parent = find(uf[x].parent, uf);
		}
		
		return uf[x].parent;
	}
	
	public static void union(int v1, int v2, UnionFind[] uf) {
		int p1 = find(v1, uf);
		int p2 = find(v2, uf);
		
	    if(uf[p1].rank < uf[p2].rank){ 	    	uf[p1].parent = p2; 	    } else if(uf[p1].rank > uf[p2].rank){
	    	uf[p2].parent = p1;
	    } else {
	    	uf[p1].parent = p2;
	    	uf[p2].rank++;	    	
	    }
	}
	
	public static int checkCycle(Graph g){
		
		UnionFind[] uf = new UnionFind[g.v];
		
		for(int i=0; i<g.v; i++) {
			uf[i] = new UnionFind(0,i);
		}
		
		for(int i=0; i<g.e.length; i++) {
			int p1 = find(g.e[i].v1, uf);
			int p2 = find(g.e[i].v2, uf);
			
			if(p1 == p2){
				return 1;
			}			
			union(g.e[i].v1, g.e[i].v2, uf);			
		}			
		return 0;
	}
	
	public static void main(String[] arsg){
		Main m = new Main();
		Graph g = new Graph(5, 4);
		
		g.e[0] = new Edge(0,1);
		g.e[1] = new Edge(1,2);
		g.e[2] = new Edge(2,3);
		g.e[3] = new Edge(3,0);
		
		if(checkCycle(g) == 1){
			System.out.println("Graph contains cycle");
		} else {
			System.out.println("Graph does not contains cycle");
		}		
	}
}

In naive implementation the time complexity of union and find operations in O(n)

// Naive implementation of find
int find(int parent[], int i)
{
    if (parent[i] == -1)
        return i;
    return find(parent, parent[i]);
}
  
// Naive implementation of union()
void Union(int parent[], int x, int y)
{
    int xset = find(parent, x);
    int yset = find(parent, y);
    parent[xset] = yset;
}

Solr

Nice tutorial for getting started with Solr version 5: https://examples.javacodegeeks.com/enterprise-java/apache-solr/apache-solr-tutorial-beginners/

Major changes from Solr version 4 to 5: https://cwiki.apache.org/confluence/display/solr/Major+Changes+from+Solr+4+to+Solr+5

Notable ones:
1) Solr is no longer distributed as a “war” (Web Application Archive) suitable for deployment in any Servlet Container.  Solr is now distributed as a stand alone java server application, including start and stop scripts.
2) Changes in bin/solr, bin/post scripts

Major Changes from Solr version 5 to 6: https://cwiki.apache.org/confluence/display/solr/Major+Changes+from+Solr+5+to+Solr+6

This quora answer has good links for learning Solr: https://www.quora.com/What-is-the-best-way-to-learn-SOLR

 

cURL & wget

cURL is a software package which consists of command line tool and a library for transferring data using URL syntax.

cURL supports various protocols like, DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP.

Examples:

  • curl http://www.centos.org
  • curl -O URL1 -O URL2     // multiple file downloads
  • curl -L http://www.google.com     // follow HTTP location headers.
  • curl -C – -O http://www.gnu.org/software/gettext/manual/gettext.html
    // continue & resume download
  • curl -z 21-Dec-11 http://www.example.com/yy.html     // download a file if modified after given date.
  • curl -u username:password URL   // pass http authentication in curl
  • curl -u ftpuser:ftppass -O ftp://ftp_server/public_html/xss.php     // download files from ftp server
  • curl dict://dict.org/d:bash   // get definition of a word with DICT protocol
  • curl -x proxysever.test.com:3128 http://google.co.in   // use proxy for file download
  • curl –mail-from blah@test.com –mail-rcpt foo@test.com smtp://mailserver.com    // send mail with SMTP protocol

 

wget utility is the best option to download files from internet. wget can pretty much handle all complex download situations including large file downloads, recursive downloads, non-interactive downloads, multiple file downloads etc.

Examples:

 

Two interesting blog posts that I have come across for cURL and wget. The definitions and examples in this post are taken from these.

cURL: http://www.thegeekstuff.com/2012/04/curl-examples/
wget: http://www.thegeekstuff.com/2009/09/the-ultimate-wget-download-guide-with-15-awesome-examples/