Design Pattern: Singleton

“Beauty!”, when I see some really amazing code that is my first reaction, but what makes a piece of code beautiful? Is it neatly named variables? Is it the uniform indentation?

Well the answer is yes but there is something a little more than these factors and that is an elegant  solution to the problem. When I say elegant solution what is that I am talking about ? What makes a solution elegant? It is the way you approach a problem.

Design Patterns in the programming world adds to the beauty of the solution, it sometimes feels that it is the missing piece of the puzzle. And the solution so magically fits to solve the problem. The various patterns that I came across are Singleton, Mixin, Pub-Sub etc. The way I approached it and studied them is a little different, design patterns are actually tailored way to react to a given situation.

Let me elaborate on that now suppose there is an emergency and somebody got hurt, what is the first thought that comes to your mind ? It is to handle it using First Aid, this is actually a catered thought which has been imbibed in us from ages and people have design First Aid boxes in such a way that it has all the first come fixes for all the emergencies.

For me I see Design Pattern in the same manner it has gone through the test of time and proved to be the best way to solve a specific type of problem.  It is like a ready made template but you should be aware enough to know the problem and to know the pattern that solves that problem. 

I have read about a lot of design patterns but to be very frank I have seldom seen one being applied in the code-base that I have came across, this could be because I have not appreciated it much and also because I was not able to observe the pattern. It was very recently when I was working with Gautham Sir I began to appreciate the beauty of it. We were writing a utility in jnaapti using EcmaScript 6. He made me feel to appreciate the beauty of it and taught me how to implement it as well.

Let us break it down more and see the type of problems in which Singleton design pattern can be used.

What is Singleton design pattern?

A Singleton design pattern puts a restriction of returning the same object irrespective of how many times the class is being instantiated. This makes sure that whatever is the state of object that state is preserved. Don’t be overwhelmed if you are not able to understand it now it will make more sense once you see the code.

The benefit you get is having a kind of a global store where you can put in data and retrieve it when you desire to.

Lets us make it more clear imagine there is a class Library now through out the life cycle of the software what we want is there should be only one Library object and when ever I get this object I should be able to add and delete books from the library hence modifying the library now when I do this the library object anywhere being use should get this information.

Lets chalk out some code and try to understand it, I have 3 files Library.js, Customer.js and LibraryPlayGround.js.  The content of those file are very straight forward.

es6-12
Library.js

Now we need customers or readers for simplifying things i have only included on one method that is return books.

es6-2
Customer.js

Once all this is done we need a playground where we can see things happening and experiment with it.

es6-3
LibraryPlaygroud.js

Now if you see the code farhaan object has tried to access the same Library object that is being exported. No matter what it well return the same instance which has been instantiated in the beginning of the lifecycle of the software. This is how I tried implementing Singleton .

I have used ECMAScript here to demonstrate that concept and to implement it, I am a learner so there could have been certain things I wouldn’t have made clear, you can leave a comment regarding the same, if you have something to add I would love to know.

Till then Happy Hacking

Weechat-Tmux

Weechat-Tmux

Recently I have been to pycon-india (will blog about that too!) there Sayan and Vivek introduced me to weechat which is a terminal based IRC client, from the time I saw Sayan’s weechat configuration I was hooked to it.

The same night I started configuring my weechat , it’s such a beautiful IRC client I was regretting why did I not use it before. It just transforms your terminal into IRC window.

For fedora you need to do:

sudo dnf install weechat

Some of the configuration and plugins you need are :

  1. buffer
  2. notify-send

That’s pretty much it but that doesn’t stop there you can make that client little more aesthetic.  You can set weechat by using their documentation.

The clean design kind of makes you feel happy, plus adding plugin is not at all a pain. In the weechat window you just say /script install buffer.pl and it just installs it in no time.  There are various external plugin in case you want to use them and writing plugin is actually fun , I have not tried that yet.

screenshot-from-2016-09-30-23-02-13

