Mock tests, Interview questions, Tutorials and Tech news
 
 

Importing csv files with , in text field

June 20th, 2014 No comments

You would have faced this issue sometimes ot other if you are importing csv files and the text field has , in between.
Since it is CSV (comma separated value) while importing, it will break the text values and move to next column.
Definitely that is not what you want.!
What I do is I go and replace , with \,\

Now when you import, it should be all set

Categories: Technology Tags:

New to Git : Adding your code to Git for first time

June 10th, 2014 No comments

If you are new to Git and are looking for very basic stuff to check in yoru code, I found this answer at stackoverflow.com very helpful

http://stackoverflow.com/questions/2866872/how-can-i-upload-fresh-code-at-github

cd "/your/repo/dir"
git clone https://github.com/user_AKA_you/repoName # (creates /your/repo/dir/repoName)
cp "/all/your/existing/code/*" "/your/repo/dir/repoName/"
git add -A
git commit -m "initial commit"
git push origin master

When I was not cloning , I faced some challenges

Categories: Programming / tutorials Tags:

Nosql with Mongo Db Tutorial

June 9th, 2014 No comments

In the last post we had given a short introduction to nosql

In this post , we will give a small working example with java with mongo db which is a type of nosql database.

Why Mongo DB

  • —It is type of Document database
  • —Written in C++
  • —Development started in 2007
  • —Commercial supported and developed by 10Gen
  • —Supports multiple types of indexing
  • —In built Sharding

What is Sharding ? Sharding is the process of storing data records across multiple machines

sharding

.

Sharding is MongoDB’s approach to meeting the demands of data growth. As the size of the data increases, a single machine may not be sufficient to store the data nor provide an acceptable read and write throughput. Sharding solves the problem with horizontal scaling. With sharding, you add more machines to support data growth and the demands of read and write operations.

Development Set Up Mongo

  1. Download and Install Mongo db. http://www.mongodb.org/downloads
  2. Install it on windows or linux.
  3. After installation create a path where you will store data. Don’t forget it is a database so it needs a location where the data can be stored. I created the path in C:\temp2\data\db
  4. Once you have installed go to bin directory and execute this command mongod –dbpath C:\temp2\data\db
  5. For linux users the account that is running mongodb should have write permissions to data/db directory. Run this command sudo chown `id -u` /data/db

Code Example


package demo;

import java.net.UnknownHostException;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

/**
 * 
 * 
 * @author Vinay
 *
 */
