Saturday 14 November 2015

Git Chit #1

Hola  Amigos!!

Diwali Greetings ! :)

So, this Diwali I had a few explosions with GIT,a tool budding developers hate as much as the pro developers adore.

[ LOL just check out the meaning of git :P It says "unpleasant or contemptible person". This will sooth you out if you have stumbled upon this post in frustration,desperately searching for your git solution. ]

So for those who are new to GIT, I must say it is a version control system, more here
In layman language, we all know is a complicated process to write and maintain code of projects especially when large number of people are involved, so git helps a lot. You can create branches, work in parallel on different features, undo the changes and do several other tasks involved in a simplified manner.




In this post we would be discussing a some use cases, i.e. what to do when a particular thing happens (based on my past experiences).

USE CASE #0
Usually when you are working on forked repo, you wish to get the changes done on the original repo too.You can easily do this by adding upstream.
git remote add upstream <git link of repo>

Now before doing any changes on local branch, do this:
1. git fetch upstream
2. git checkout master
3. git merge upstream/master

USE CASE #1
Deleting a file: (Do not do Shft+Del or Del directory. This will create problems.)
git rm <filepath>
git commit -m "Commit Message"

USE CASE #2
When you have done several not so useful commits, it becomes hard to follow in a PR, you can use git rebase. Eg for last five commits:  "git rebase -i HEAD~5" and squash them together and than git push --force ...
Have a look : https://www.atlassian.com/git/tutorials/rewriting-history/git-rebase-i

USE CASE #3
When working on different issues or features it is good to work on separate branches and create a separate PR from each one of them. This can be easily done by creating a new branch by using git branch -b <branch name>and checkout that, now work on that.
If you initially had just one branch and now wish to create a Pull Request with selected commits, use git cherry-pick feature, it's awesome!
So basically, do git log, it will show you all the commits. Now select the hash value of commit from which you which to create a new branch, so do :

You can create the branch via hash,
git branch branchname <sha1-of-commit>
or by using a symbolic ref.
git branch branchname HEAD~3
Now checkout to this branch,to include specific commits in it, use:
git cherry-pick <sha1-of-commit>

Do git log to get an idea of commits included in this branch.
Now do git push origin <branchname>
This will create the required PR.

So this was the first git chit.

Hope that helps!

Will see you in next post, hopefully soon, till then, keep hacking! :)


Saturday 19 September 2015

What emotions run through your playlist?

Hola !!

Long time. So I was upto creating this application one night , I named: "Playlist Emotions" , "What does the song says" :P , "PlayWithEmotions" and what not, each project of a failed experimentation.

Duh.

The project took way too long. Thanks to the noble idea of making and deploying it as a GWT application and then to improve upon the GUI of the app.
FYI , I tried but done neither of the things above. My Google Console developers trial account  supposedly has some issues with this app, yet to be resolved. So before the entire idea behind the app and the excitement of results it displays fades out , I thought, lemme write a blog post on the same.


So what is this all about?

The idea originated from a candid discussion with my friend on how songs influence our moods and also how our emotions affect the type of songs we listen to.

Being fascinated about knowing what kinds of songs I listen to, I thought of creating an application where I would just enter the folder location where my songs are and it would return me emotional composition of the songs I listen to.

Next stage was how to do that?

Logic is somewhat like this: When you share your music directory with me, I read the titles of all ,mp3 / .wav songs. Then the application extracts lyrics for those songs.

There exists no robust API that can give the lyrics of the song. Trouble multiplies when it is a Hindi Song, because we need to fetch the lyrics in English to do the sentiment analysis of the song.

So, indeed the program does a google search of "English Lyrics" + title of the song in your directory.
This gives me a list of links. I pick up the links resembling to either one of the following four trusted websites on lyrics , whichever is encountered first:
www.metrolyrics.com
www.lyricsfreak.com
www.hindilyrics.net (for Bollywood Songs)
www.bollymeaning.com (for Bollywood Songs)


Next step is scraping lyrics from these links. I studies the html structure of the websites and using JSoup library I finally fetched the string of my interest.

Then comes the third step of doing sentiment analysis, I did it using Synesketch .

"Synesketch analyses the emotional content of text sentences in terms of emotional types (happiness, sadness, anger, fear, disgust, and surprise), weights (how intense the emotion is), and a valence (is it positive or negative). The recognition technique is grounded on a refined keyword spotting method which employs a set of heuristic rules, a WordNet-based word lexicon, and a lexicon of emoticons and common abbreviations. Synesketch visualizes the emotions recognized in the form of real-time generative art. The art is partially based on Jared Tarbel’s algorithms and is inspired by the physics graphics of colliding particles."