I also use to use bigger font but now I find this size more soothing to eyes. It is because of weechat I got to know or explore about this beautiful tool called tmux ,  because on normal terminal screen weechat lags , what I mean by lag is the keystroke somehow reach after like 5-6 seconds which makes the user experience go bad.  I pinged people on IRC in #weechat channel with the query the community is amazing they helped me to set it up and use it efficiently , they only told me to use tmux or screen . With tmux my session are persistent and without any lag.

To install tmux on fedora:

sudo install tmux

tmux is a terminal multiplexer which means it can extend one terminal screen into many screen . I got to learn a lot of concepts in tmux like session, pane and windows. Once you know these things in tmux its really a funride. Some of the blogs I went through for configuring and using tmux the best I found was hamvoke , the whole series is pretty amazing . So basically my workflow goes for every project I am working on I have a tmux session named after it, which is done by the command:

tmux new-session -s <name_session>

Switching between two session can be done by attach and detach. And I have one constant session running of weechat. I thought I have explored every thing in tmux but that can’t be it , I came to know that there is a powerline for tmux too. That makes it way more amazing so this is how a typical tmux session with powerline looks like.

screenshot-from-2016-09-30-23-31-10

I am kind of loving the new setup and enjoying it. I am also constantly using tmux cheatsheet 😛 because it’s good to look up what else you can do and also I saw various screencast on youtube where  tmux+vim makes things amazing.

Do let me know how you like my setup or how you use it .

Till then, Happy Hacking! 🙂

 

Vacation Of Code

Vacation Of Code

This all started when pingou gave me the opportunity to write a utility which helps to user to edit comment on pagure.Now for those who don’t know what pagure is , so pagure is open source equivalent of Github, to be precise :

Pagure is a light-weight git-centered forge based on pygit2. Currently, Pagure offers a web-interface for git repositories, a ticket system and possibilities to create new projects, fork existing ones and create/merge pull-requests across or within projects.

So the utility that was allotted to me was an edit button that privilege the owner of the comment to modify the comment on the pull request. That sounds really simple but writing the whole code and modifying others code are two different things.

I finally started exploring Flask and its feature so Flask is framework  that helps you write servers , Server as the name suggest is use to serve request.I had a brief idea about the type of request but never got the chance to explore it.

There are many types of request that help the client and server to talk to each other  famous ones are POST and GET.

The GET method

The GET method is the method used by the browser to ask the server to send back a given resource: “Hey server, I want to get this resource.” In this case, the browser sends an empty body. Because the body is empty, if a form is sent using this method, the data sent to the server is appended to the URL.

The POST method

The POST method is a little different. It’s the method the browser sends the server to ask for a response that takes into account the data provided in the body of the HTTP request: “Hey server, take a look at this data and send me back an appropriate result.” If a form is sent using this method, the data is appended to the body of the HTTP request.

Source: MDN

So in first attempt I wrote a shabby code and somehow make it work , but as I told it was really shabby so pingou and subho told me to use hidden form technique which is used to trigger certain functions without actually making the user know what is going on . It is more of a hack to get things done your way.The problem I faced was delete comment and edit comment use the same form to send request so both have the same end point hence inside the function that deletes comment I devised a way to distinguish how to differentiate when to edit comment and when to delete it.

The algorithm was simple get comment id , get new comment , replace the old comment by new one and make entry in the database.The code snippet that really helped me to understand things to a new depth was:

Example

Consider the following form:

<form action="http://foo.com" method="get">
  <input name="say" value="Hi">
  <input name="to" value="Mom">
  <button>Send my greetings</button>
</form>
With the GET method, the HTTP request looks like this:
GET /?say=Hi&to=Mom
HTTP/1.1 Host: foo.com
Example

Consider this form (the same one as above):

<form action="http://foo.com" method="post">
  <input name="say" value="Hi">
  <input name="to" value="Mom">
  <button>Send my greetings</button>
</form>

When sent using the POST method, the HTTP request looks like this:

POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

say=Hi&to=Mom
 My Pull request is still under consideration so you can actually check what I did in pagure. Do let me know what you think about it.