public class HelloMongoDB {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		HelloMongoDB helloMongo = new HelloMongoDB();
		helloMongo.insertData();
		helloMongo.findData();
		helloMongo.updateData();
	}

	/**
	 * An example of find data in mongo db
	 */
	private void findData(){

		BasicDBObject basic = new BasicDBObject("name" , "USA")
		.append("type", "country");
		

		
		try {
			Mongo mongo = new Mongo("127.0.0.1", 27017);
			DB db = mongo.getDB("hellomongo");
			DBCursor cursor = db.getCollection("hellomongo").
				find(basic).limit(5);

			while (cursor.hasNext()) {
				System.out.println(cursor.next());
			}
			
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

	}

	
	/**
	 * An example of update data in mongo db
	 */
	private void updateData(){

		BasicDBObject basic = new BasicDBObject("name" , "USA")
		.append("type", "country")
		
		.append("count", 3)
		.append("states", 
					new BasicDBObject("1" , "MA 3")
						.append("2", "TX 3")
						.append("3", "CA 3"));

		
		try {
			Mongo mongo = new Mongo("127.0.0.1", 27017);
			DB db = mongo.getDB("hellomongo");

			
			BasicDBObject newObject = new BasicDBObject("name" , "USA")
			.append("type", "country")
			.append("count", 3)
			.append("states", 
						new BasicDBObject("1" , "MA 1999")
							.append("2", "TX 1999")
							.append("3", "CA 1999"));
			
			db.getCollection("hellomongo").update(basic, newObject);
			

			BasicDBObject newObject2 = new BasicDBObject("name" , "USA")
			.append("type", "country")
			.append("count", 3)	;

			
			DBCursor cursor2 = db.getCollection("hellomongo").
					find(newObject2);
				
				while (cursor2.hasNext()) {
					
					System.out.println(cursor2.next());
					
					
				}
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * An example of inserting data in mongo db
	 */
	private void insertData(){
		
		try {
			
			//Connect to Mongo DB
			Mongo mongo = new Mongo("127.0.0.1", 27017);
			
			// by default 3 databases are created local, admin, todo
			System.out.println(" Connected "+mongo.getDatabaseNames().toString());
			
			//Created a new database 
			DB db = mongo.getDB("hellomongo");
			
			Set<String> collections = db.getCollectionNames();
			for(String s : collections){
				System.out.println("Collection: " +s);
			}
			DBCollection items = db.getCollection("hellomongo");

			long timeInsertStart = System.currentTimeMillis();
			for(int i= 0; i<100 ; i++){
			
				items.insert(createObjectsToInsert(i));
			}
			long timeInsertEnd = System.currentTimeMillis();
			System.out.println(" Time to Insert --> "+(timeInsertEnd-timeInsertStart));
			
/*			DBObject myDoc = items.findOne();
			System.out.println(myDoc);
*/

			long timeFetchStart = System.currentTimeMillis();
			DBCursor cursor = items.find();
			long timeFetchEnd = System.currentTimeMillis();
			System.out.println(" Time to fetch --> "+(timeFetchEnd-timeFetchStart));
			while (cursor.hasNext()) {
				//System.out.println(cursor.next());
			}
			
		} catch (Exception e) {
			
			e.printStackTrace();
			
		}

	}
	
	private static BasicDBObject createObjectsToInsert(int count){
		
		BasicDBObject basic = new BasicDBObject("name" , "USA")
									.append("type", "country")
									.append("count", count)
									.append("states", 
												new BasicDBObject("1" , "MA "+count)
													.append("2", "TX "+count)
													.append("3", "CA "+count));
		
		return basic;
	}
	
}


pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>javaMongoDBExample</groupId>
  <artifactId>javaMongoDBExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>javaMongoDBExample</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- Mongo Db driver -->
     <dependency>
		<groupId>org.mongodb</groupId>
		<artifactId>mongo-java-driver</artifactId>
		<version>2.12.0</version>
	</dependency>
  </dependencies>
</project>

Get the working project from github

Full Documentation

http://docs.mongodb.org/

Helpul Links

Introduction to NoSQL

June 9th, 2014 No comments

 

What is No SQL

No Sql are called as Next Generation database

Characteristics

  • —Non-relational
  • —Distributed
  • —Open-source
  • —Horizontally scalable
  • —No Predefined Schema

Horizontally scalable : Adding more machines to your resource. Vertical scaling is by adding more power.

NoSQL Database Types

There are 4 types of No Sql database

  • Document databases pair each key with a complex data structure known as a document. Documents can contain many different key-value pairs, or key-array pairs, or even nested documents. Couch DB, Mongo DB
  • Graph stores are used to store information about networks, such as social connections. Graph stores include Neo4J and HyperGraphDB.
  • Key-value stores are the simplest NoSQL databases. Every single item in the database is stored as an attribute name (or “key”), together with its value. Examples of key-value stores are Riak and Voldemort. Some key-value stores, such as Redis, allow each value to have a type, such as “integer”, which adds functionality.
  • Wide-column stores such as Cassandra and HBase are optimized for queries over large datasets, and store columns of data together, instead of rows. Hadoop/ Hbase, Cassnadra, Level DB (from Google), BigTable

Why No SQL ?

  1. Large columns of structured, semi structured data and unstructured data
  2. Efficient scale out architecture
  3. Helps in agile development

Example of data in mysql

{

“_id” : { “$oid” : “536ce8d1c25cf6e89fa7deeb”} ,

“name” : “USA” ,

“type” : “country” ,

“count” : “1″ ,

“states” : { “1″ : “MA” , “2″ : “TX” , “3″ : “CA”}

}

No SQL vs SQL

Some major differences between two

SQL Databases No SQL Database
Example Oracle , mysql Mondo DB, CouchDB, Neo4J
Storage Model Rows and tables Key-value. Data stored as single  document in JSON, XML
Schemas Static Dynamic
Scaling Vertical & Horizontal Horizontal
Transactions Yes Certain levels
Data Manipulation Select, Insert , Update Through Object Oriented API’s

Slide presentation at slideshare

Helpful Links

http://nosql-database.org/

http://www.mongodb.com/nosql-explained

http://couchdb.apache.org/

http://www.javacodegeeks.com/2013/03/a-3-step-guide-to-getting-started-with-nosql.html

Categories: Programming / tutorials Tags:

MySQL Developer Exam Quiz

May 29th, 2014 No comments

user MsKnapp has added MySQL Developer Exam at skill-guru.
The quiz comprises of 100 questions. He has offered 10 free questions to readers to try out before they make commitment to buy it.
The questions will challenges your conceptual knowledge as well as practical skills.
Please give your feedback about the quiz to MsKanpp

Categories: Mock Exam / Certifications Tags:

How to add google analytics tracking code to website ?

April 30th, 2014 No comments

So your new shiny website is ready and you have opened it to public. You can measure page views, uniques but not sure what users are doing on their site. You have a search button but not sure how are the users using it.

Do you know you can track the events on your website using google analytics code ?

Please ensure that you are using google Universal analytics which is out of beta as of April 2014. If you are using google universal analytics and using old code, the tracking will not work.

Make sure that you have upgraded to Universal Analytics , if you are not suing Universal Analytics

How do you know if you are already on the google universal analytics ?

A Classic Google Analytics account has an option in this column called Tracking Code. A Universal Analytics account has an option called Tracking Info that includes more Admin settings like Session Settings and Organic Search Sources. These additional settings are only available to Universal Analytics properties. If you have these settings, you have a Universal Analytics property.

This is the code you will be seeing in new google Universal analytics


(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
		  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
		  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

		  ga('create', 'UA-42999935-1', 'skill-guru.com');
		  ga('send', 'pageview');

Here is the the code. This is without using jquery. This code has example for a click of button and a link cool



   <script type="text/javascript">
	
	  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
		  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
		  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
		
		  ga('create', 'UA-4244435-1', 'studyn.us');
		  ga('send', 'pageview');

	</script>
	
	<script type='text/javascript'>
		function trackSubmit() { 
		
		ga('send', 'event', 'button', 'click', 'searchsubmit', 4);
		}
		
		function trackClick() { 
			ga('send', 'event', 'button', 'click', 'This is coool');
		}
	</script>
	
	<body>
	Pushing data.......

		<form onsubmit='trackSubmit()' id='frm'>
		    <button type='submit' id= 'searchsubmit'>Search</button>
		    
		    </br>
		    <a href='http://cool.com' onclick="trackClick(); return false;">cool</a>
		</form>
	
	</body>

How do you debug your google analytics code ?

Now you have written this google analytics code and would like to debug it or see the action.
I have used google analytics debugger for chrome to debug the output.

This is how the output would be in the console

google-analytics-submit-button-track

When you click on link cool, you would see this on console

Executing Google Analytics commands. analytics_debug.js:9
Running command: ga(send, event, button, click, This is coool)

When you click on the submit button , you will not see any output on console.
Do you know the reason why ?

Because the event gets fired , gets printed on console but then page gets submitted and everything gets overridden.

Add this alert after line 16 on code

  alert('testing send event')

Once you run the page, you can see the event being fired. Look at the red arrow in image.

If you do not want form submit , use this on your submit button

 <button type='submit' id= 'searchsubmit2' 
onClick="ga('send', 'event', 'button', 'click', 'searchsubmit', 4);">Search2 </button>

Using google universal analytics code with jquery. Use the method below


 		var _this = this;
			ga('send', 'event', 'button', 'submit', {
			    'hitCallback': function() {
			        $(_this).parents('frm').first().submit();
         }
	}); 



Hope this helps.

Google Universal Analytics Reference

How to create a java project with Maven in Eclipse

April 28th, 2014 No comments

There are two way to get started with java project in Maven

1. Use command line tool

2. Use Eclipse or STS.

In this port we will demonstrate how to create a maven project in Eclipse or STS (Spring source tool Suite)

 

Using Eclipse/ STS to create Java Maven Project

  • Click on File –>New Project .
  • Select the Maven project.
  • In next step, give the name and then go to next step of selecting the archetype. This is important. If you skip the archetype selection, you will no longer be able to run java code.

Arhchetype are maven project templating toolkit. Fastest and easiest way to get started. For more on Archetype refer to maven Arhchetype

maven-java-project

  • Select maven-archetype-quickstart. Eclipse will try to download if not already present.
  • Fill in the details and click finish
  • You would be able to see  the project in your Eclipse.
  • To verify , this is how the Java Build path should look like in Eclipse
  • Maven java project

How to find which version of windows you are running ?

April 24th, 2014 No comments

A quick command line shortcut to figure out which version of windows you are running

wmic os get osarchitecture

The output will be something like

OSArchitecture
64-bit

Categories: Programming / tutorials Tags:
Get Adobe Flash playerPlugin by wpburn.com wordpress themes