And tadaa, I have the composition of emotions in songs I frequently listen too.
Mine was overall positive, with more of happy and surprise content :D If you want to try, find the app here:
https://github.com/nextLane/Playlist-Emotions

The code is open source, feel free to download and experiment. :)

This is how the raw application looks:


And when you get your results :D


The accuracy is challengable though, majorly because of two reasons:
1. Not the entire playlist is analysed, as in the trick that we applied to fetch the lyrics is usually applicable to around 70-80% songs, at times all, if you have named your songs properly in your playlist rather than random strings/numbers.

2. The Synesketch does sentiment analysis on words the song uses, we are equating the category of words with the category of songs, as in sad words corresponds to sad songs, This might not be the case always, for song also constitutes of musical beats , eh. Ok, just for clarification there is nothing like sad words, I just used it to indicate the set of words that can be categorized to a sad emotion. The details of it lie in the logic of Synesketch itself.
Detecting emotions in text is an ongoing research so high accuracy cannot be expected as of now.

So that was it, a whole night and the abstract thought of yesterday concreted into the application of today. Its fun to get your hands dirty into code this way.

See you in next post soon, with one more exciting creation/ exploration.

It would be great to hear your comments below!

Till then, keep hacking ;)

Adieu

Monday 15 June 2015

Get back your original pendrive size

At times situations come when you have to get things back, just take this case.

You master at crashing your OS again and again, due to one reason or the other, and then starts the endless quest for free pen-drives and isos :P

The people who have had an experience of giving their noble laptops and pendrives to you usually are not that enthusiastic to help you again
(I don't know if their last experience was bad or what) but anyways , you are now in search of one pen-drive, a pen-drive that can bring you your life back.

Now lets say a heavily loaded 16 GB pen-drive somehow becomes available by someone you know, but the pen-drive is indeed of a person, the some one you know , knows (heavy responsibility).

You take  a look at the pen-drive, your intentions are not at all noble, you want to convert it into a bootable pen-drive that can bring the electric spark back to your laptop . So you silently copy all the contents to your harddrive, download Power ISO (on someone else's laptop :P) and make the PD bootable, by brutally clicking the format option.

So now you have the pd in your hand, time to get your OS back, and you eventually get it back.
Now, lets clean the footprints , eh... get back the data to pd, delete power ISO and return people's stuff back to them.

So you insert the PD again, but whats that? Unable to copy back the contents because the volume is squeezed to 2 MB !!

Random options and cost of the PD and your trust and reliability as a person is at stake suddenly.

Chuck the rest of the story, here is how to get it back:

The problem is that the remaining space of your USB flash disk has become unallocated. To repair it, use diskpart (in windows):
  • Open command line (cmd) and type diskpart. Allow the windows to run it.
  • type list disk, and find the number of your USB flash disk.
  • type select disk X, and type the number of the USB disk instead of X.It should say that disk X is now selected.
  • type clean.
  • type create partition primary.
Now you should be able to use the flash disk as before. (You have to format it first)

Thanks to AskUbuntu.

So, now , return the stuff dude, and keep experimenting :P

Keep hacking!
See you in next post!

Monday 25 May 2015

Continuing with SignalR



Hola amigo!!!

Ella unnav? (How are you? in Telugu :D )

Anyways, so here we continue with the second part of making apps with SignalR, a pretty cool library, for first part refer:







So struggling to figure out how to implement signalR in console apps that with .NET Client, I finally got the way through it.

You need to have two separate projects(preferably):
1. Server 
2. Client

Inside Server:

I have a main class, a startup class and a hub.
Before starting make sure you have added relevant references beforehand.
How?
Right click the project name and select Manage NuGet Packages, install:
signalR .NET client : Microsoft ASP.NET SignalR .NET Client
and  also SelfHosting 

One thing that comes into scens and is the most important is Cross Domain Communication.

Both the server and the client are separate projects now, so the client must be able to identify and connect to the server running in parallel as a separate project. What changes do we need to incorporate with the same?

Here they are:

Majorly the Startup.cs OWIN class gets changed to support cross domain connection.
Refer this for more details on what it is:

http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#crossdomain

So the startup file is changed to:

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Cors;
using Microsoft.AspNet.SignalR;
 
[assemblyOwinStartup(typeof(BroadcasterConsole.Startup))]
 
namespace BroadcasterConsole
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    EnableJSONP = true
                    
                };
                map.RunSignalR(hubConfiguration);
            });
            
        }
    }
}