Telegram Bot, this is how you do it!

Telegram Bot, this is how you do it!

I have been wondering about writing telegram bots, so while searching about it I landed on this link Python telegram api. This fueled my curiosity to write my first telegram bot. I searched for many ideas and I was too late to implement them because others have already implemented it.

Then while having a conversation we came across the idea of having a lmgtfy bot to answer silly question , then tools met requirements and voila  lmgtfyou_bot was born. (Yeah! you got it right, every other name was taken.)

So, yeah you need to install a pip package mentioned in the link above. Before going into details let me discuss something about ‘polling’.

There are two type of models namely polling and observer model. Polling means the function keeps on pinging the application to see if something changed while in observer model it’s like tell me if something changed.

Imagine a very irritating waiter who is disturbing you in every 10s about your order now that is polling while you calling a waiter when you are ready is observer pattern.

Here Telegram api is using a polling pattern to get change in the event , for us it is new messages.Now there is a lot of things that is happening in the code. Let me walk you through it

 
try:
 LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
except IndexError:
 LAST_UPDATE_ID = None

So let’s see whats going on here. getUpdates() function returns a list of updates which is a composite data containing various metadata about the message like text, username , date etc. Here, update_id is taken from the latest update i.e message hence [-1]. update_id keeps on increasing with every incoming message. We use this to control our script which running in an infinite loop.

 
 while True:
   fetch_url(bot)

fetch_url is being called infinite number of times which is being controlled by LAST_UPDATE_ID variable.

 
def fetch_url(bot):
 global LAST_UPDATE_ID

 # Following is a dictionary of commands that the bot can use

 commands = {'/help':"You can add me in any group or text me! I don't have aceess to the group message so you need to call me by my name i.e @lmgtfyou_bot or start your senstence with '/' , I listen to the keyword 'means' ", '/start':'I am always listening to you. Just use magical words'}

 magic_words = ['means','mean','/means','/mean']

 for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=10):
     chat_id = update.message.chat_id
     message = update.message.text.encode('utf-8')
     message_list = message.split()

     if(message in commands):
         bot.sendMessage(chat_id=chat_id, text=commands[message])
         LAST_UPDATE_ID = update.update_id + 1

     if ( list_compare(magic_words, message_list)!= -1):
         search = message_list[list_compare(magic_words, message_list)-1]
         url='http://lmgtfy.com/?q='+search
         bot.sendMessage(chat_id=chat_id,text=url)
         LAST_UPDATE_ID = update.update_id + 1

Most of the code is self explaining, but last line of the if block is kind of a base case which is helping to control the actions.

You can host the code on openshift for free, just set up an instance write the code in app-deployment folder and ssh into the instance. Now, in the instance run the script normally and put it in the background.That’s all for this time have a nice hack.

Feel free to fork and contribute to my repo on GitHub.

Python And Cricket

Python And Cricket

“Indiaaa Indiaaaaa!!”  there is only one time when  our diverse country unite as Indians and that happens when India is playing against Pakistan and that too specially in cricket. I have a little confession to make I am not a cricket fan . I don’t like cricket but even I watch India v/s Pakistan because it is not only cricket it is something more than that and me being a Geek cannot get my hands away from my MacBook so I ended up writing some code related to the match.

So, I am actually getting my hands dirty with Python . To all the PETA people out there , I am not doing anything with snakes. Yeah, so getting back to it I was actually going through all the tweets on my page and there was a flood of tweets for IndiPak match so I thought why not write a script to do that for me just out of curiosity .

The requisites for that is you need to install the python library called tweepy for that you can do “pip install tweepy”. Once that is done you need to register yourself for making twitter application on https://apps.twitter.com . Once you get the consumer key and access token you are good to go.

Now, one more thing you need to seed this script with another file having all the slogans . The code is published on github, you can use that script and make amends , you can even push them on github :

https://github.com/farhaanbukhsh/tweetpy

Till then , peace out !

hvhv