Translate

Monday 30 September 2013

Java FX | A Powerful Platform

Today, in the age of Web 2.0, AJAX, and the iPhone, users have come to expect their applications to provide a dynamic and engaging user interface that delivers rich graphical content, audio, and video, all wrapped in GUI controls with animated cinematic-like interactions. They want their applications to be connected to the web of information and social networks available on the Internet. Developers, on the other hand, have become accustomed to tools such as AJAX/HTML5 toolkits, Flex/Flash, Google Web Toolkit, Eclipse/NetBeans RCP, and others that allow them to build and deploy rich and web-connected client applications quickly. They expect their development languages to be expressive with features that liberate them from the tyranny of verbosity and empower them with the ability to express their intents declaratively.
During the early days of the Web, the Java platform was the first to introduce rich content and interactivity in the browser using the applet technology (predating JavaScript and even Flash). Not too long after applets appeared, Swing was introduced as the unifying framework to create feature-rich applications for the desktop and the browser. Over the years, Swing matured into an amazingly robust GUI technology used to create rich desktop applications. However powerful Swing is, its massive API stack lacks the lightweight higher abstractions that application and content developers have been using in other development environments. Furthermore, the applet's plugin technology was (as admitted by Sun) neglected and failed in the browser-hosted rich applications against similar technologies such as Flash.
 The JavaFX is Sun's (now part of Oracle) answer to the next generation of rich, web-enabled, deeply interactive applications. JavaFX is a complete platform that includes a new language, development tools, build tools, deployment tools, and new runtimes to target desktop, browser, mobile, and entertainment devices such as televisions. While JavaFX is built on the Java platform, that is where the commonalities end. The new JavaFX scripting language is designed as a lightweight, expressive, and a dynamic language to create web-connected, engaging, visually appealing, and content-rich applications.
The JavaFX platform will appeal to both technical designers and developers alike. Designers will find JavaFX Script to be a simple, yet expressive language, perfectly suited for the integration of graphical assets when creating visually-rich client applications. Application developers, on the other hand, will find its lightweight, dynamic type inference system, and script-like feel a productivity booster, allowing them to express GUI layout, object relationship, and powerful two-way data bindings all using a declarative and easy syntax. Since JavaFX runs on the Java Platform, developers are able to reuse existing Java libraries directly from within JavaFX, tapping into the vast community of existing Java developers, vendors, and libraries.


The most fascinating thing about JavaFX is that we  need not take pain to install any third party plugins or include any external libraries, as it comes bundled with JRE, from Java7 onwards, in turn JavaFX leverages the extreme ubiquity, power, performance and security of the JRE. So we just need to install Java and you are ready to build FX applications with inbuilt library with utmost ease.

JavaFX provides a vivid range of functionality like animation, support for Canvas API, Multi-Touch Support and many more.JavaFX offers a dramatically shortened production cycle for designers and developers through its designer–developer workflow. JavaFX allows you to incorporate multimedia assets from popular third-party design tools such as Adobe Illustrator and Photoshop using the JavaFX Production Suite.

One other thing which I personally like in JavaFX is that , the FX application which is made is directly available as an executable JAR file as soon as the code is compiled , so it becomes pretty easy for distribution purposes . 

Feel free to post any queries in the the comments section I will be more than happy to answer them . I will be posting a basic FX game , FX Movie maker and FX Video player soon with the complete description of the code. So stay tuned , key in your email in 'Follow By Email' to get the notification as soon as I post .

Cheers!!

Friday 27 September 2013

Google Search | The Guardian Angel

Google  has become integral part of all the working professionals , as it is the ultimate solution to all the questions whatever may be the field , subject . It is basically the solution bank to all the questions which people have around the world.

Google is the most used search engine , among the other dozens of search engines available. Google makes life easy as you find all the possible links to the question keyed in . Frankly speaking to search on google is an art , not everyone can find desired results , as you should be really very sure what keywords should find the required content, as Google takes each of the word keyed in the search as the keys to search for and then it runs the search and drives the pages which have maximum number of keyword matches.