CorsOptions.AllowAll  will help your cross domain client to connect to te serevr. Also, please don't miss out the line:  [assemblyOwinStartup(typeof(BroadcasterConsole.Startup))]

Theses changes will make your server been detected and connected by the cross domain clients.

Rest of the server code is more or lesss the same as teh previous code. We need to have a hub class and a main class, I preferred to have them both in same namespace and it goes like this:

namespace BroadcasterConsole
{
    class Broadcast
    {
        static void Main(string[] args)
        {
            string url = "http://localhost:8088";
            try
            {
                using (WebApp.Start(url))
                {
                  //Have your code here
                }
 
        }
    }
 
 
 
 
    [HubName("broadcaster")]  
 
//Don't forget this line above, this name helps you to connect to the hub from the client side
    public class Broadcaster : Hub
    {
 
        public override Task OnConnected()
        {
            Console.WriteLine("Hub OnConnected {0}\n", Context.ConnectionId);
 
            return (base.OnConnected());
        }
 //Define your own hub methods
 
        public override Task OnReconnected()
        {
            Console.WriteLine("Hub OnReconnected {0}\n", Context.ConnectionId);
            return (base.OnDisconnected(true));
        }
    }
}


So, let's come back to the client side. I tried to have clients in different languages.

A peek into Javascript Client:

Firstly, include these scripts in this particular order:

   <!--Reference the jQuery library. -->
   <script src="Scripts/jquery-2.1.4.js"></script>
   <!--Reference the SignalR library. -->
   <script src="Scripts/jquery.signalR-2.2.0.js"></script>
 
 
   <!--Reference the autogenerated SignalR hub script. -->
 
   <script src="http://localhost:8088/signalr/hubs" type="text/javascript"></script>


Please see I have hosted my server on 8088 port, change it accordingly, as per the url of your hosted server.

Here goes your main connection code:

<script type="text/javascript">
       
       $.connection.hub.url = 'http://localhost:8088/signalr';
       var hubProxy = $.connection.broadcaster;
       hubProxy.client.addMessage = function (message) {
     
           //message is a c# struct Request object.
    
           // Add the message to the page.
           $('#discussion').append('<li><strong> ' + document.getElementById('displayname').value + ' received request  Name:' + message.Name +  '\n   Program:' + message.Program +  '\n     Input:' + message.Input
               + '</strong>:&nbsp;&nbsp;</li>');
       };
 
       $.connection.hub.start().done(function(){
       
           alert('Now connected, connection ID=' + $.connection.hub.id);
           $('#displayname').val(prompt('Which process are you?'''));
           hubProxy.server.registerMe(document.getElementById('displayname').value);
           $('#sendoutput').click(function () {
 
               hubProxy.server.getClientOutput({ "Name""JS Client""Result": $('#output').val() });
 
               $('#output').val('').focus();
           });
       });
     
      
   </script>


Its fine if you don't get any of the above code since it would be a bit out of the context you are into. just focus on highlighted lines.

Set the hub url, create a hub Proxy.
Prior to starting teh connection, add the client side methods that the hub can call, for example here we have: addMessage.
Then start the connection by this line:  $.connection.hub.start().done.

You can call server side methods by : hubProxy.server.getClientOutput (//required params)


There we finish with the JavaScript client, we can do the same with clients for different languages:

.NET Client:

//Set connection
           var connection = new HubConnection("http://localhost:8088/");
//Make proxy to hub based on hub name on server
           myHub = connection.CreateHubProxy("Broadcaster");
           
//Add client side methods

           myHub.On<Request>("addMessage", param =>{
              //Define your method
           });
 
//Start connection
           connection.Start().ContinueWith(task =>
           {
               if (task.IsFaulted)
               {
                   Console.WriteLine("There was an error opening the connection:{0}",
                                     task.Exception.GetBaseException());
               }
               else
               {
                   Console.WriteLine("Connected");
 
               }
 
           }).Wait();
 //Invoking hub methods

           myHub.Invoke<string>(<Method Name as is>, clientName)


C++ Client:
Here is a detailed guide to do the same with C++. 
https://github.com/aspnet/SignalR-Client-Cpp

It is pretty simple to use, in case you have any queries, leave in comments below. So that was all folks, see you in next post! Till then, Happy Hacking! Meanwhile, get your signals across using SignalR :D



Tuesday 19 May 2015

My Experiments with Truth, oops sorry, SignalR

So what have I been upto these days is a really cool library SignalR

Wanna know more about its where and how abouts? Visit this:


 


 So , after a little researching I got to know you can create two sorts of clients here: JavaScript and .NET clients.

If your mind is like: What Clients?
Dude, you have not gone through the video, eh? :P

Anyways, so Signal R actually facilitates real time conversation, the ones you see in chats like IRC (Internet Relay Chat) . So a message can be broadcasted simultaneously to multiple clients and you can make it possible to gather the responses from the client too.

I have not yet covered the thread safety and async-ness into consideration but overall my code goes somewhat like this:
You can create a broadcast server, that is essentially the hub.

The major files I have are these:
1. Hub Class: Right click your project and select add item>SignalR Hub Class v2

Make sure you are creating a web application in visual studio, prior to doing this otherwise this option may not come.
Also, this way it helps adding all relevant SignalR references to your project.
The hub class has simple code as:

public class BroadcastHub : Hub
  {
      
      public void Send(string input)
      {
          Clients.All.broadcastMessage(input);
      }
 
      public void Receive(string name, string output)
      {
          System.Diagnostics.Debug.WriteLine(name + " has given output:" + output);
      }
 
  }


2. Owin Startup Class: Right click the project name and select add item> OWIN startup class.

While I am still in a process to learn more about OWIN, the most I can tell you is :
"OWIN is a specification that defines an API for framework and servers to cooperation. The point of OWIN is to decouple server and application. For example, ASP.NET Identity uses OWIN security, SignalR self hosting uses OWIN hosting, and etc., the examples all use OWIN, therefore they all need to have a startup class, that is defined in "Startup.cs" file."

So inside your startup.cs owin class you would be having code like:
 
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
 
[assemblyOwinStartup(typeof(ServerBroadcast.Startup))] namespace ServerBroadcast
{     
public class Startup     
{         
public void Configuration(IAppBuilder app)         
{             
app.MapSignalR();         
}     
}
}

3. Client : I have javascript client so it was basically an html page. I named it FakeClient.
Major methods it uses:
<script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var chat = $.connection.broadcastHub;
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (message) {
                // Html encode display name and message.
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#discussion').append('<li><strong> ' + document.getElementById('displayname').value + ' received '
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Which process are you?'''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                    $('#sendoutput').click(function () {
                  
                    chat.server.receive(document.getElementById('displayname').value, $('#output').val());
                    
                    $('#output').val('').focus();
                });
            });
        });
    </script>

From the code, it is evident that once we get connection from the hub in var chat, we can access the server and client part of it as, chat.server.receive, note that receive method is defined in my hub and chat.client.broadcastMessage , broadcastMessage has been a defined method for signalR client.
 
 
 


4. Broadcaster: Since I wanted to give a face to my hub too so I created one more html page and set hat as the start page.

It has simple code as:

<script type="text/javascript">
       $(function () {
           // Declare a proxy to reference the hub.
           var chat = $.connection.broadcastHub;
                   
           // Set initial focus to message input box.
           $('#message').focus();
           // Start the connection.
           $.connection.hub.start().done(function () {
               $('#sendmessage').click(function () {
 
                   // Call the Send method on the hub.
                   chat.server.send($('#message').val());
 
                   // Clear text box and reset focus for next comment.
                   $('#message').val('').focus();
               });
               $('#addclient').click(function () {
                   window.open('http://localhost:44621/FakeClient.html''_blank');
                   window.focus();
 
 
               });
           });
       });
   </script>
 
 
 
So that's pretty much it and you are done, with signalR implementation.
 
Next we would be covering on how to do the same with .NET clients...
Till then see you!
 
Happy hacking!
 


 

Tuesday 17 March 2015

Introduction to Clustering using R

We all have heard of Big Data a lot! Want to try basic clustering techniques on it?

Here we go. Before beginning into the coding , lets familiarize ourselves with some basic terms and platforms to do this thing.

1. What data are we studying?
For this purpose we would be studying Twitter, there are well equipped APIs to study the tweets that too in varied languages, eg, twitteR in R (stastical tool), tweetPy in python.

2. Tools we would be using: R
Get yourself quickly familiarized with R by following these links:

http://www.r-bloggers.com/how-to-learn-r-a-flow-chart/
http://tryr.codeschool.com/

And while searching for the relevant links, I have found this course for you, you may want to attend:

https://www.coursera.org/course/rprog


3. What we aim to do?
Collect the list of friends and followers for any one person's twitter account.
We would make use of user class of twitteR for the same.
It has following fields:
  • name:Name of the user
  • screenName:Screen name of the user
  • id:ID value for this user
  • lastStatus:Last status update for the user
  • description:User’s description
  • statusesCount:Number of status updates this user has had
  • followersCount:Number of followers for this user
  • favoritesCount:Number of favorites for this user
  • friendsCount:Number of followees for this user
  • url:A URL associated with this user
  • created:When this user was created
  • protected:Whether or not this user is protected
  • verified:Whether or not this user is verified
  • location:Location of the user
  • listedCount:The number of times this user appears in public lists
  • followRequestSent:If authenticated via OAuth, will be TRUE if you’ve sent a friend request to this user
  • profileImageUrl:URL of the user’s profile image, if one exists
and several methods. To look into what all things twitteR API offers, check out this: http://cran.r-project.org/web/packages/twitteR/twitteR.pdf 

So, what we intend to do on the basis of this information is quite simple (and not that useful :P ) but may serve as a good introduction to clustering.

We accumulate a set of users on twitter, by fetching a twitter user's friends and followers as User class objects . We take the union of these users. Now we plot a graph friends vs followers, where each dot is a 2 D / 3 D entity containing friends' count, followers' count and/ or statuses' count.

We use inbuilt K-means clustering algorithm in RStudio to do the clustering on this data.
Pondering what is K-means? Check : https://sites.google.com/site/dataclusteringalgorithms/k-means-clustering-algorithm
or several explanatory videos available online.

So basically, here we have a feature vector of 3 features per user:
1. friend's count
2. follower's count
3. statuses'  count

On the basis of similarity measure, we cluster the data points together on the basis of similarity wrt to these 3 features.

***Check out what similarity kmeans internally uses in R and answer in comments if you find one, I guess it is cosine similarity. ***

These clusters can be further colored to mark density.

Follow the code given in this link to do it by yourself:

http://rstudio-pubs-static.s3.amazonaws.com/5983_af66eca6775f4528a72b8e243a6ecf2d.html


I used and tweaked the code a bit to do kmeans clustering on "modi" as user and used 2 features : friends count and followers count for first and
3 features: friends count , followers count and statuses' count for the next, this is what we attained:

  
 2 Features

                                                 3 Features


PS: It is a 2D graph still but the clusters have been redefined, I put k=5 for this, where k stands as the number of clusters we wish to generate using the kmeans algorithm.


So that's it for now. I hope it would have been interesting and useful.
There exists lots of exciting relevant stuff online, keep checking!

See you in next post, till then
Keep Hacking! :)

Saturday 14 March 2015

Diving Deep | Android

So here I am building my weather app on android studio, that would essentially fetch weather forecast for upcoming days. (covers lessons 1-3)

Check out:
https://github.com/udacity/Sunshine-Version-2

for more details on code we would be deliberating upon in this post. The post essentially doesn't deals with the whole details, it gives an idea on what kind of methods exist and their purpose and how it is all connected in an android app. Budding developers may find it a bit useful.

Since I have come a long distance till now, lets quickly sum up the way it is working as of now:






I have four main java classes till now:

1. MainActivity

2. Forecast Fragment

3. Detail Activity

4. Settings Activity

Let's peek into and see what these files are actually doing:

1. MainActivity: This extends ActionBarActivity
It has some basic overridden methods like:
(i) protected void onCreate(Bundle savedInstanceState)
It sets the content view to some layout XML using setContentView method.It sets the view to activity_main XML, it just has a framelayout component named container.

Then we have, onCreateOptionsMenu, this essentially inflates the main xml of menu. It has the xmls adding items like settings and refresh to it.

Then we also have one method named onOptionsItemSelected which deals with events related to selecting something from the menu bar. Comparisons like item.getItemId()==R.id.action_settings are done inside it.


2. ForecastFragment : One of the lengthiest.
It extends Fragment Class.
A Fragment is a piece of an application's user interface or behaviour that can be placed in an Activity.
In its core, it represents a particular operation or interface that is running within a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own life cycle, that life cycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed.

What does it particularly deals with?

Well, that is the list of weather forecasts we wanna display. To populate the list we need to have data in some form. To do the entire thong, we need to have ArrayAdapter

  Then we have all the overridden methods:
(i)  public void onCreate(Bundle savedInstanceState)
This just setOptionsMenu true so as to detect the presence of Menu Bar for the app.

(ii) public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
This inflates the menu view having refresh feature.

(iii) public boolean onOptionsItemSelected(MenuItem item)
It features the utility that is what will happen when refresh is clicked.
We used Shared Preferences and corresponding preference manager to generalize the input for city in which we need to check weather.
 We also created the object of async class FetchWeatherClass to fetch weather from the API in background.

(iv) public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
It inflates the required layouts and xmls
Creates array list and adds ArrayAdapter to it.
Components of ArrayAdapter :
1. The current context (this activity)
2. The name of the layout ID.
3. The ID of the textview to populate.
4. The array list i.e. weekForecast in this case.


We use listView object to display the list of weathers fetched. This list View is attached with the ArrayAdapter. A setOnItemClick listener is also attached to it so that on clicking any list item a different screen (activity) may come up using Intent.

Syntax for Intent is worth a deep glance:
Here it goes:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String forecast = mForecastAdapter.getItem(position);
                Intent intent = new Intent(getActivity(), DetailActivity.class)
                        .putExtra(Intent.EXTRA_TEXT, forecast);
                startActivity(intent);

            }
        });


We also have an inner class in this:
public class FetchWeatherTask extends AsyncTask<String, Void, String[]>
 This is essentially to retrieve and parse JSON data retrieved from the API into string array.
The doInBackground method essentially helps in URL construction and http connection to the API.
onPostExecute does the required add ons/ changes to the adapter to reflect the fetched data.

3. Detail Activity:
 Quite simple class. It extends ActionBarActivity too as the main activity does and also has an inner fragment class as a placeholder
The onCreate, onCreateOptionsMenu and onOptionsItemSelected methods have the same functionality as they are in the main activity apart from the required changes related to fragment.


The inner class  DetailFragment with the significant onCreateView method holds some significance , making canges to the displayed text view in accordance with the intent object it has received.

4. Settings Activity:
This extends the PreferenceActivity   class and implements the interface: Preference.OnPreferenceChangeListener
It makes use of xml file namely pref_general.
We do addPreferencesFromResource(R.xml.pref_general);
and  bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));

The second method Attaches a listener so the summary is always updated with the preference value. Also fires the listener once, to initialize the summary (so it shows up before the value is changed.)

Third method is : public boolean onPreferenceChange(Preference preference, Object value)
For list preferences, look up the correct display value in the preference's 'entries' list (since they have separate labels/values).
For other preferences, set the summary to the value's simple string representation.


Please note corresponding changes are being done in AndroidManifest file parallely.


So, that's all for now. Hope this post proves useful in some way. I just experimented on the ways an app's actual functionality can be understood from the point of view of a beginner.
Feel free to drop suggestions below.

Have a great day!

Keep hacking till then! :)




Saturday 14 February 2015

Beginning with jQuery

As a demand of upcoming project and a desire to try my hands on some front-end tools, here is my first post on UI designing.

I would be experimenting with jQuery.

Oops my XAMPP is not installed, I remember the recent system crash I had.
Anyways, go to this site:

http://irishlightandcolour.blogspot.in/2013/10/install-xampp-for-linux-on-ubuntu-1204.html

Install XAMPP.
Give rights that is sudo chmod 577 to the executable file you just downloaded and then do sudo  ./<filename> as described in the link.

Once done, start the server.
Why did you do this?

Because to run php scripts we need a server, xampp help us create a local host where we can test our website/ scripts.


 Click on "Go to application". Open Google Chrome manually if some error comes.
You will see this screen:


Now what? Write a script, php one or may be some html page.

Cool. Now navigate to opt> lampp> htdocs > xampp
Code your first php script/ html page here.

I tried using simple jQuery draggable component.
Code this:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">

<style>

#draggable { width: 250px; height: 250px; padding: 0.5em; background-image: url(http://icons.iconarchive.com/icons/double-j-design/origami-colored-pencil/256/red-heart-icon.png); }
</style>
<script>
$(function() {
$( "#draggable" ).draggable();
});
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content" f>
<p> #Valentine's Day!</p>
</div>
</body>
</html>

#Source: http://jqueryui.com/draggable/

Play with this code now. And do the required changes. You are done with your first draggable user interface! This is how it looks like in my case:

 After dragging:



Kudos!

Keep hacking!




A secret love message ~

Hmm, so the trick of putting up a catchy seasonal title worked out, we got you here! Folks, we will be talking about a really cool tech...