For the people who are in software development field, google acts as a boon for them. By profession I am also an Software Developer , Google really serves well in the crunch time , or just for casual searching. Be it preparation of Seminar , making of a Project, or preparation of a presentation. Even you could find several explanations for the technical questions you might come across . You could really anything in the technical field , as there are several online forums for various technologies , which have tags so that they be visible in searches made on Google.

 Google makes you aware of things which might be completely alien , and at some point of time you need to know about that alien object. One of my experiences, when I joined the company my lead assigned me a technology called 'SERVOY' , and I really didn't have idea if such a platform exist basically never heard of , so after the assignment of the technology I did a Google search and at least got that basic idea as what we can do on this platform .

Google Search in true terms is the saviour for people of all the age group , starting from small kids who may use it to search photos for their science projects ,or the professional people-- be it at work or be it for show timings of the shows in the city .Even  old people could use google for remedies of the diseases , or could be for casual reading or for reading news and lots more .

What a day for writing about the Google Search , today is the 15th Anniversary of Google (Might have noticed the doodle and the little game there .. ) .In order to help people search in a productive manner and to attain the closest match to the queries keyed in the Google Search , you can go through the courses offered on Power Searching by Google

I really want to thank Google for being my side always when  I needed any solution . Please do post you experience I will be more than happy to know them.
Cheers...!!

Thursday 26 September 2013

Being Amongst the Crowd or An Individual?

 
   The people in world could be categorized , as an individual or as  a someone among the 7 billion people in the world. The people be an individual , or be amongst the crowd , completely based on traits . I am not demarcating this on the basis of degree of greatness of a person , or popularity or any other aspects which are not common to all the people in the world , I am simply demarcating on the basis of their mentality and decisiveness .

To start with : What is a crowd
Crowd is basically a group of individuals which do not have their personal identity ( but a collective identification as a general mob ) or are a bit shy taking lead or stand in a cause , and they all have a common thinking that someone takes a stand in their group, hiding themselves behind each other. Being a part of crowd person's individuality subside, and even it deprives the individual of his power of expression  have fear or hesitation , that what will other think of their doing , will it be appreciated or condemned .

What is an Individual?
Individual is a person who weighs each and every situation reasonably and act accordingly surpassing all the reasons which might withdraw his decision. The reasons here is not change of mind , reasons are being influenced by what others might think , how would others react ,or will anyone support or not etc. But an individual being does not care about the noise (Reasons stated earlier ) in the environment he/she just goes on. An Individual always have an edge over the crowd because the wonderful gift which comes in blessing as a disguise is high level of confidence. In today's scenario one thing which is a direct  requirement for all the jobs be it any field is confidence. In other words confidence is the currency in the industry one person belongs to , because interviewers are looking for the level of confidence which is in the candidate. It is rightly said by a noted Physician, Bernard M. Baruch that ----

                                        “Be who you are and say what you feel, because those who mind don't matter,and those who matter don't mind.” 



It is frequently said that there are consequences and latter effects of a thing,as a Crowd(or mob) there comes mob mentality as the consequence(as human in a rational being , and humans constitute mob-- though the catch is that they don't think that rationally) , this is basically the collective decision of group of people. This kind of mentality can be seen among the herd and cattle where all of them do a common thing,like walking in group one after the other ,etc.   An instance which would give a better perception-- Everyone would have heard about the communal riots , what happens in it one person turns outlaw and huge crowd of people simply follow because of witty talks of single person without giving it a second thought,  and unknowingly they become part of the anti-social activity. See how does this mentality has a magnification effect starting with a one outlaw person, it raised the whole crowd of outlaws.

Now, lets see another less intense or rather general instance , I can bet that everyone must have  seen a place where it is written that 'No Spitting Here' and to much surprise that particular place is stained all over with spits. 
What do you think people can't see or they just feel happy breaking code of conduct?
 Here  mob mentality plays its part , suppose a person when sees the sign of 'No Spitting Here' ,notices the spits all over, looking that ,his confidence soars up to spit ,thinking that already the place is dirty let me add to the attributes , instead he could obviously not clean it but at least could have refrained form spitting.


It does not takes much to be a face in the crowd and take rightful decisions , but in turn it acts as a foundation to individuality, which in its true essence, is responsible for molding a human into a person who is master of his intellect.

So think wisely which group are you into , as your decision could be crucial. Do post your views/suggestions as I would love to hear from you about the topic, as views vary from person to person .
Cheers!! 

Wednesday 25 September 2013

How to decorate reports in Jasper Reports , and how can we produce certificates with Jasper reports?

What you need to do is add a property to the fields you are wanting referenced. To add the class name you need to add net.sf.jasperreports.export.html.class and to include an id you need to addnet.sf.jasperreports.export.html.id as a property. As an example, below is a Text field that sets both:
<textField>
    <reportElement uuid="2399e4ef-633c-4d17-b964-3e093ece1936" x="0" y="22" width="100" height="20">
        <property name="net.sf.jasperreports.export.html.class" value="TEST"/>
        <property name="net.sf.jasperreports.export.html.id" value="ID"/>
    </reportElement>
    <textElement markup="html"/>
    <textFieldExpression><![CDATA[($F{field1}]]></textFieldExpression>
</textField>
In iReport you add these by selecting the field, and then in the properties window clicking the ellipses button next to Properties expressions. enter image description here
To include the link to the css file in the exported report, you need to set the value for theJRHtmlExporterParameter.HTML_HEADER parameter before exporting. Note the parameter is not the header in the sense of HTML (the contents of the head tag), but the header of the exported HTML report. Meaning it is what is first placed in the exported report to begin with, before including the report. The default that Jasper Reports uses is:
<html>
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <style type="text/css">
    a {text-decoration: none}
  </style>
</head>
<body text="#000000" link="#000000" alink="#000000" vlink="#000000">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr><td width="50%">&nbsp;</td><td align="center">
So you will need to modify this to include the link to your stylesheet by adding:
<link rel="stylesheet" type="text/css" href="<cssfile you want to point to>" />
to that in the appropriate place, which I think is inside the head tag, but if not move to appropriate area. So the java code would end looking something like:
<span style="font-size:11px;"><strong>JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, 
    "<html>"+
    "<head>"+
    "  <title></title>"+
    "  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>"+
    "  <link rel=\"stylesheet\" type=\"text/css\" href=\"css/jasper.css\" />"+
    "  <style type="text/css">"+
    "    a {text-decoration: none}"+
    "  </style>"+
    "</head>"+
    "<body text="#000000" link="#000000" alink="#000000" vlink="#000000">"+
    "<table width="100%" cellpadding="0" cellspacing="0" border="0">"+
    "<tr><td width="50%">&nbsp;</td><td align="center">");
exporter.exportReport();</strong></span>
Hope that it helps

How to make global header and footer in Jasper Reports?

Hi,
Suppose there are reports ABX,BNC and KLM  which have a same header and footer Then what you can do is create a master Report suppose mainReport, in there you add 3 subreports in the details section and then  and give the path of the the three reports ABX,BNC and KLM.  
You will have to specify the input control in the mainReport which user will have to enter suppose REPORT_SELECTION. Now you will have to decide the disctinct codes for each of the subreports . Suppose in this case I assign codes as :
ABX-1
BNC-2
KLM-3 
It  would accept the 1,2,3 from the user as input from the user in the parameter $P{REPORT_SELECTION} on the basis of this very choice of user it will trigger the presence or absence of the subreport.(Here 1,2,3 are just the cases could be anything like A,B,C or name itself like "ABX","BNC","KLM" )
Now to trigger the appearance of the subreport on the basis of this parameter $P{REPORT_SELECTION} ,which is entered by user we need to write the print when expression. The printwhen expression(which you would find in the property of the subreport element) you need to specify it as  : $P{REPORT_SELECTION}  ==1 (This will be for the report ABX ). So in this way the expression will vary. and you will get the desired subreport.
Please keep in mind that in the subreports header and footer is removed .
Here the input control REPORT_SELECTION is included on the mainReport so would be global too, and even you could accept the values of other parameters required by the reports and then pass it on to the subreports.So the parameters or input controls would be turned global too.
Hope that above explanation helps .


Happy Coding!!

How to execute Jasper Report through Java?

I found a way for that by parsing the xml and then extracting the tags with parameter and retrieving the attribute name and class keeping in mind the check attribute  isForPrompting is blank or not present for the parameters , In this way I got the Hashmap of all the parameters with their types and I put that in the parameterMap and hence fulfilling the parameters in the jrxml dynamically


The jars need to be included are-
1.commons-beanutils-x.x.x.jar
2.commons-collections-x.x.x.jar
3.commons-digester-x.x.jar
4.commons-logging-x.x.jar
5.groovy-all-x.x.x.jar
6.iText-x.x.x.jar
7.jasperreports-x.x.x.jar
8.poi-x.x.jar(for excel export)
9.jfreechart-x.x.x.jar


Happy Coding!!

What is MONGO DB?

MongoDB is a cross-platform document based system. Classified as a "NoSQL"database, MongoDB eschews the traditional relational database structure in favor of JSON-like documents with dynamic schemas , making the integration of data in certain types of applications easier and faster.

It is very interesting to work on a system which does not follow the conventional tantrums of relational DB, and curbing the obligation of maintaining  a perfect table structure and keeping the relations intact. Now you need not worry for the same with MongoDB , you just have to create the collections to much of a surprise the collections here are dimensionless , what I mean is that there could be a scenario where in the first row you have 3 records and next you have 2, wherein the SQL table you need to specify all the fields for all the rows. For Instance :
As the data stored is in a form of a document so all the documents are like a JSON  Document
{a:1,b:1,c:3},
{a:1},
{a:2,b:3},
{a:1,b:4,c:3,d:4}

As you could see above , its dimensionless. Now the next question which would haunt you would be that how would the sorting, grouping and other aggregations can be done , so the answer is that MongoDB has an inbuilt feature which skips the rows which does not contain the queried field to sort.


One might question that if there is no relational arrangement then how come the relations are maintained, but joy of a Document database is that it eliminates lots of Joins. Your first instinct should be to place as much in a single document as you can. Because MongoDB documents have structure, and because you can efficiently query within that structure there is no immediate need to normalize data like you would in SQL. In particular any data that is not useful apart from its parent document should be part of the same document.So the catch is you can put as much data in the parent document which has high frequency of access , but is required to be updated less . And the documents which needs lots of updates or require increments it could be placed in a small document. So in that way the data is arranged and that data is only accessed which needs to be retrieved.



'mongod' This is a command line command to run the database instance , 'mongo' is a command to run the mongo shell where in you could access you data ,'mongos' this command keeps the track of shard keys. When you have to access the data you have to run the database instance and then access the mongo shell .

MongoDB provides a number of features that allow application developers and database administrators to customize the behavior of a sharded cluster or replica set deployment so that MongoDB may be more “data center aware,” or allow operational and location-based separation.


MongoDB uses write ahead logging to an on-disk journal to guarantee write operation durability and to

provide crash resiliency. Before applying a change to the data files, MongoDB writes the change operation to the
journal. If MongoDB should terminate or encounter an error before it can write the changes from the journal to the 
data files, MongoDB can re-apply the write operation and maintain a consistent state.

The MongoDB aggregation framework provides a means to calculate aggregated values without having to use mapreduce.While map-reduce is powerful, it is often more difficult than necessary for many simple aggregation tasks,such as totaling or averaging field values.

If you’re familiar with SQL, the aggregation framework provides similar functionality to GROUP BY and related
SQL operators as well as simple forms of “self joins.” Additionally, the aggregation framework provides projection
capabilities to reshape the returned data. Using the projections in the aggregation framework, you can add computed fields, create new virtual sub-objects, and extract sub-fields into the top-level of results.

MongoDB supports unique replication feature which increases data availability with multiple copies of data on different database servers, replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup



This feature gives and edge in the case when the primary DB fails, because mongoDB supports a unique feature , wherein it grants  the secondary databases to perform an election amongst them to elect the primary database and then carry on the further transactions from that instance.



Another great feature of MongoDB is Sharding, or horizontal scaling which divides the data set and distributes the data over multiple servers, or shards. Each shard is an independent database, and collectively, the shards make up a single logical database. 

MongoDB also supports segregation based on functional parameters, to ensure that certain mongod instances are only used for reporting workloads or that certain high-frequency portions of a sharded collection only exist on specific shards. 

There is a limitation of MongoDB that it can have a document of maximum 16mb ,not greater than that , but to cater that 'GridFS' is there- This breaks the document in several small chunks and index it accordingly . This proves handy when you have to store huge data like photos,etc.

In my views it really fascinating to work on MongoDB ,to experience the NOSQL environment , it really great to provide flexibility in the database structure as the structure, relations have been the prime concern  for the developers . I would certainly recommend the usage in order to provide wings to the application.

Well one of the courses which I would recommend everyone is MongoDB for Developers M101J-   MongoDB for Developers M101J. In the course nicely all the features are covered and explained , I will recommend everyone to complete this.

Don't hesitate to add comments and questions if you have any doubts in the content , I will try to answer as soon as possible.
Cheers!!

Poverty,Poverty,Poverty ... Is this what hindering growth of our Nation!!

   Poverty , when we hear this word many of us give it a thought (that's really great!!) but next thing which they do is just let it go having reason , that we are not poor ,we don't need to think about them etc. etc. As we all are rational beings and we have solid reasons to not to give  thought to grave problem of poverty.

    Million Dollar question is , IS POVERTY HAMPERING THE GROWTH OF NATION??
Truthfully if I say not really because the poor people right now do not constitute the growth of  nation, as they are already out of the race . These people are not even capable of managing their basic needs or if they do somehow it is merely marginal , after a whole day's toil. That is really disheartening , everyday when they get off their homes they really don't know that they would be even able to get enough resources to curb hunger of their family.

  The poor people have become really become hopeless , waiting for a helping hand . Do they deserve this ?
Don't they have any right to contribute to progress of Nation ?  A really sorry sight which I eye-witnessed- Early morning I was at a Railway Station waiting for train to arrive , I bought a cup of tea from a nearby stall and what I noticed was that there was a poor man searching the dustbin attached to the stall curiously but at an interval of  5-10 mins the stall owner scolded him off like a cattle , but the poor guy repeatedly came back .After two or three such encounters he finally set at some distance . Then what I saw was distressful sight that he was fishing for the discarded teabags in the dustbin and he was squeezing that into a cup to get him a cup of morning tea . Seeing that I could not take another sip from my cup , I gave mine to him as well as a packet of biscuit which brought a little smile on his face , which brought down the my guilt marginally.

  I am not suggesting that you start making donations to them or tipping the beggars , no not at  all that will introduce a new shortcut for the poor people for begging.What I learned was that , giving a cup of tea and a packet of biscuit to him , brought him a smile . See the point which I want to make is that they should have their share of  subsidies and aids , which could get some content and some sense of being cared.      

   We hear of things like prices of the general commodities increasing day by day , but the question is that - Are the wages of the poor people rising too? Answer is simply no , the challenge of earning their basic urges is going up by leaps and bounds and they are helpless.Who is going to help them , Me,You or the Government, answer is tough isn't?
 
    We hear of the Government policies and rural development programs , wherein Government sanction huge sum of money for supporting one or other problems like houses for poor, food at subsidized rates ,etc. But one thing to catch is , Are the people at grass root level really getting the money invested upon them , forget about getting do they even know that Government is taking steps to curb their helplessness.
 
   Are these really benefitting the targeted people ?  No , the money or the resources are no doubt flowing from the government treasury , but it has to undergo lots of levels of executives and systems .The layers should be completely porous to let the resources seep, ironically what poor receives are the drops of resources and with such limited resources only limited things can be done , which are still insufficient.But the real concern is that , instead of porous intermediate layers of administration they turn  act semi-porous .
 Why so ? Don't they want upliftment of poor ?

How come the enormous resources turn meagre ?

That is a really controversial point which has a different conclusion for different people so that's a little food for thought for you, feel free to put the comments and suggestions in the box below.

If the poor people are not taken care off, they are already out of league to enhance the growth of nation as they also constitute the growth as a whole , because development of nation means development from the grass root level .

Tuesday 24 September 2013

Are the Smartphones really 'SMART' ?

 Today having a Smartphone is a more of a style statement. The comparisons are made with the size of the screens which they have on their phones .The small and stylish phones have now grown into Phablets and even the tablets which are enormously large are coming with calling facility. People have really gone crazy for the smartphones but along with this another trait which gets cultivated along is the obsession or rather addiction to their devices.  

 People nowadays do two things majorly, one that they perform there daily jobs and the second the pastime which they mostly pass on using they so called 'smartphones'. Well day by day the size of the smartphones are getting increased and so is the craze to own one . Things which are aiding the cause is the huge smartphone market which has a policy of selling as much units as possible, and even the price ranges are for people of all the classes. Now as  these smartphones are available to all groups of people this has fueled the craze , and have led them on to a path of being virtual socialization.

The term 'Virtual Socialization' which I have used here refers to endless social messaging apps , and among the social messaging giants are Facebook, Twitter, Whatsapp , etc.   which provide you with amazing power to connect to people (who are in your "Friend List ") virtually with no physical connection , simply OTA (Over The Air ) at your convenience.

 Smartphone user have an edge to this amazing technique , as they can always be logged into their social app accounts and can access anywhere ,anytime it is just the internet pack which they need (which is readily available these days cultivating the cause) and you are good to go.

But the truth is  ,   Is it worth it ?
To overlook the real  available social circle which is powered by real communication than digging deep into your beloved smartphone in order to keep the virtual web around you intact. Moreover  people have grown an habit of searching things online pointlessly just to prove the superiority on others or for just mere fun.

There are even radiation threats on prolonged usage of the smartphones, as in order to make phones smart lots of sensors and receivers are embedded in the smartphones , as we can see that there is lot of competition in the market amongst the different brands the companies tend to use the cheap components which are a emitter of radiations. These radiations could be really very harmful , completely hampering health of the carrier.

People have to think that there is lot more than a phone, rather they should look around and find  things which could be of better good, there is more they can do than keying in the messages and Face-booking as it is said.People have nowadays hobby of  browsing apps in their smartphones and killing their precious time but they need to think harder that virtual socialization is just making virtual connections , which will enable you to believe that you have a vast connection of friends. There might be a case that a person might have over 100 Facebook friends, 50 twitter followers , but in reality he might be struggling to get a one good friend. This is possibly because through social networking sites you might have an edge of making as many friends through sending a friend request but when it comes down to talk in person it could be real hard, but these things are to be understood by each person . Let us leave that topic as its wayward from the title .

People have really stopped observing their surroundings and events happening in their vicinity , because they are busy focussing in their smartphones. People have stopped observing the weather and started asking to 'Siri' and 'Google Now' -- '' How's the weather Like?". People have stopped exploring their surroundings and started finding in the maps  in their phones. People have started texting the smilies without literally exclaiming their emotions , and many more . There are more funny comparisons but the list may just go on. People try to find each and everything in their phone ,  as they spend in them heavily so of course will expect returns and phones in turn don't discourage their hopes providing all kind of virtual solutions and expectations to the user.

I might sound like I totally condemn the usage of smartphone but fellas I do have a smartphone but the thing which is clear in my mind is that it is just another small gadget in my daily life which I use only when it is required ,not using it for a time pass or just a hobby and wasting my precious time in fondling the apps in my phone.


Smartphone ,Yes has an edge over other phones , when we utilize it for daily needs its good but when requirement turns into addiction , then is the time when it hampers the smartness of an individual .









Friday 20 September 2013

M101 MongoDB for Java Developers' final exam Answer(M101J)

Here I am providing the answers for FINAL exam M101J,which I found out upon solving.Hope you use it wisely, my point of discussing each of the questions is that everyone could check which point are they going wrong and yes I could also get a better solution than mine. So please use it as a extra check after you have solved the question once on your part so that the explanations benefit you the most.


Question 1 : 
Here we need to query the enron dataset calculate the number of messages sent by Andrew Fastow, CFO, to Jeff Skilling, the president. Andrew Fastow's email addess was andrew.fastow@enron.com. Jeff Skilling's email was jeff.skilling@enron.com

So for this first we need to download the enron zip/tar and then import in the mongoDB database name enron and collection name messages . Command for import

mongoimport -d enron -c messages > enron.json

Now switch to mongo Shell  commands:
use enron
db.messages.find({"headers.To":"andrew.fastow@enron.com","headers.From":"jeff.skilling@enron.com"}).count()
This will produce the answer as 3









Question 2:

Please use the Enron dataset you imported for the previous problem. For this question you will use the aggregation framework to figure out pairs of people that tend to communicate a lot. To do this, you will need to unwind the To list for each message.

The mongo shell command which will retrieve the desired answer would be 
db.messages.aggregate([
{
$project: {
from: "$headers.From",
to: "$headers.To"
}
},
{
$unwind: "$to"
},
{
$group : { _id : { _id: "$_id", from: "$from", to: "$to" }
}
},
{
$group : { _id : { from: "$_id.from", to: "$_id.to" }, count: {$sum :1}
}
},
{
$sort : {count:-1}
},
{
$limit: 2
}
])
This would give you the top 2 communication , and check the top most  which would turn out to be :

 "result" : [
         {
                 "_id" : {
                         "from" : "susan.mara@enron.com",
                         "to" : "jeff.dasovich@enron.com"
                 },
                 "count" : 750
         },
         {
                 "_id" : {
                         "from" : "soblander@carrfut.com",
                         "to" : "soblander@carrfut.com"
                 },
                 "count" : 679
         }
 ],

 "ok" : 1
So, it clearly shows the answer is "susan.mara@enron.com" to "jeff.dasovich@enron.com"





Question 3:

In this problem you will update a document in the Enron dataset to illustrate your mastery of updating documents from the shell. Please add the email address "mrpotatohead@10gen.com" to the list of addresses in the "headers.To" array for the document with "headers.Message-ID" of "<8147308.1075851042335.JavaMail.evans@thyme>" 

For this there would be a simple update expression using mongo shell as :
db.messages.update({"headers.Message-ID":"<8147308.1075851042335.JavaMail.evans@thyme>"},{$addToSet:{"headers.To":"mrpotatohead@10gen.com"}})

Then run the validation code and get the validation code as : 897h6723ghf25gd87gh28





Question 4:

Enhancing the Blog to support viewers liking certain comments.

Here you need to work on the BlogPostDAO.java at the area marked as XXXXXX

postsCollection.update(new BasicDBObject("permalink", permalink), new BasicDBObject("$inc", new BasicDBObject("comments." + ordinal + ".num_likes", 1)));

Here in the above command we search the posts collection with the permanent link and increment the like counter by one for the comment which is clicked for like or in other words the ordinal or the order of the comment in the comments array, this ensures that the like is incremented for the comment clicked for like.
Doing this you could see that the like button starts working.

Now run the validator , and you will get the code as : 983nf93ncafjn20fn10f






Question 5 :    

In this question a set of indexes are given and we have to select the indexes which might have been used , in execution of 
db.fubar.find({'a':{'$lt':10000}, 'b':{'$gt': 5000}}, {'a':1, 'c':1}).sort({'c':-1})

 As the Find portion searches on a,b and a,c  and sorting is carries on c reverse order.

_id_ -- This index is not used either in sort or find clause of the operation
a_1_b_1 --  This index is used in the find operation as find is on a,b
a_1_c_1 --  This index is used in the find operation as find is on a,c
c_1 -- This index is also used, because there is a provision that a index is not utilized for the find operation but  for the sort it is used as sort({'c':-1})
a_1_b_1_c_1 - This involves all the three a,b,c and this is also used as it can also be used as a valid index





Question 6

Suppose you have a collection of students of the following form:
{
 "_id" : ObjectId("50c598f582094fb5f92efb96"),
 "first_name" : "John",
 "last_name" : "Doe",
 "date_of_admission" : ISODate("2010-02-21T05:00:00Z"),
 "residence_hall" : "Fairweather",
 "has_car" : true,
 "student_id" : "2348023902",
 "current_classes" : [
  "His343",
  "Math234",
  "Phy123",
  "Art232"
 ]
}

Now suppose that basic inserts into the collection, which only include the last name, first name and student_id, are too slow. What could potentially improve the speed of inserts. Check all that apply.

Add an index on last_name, first_name if one does not already exist.
Set w=0, j=0 on writes
Remove all indexes from the collection
Provide a hint to MongoDB that it should not use an index for the inserts
Build a replica set and insert data into the secondary nodes to free up the primary nodes.

option 1 - As a fact adding index affects reading not writing so it would be indifferent with the indexing so not this option
Option 2 seems to be valid as when w=0 and j=0 is done for the writes no waiting is done at all are no wait is required to obtain as the write confirmations , simply the data is dumped without verification therefore speeding the writes
Option 3 removing indexes would actually help as it would reduce the load and speed up the writing process
Option 4 This seems absurd
Option 5 This is not actually possible as writes are not possible on the secondary nodes so not valid option






Question 7

You have been tasked to cleanup a photosharing database. The database consists of two collections, albums, and images. Every image is supposed to be in an album, but there are orphan images that appear in no album. Here are some example documents (not from the collections you will be downloading). 
When you are done removing the orphan images from the collection, there should be 90,017 documents in the images collection. 

In order to remove the Orphans talked I wrote a Java Program :

/**
 *
 * @author Ankur Gupta
 */
public class Test {
    
        public static void main(String[] args) throws IOException {
            MongoClient c =  new MongoClient(new MongoClientURI("mongodb://localhost"));
            DB db = c.getDB("finaltask");
            int i =0;
            DBCollection album = db.getCollection("albums");
            DBCollection image = db.getCollection("images");
            
            DBCursor cur = image.find();
            cur.next();
            
            while (cur.hasNext()){
                Object id = cur.curr().get("_id");
               DBCursor curalbum = album.find(new BasicDBObject("images", id));
               if(!curalbum.hasNext()){
                   image.remove(new BasicDBObject("_id", id));
               }
               cur.next();
            }
        }
}

In order to verify above statement after removing orphans :
db.albums.aggregate({$unwind:"$images"},{$group:{_id:null,sum:{$sum:"$images"},count:{$sum:1}}})
The result looks like:
    "result" : [
            {
                    "_id" : null,
                    "sum" : NumberLong("4501039268"),
                    "count" : 90017
            }
    ],
    "ok" : 1

To prove you did it correctly, what are the total number of images with the tag 'sunrises" after the removal of orphans?
db.images.find({"tags":"sunrises"}).count()
This will fetch the final answer as  45044




Question 8:
Supposed we executed the following Java code. How many animals will be inserted into the "animals" collection?
public class Question8 {



        public static void main(String[] args) throws IOException {
            MongoClient c =  new MongoClient(new MongoClientURI("mongodb://localhost"));
            DB db = c.getDB("test");
            DBCollection animals = db.getCollection("animals");


            BasicDBObject animal = new BasicDBObject("animal", "monkey");

            animals.insert(animal);
            animal.removeField("animal");
            animal.append("animal", "cat");
            animals.insert(animal);
            animal.removeField("animal");
            animal.append("animal", "lion");
            animals.insert(animal);

        }

}

When you run the above , then you will see an error is thrown that there is a duplicate ID , as we are trying to add , documents again and again on the same Id as we are modifying the same document . So the only one document will be inserted in the collection which will be the first insert as {_id::xxx,"animal","monkey"}
then when again ("animal","cat") is tried to push then the id is same so , it throws duplicate key . So answer is that only one document gets inserted.




Question 9:
Imagine an electronic medical record database designed to hold the medical records of every individual in the United States. Because each person has more than 16MB of medical history and records, it's not feasible to have a single document for every patient. Instead, there is a patientcollection that contains basic information on each person and maps the person to a patient_id, and arecord collection that contains one document for each test or procedure. One patient may have dozens or even hundreds of documents in the record collection. 

We need to decide on a shard key to shard the record collection. What's the best shard key for therecord collection, provided that we are willing to run scatter gather operations to do research and run studies on various diseases and cohorts? That is, think mostly about the operational aspects of such a system.

patient_id
_id
primary care physican (your principal doctor)
date and time when medical record was created
patient first name
patient last name

Here among the options given for the shard key most favourable is patient_id , as there are large number of patient_id and they have been distributed in different diseases, and when a scatter gather operation is carried out then the data is far more expanded on the basis of patient_id.

Other options are not suitable for the scatter and gather operation.




Question 10:
Understanding the output of explain We perform the following query on the enron dataset:
db.messages.find({'headers.Date':{'$gt': new Date(2001,3,1)}},{'headers.From':1, _id:0}).sort({'headers.From':1}).explain()
and get the following explain output.
{
 "cursor" : "BtreeCursor headers.From_1",
 "isMultiKey" : false,
 "n" : 83057,
 "nscannedObjects" : 120477,
 "nscanned" : 120477,
 "nscannedObjectsAllPlans" : 120581,
 "nscannedAllPlans" : 120581,
 "scanAndOrder" : false,
 "indexOnly" : false,
 "nYields" : 0,
 "nChunkSkips" : 0,
 "millis" : 250,
 "indexBounds" : {
  "headers.From" : [
   [
    {
     "$minElement" : 1
    },
    {
     "$maxElement" : 1
    }
   ]
  ]
 },
 "server" : "Andrews-iMac.local:27017"
}
The query did not utilize an index to figure out which documents match the find criteria.
The query used an index for the sorting phase.
The query returned 120,477 documents
The query performed a full collection scan

Here the correct options will be :
Option 1 seems to be correct as  if you could notice that "cursor" : "BtreeCursor headers.From_1" that means that headers.From_1 is used which is not in the find clause but is in the sorting

Option 2 also seems to be correct as "cursor" : "BtreeCursor headers.From_1" the cursor is used in the sorting phase

Option 3 This option is wrong as 83057 records as n=83057


Option 4 This option is correct as if we see nscanned objects is 120477 so it has scanned all



Hope that above explanation prove helpful, please put your precious comments and suggestions on better method to do any question.