Creating an autocomplete field | Setting up the backend | Part 1

Hello folks, so my exams are over and its time to roll. LOL pretty excited here. I am creating this series of two articles in which we will download all the pincodes (or zipcodes), add them to a MySQL database, write an API in PHP to retrieve the data in JSON, and finally we will write our form, in which, when we enter a pincode, we automatically get the ‘taluka’, ‘district’ and ‘state’ fields filled. So lets begin.
(and if you are from outside India, a ‘taluka‘ is a small region, like a city)

Step 1 – Getting the Pincode list

This was my biggest concern. Where do I get a list of all the pincodes in India. I could write a script and iterate through all the possible pincodes from 100000 to 999999, but, of course, there had to be a better way (and by the way, I would have got banned by the site if I sent around a million requests in a short period of time).
Fortunately, after some googling, I found a list here, at data.gov.in, to directly download the list, click here. The data is in .csv format, which is essentially a text document with some proper ordering (LOL).

Step 2 – Setting up MySQL database

We will now add the values to a database with will serve as our source to retrieve data in the form. I am selecting MySQL because, well, that is the only SQL I currently know (wink!). I assume you know the basics of how to create a database, and even if you don’t, you can do it easily by using the  phpmyadmin. It is graphical, and will get the work done.

The columns available for inserting data are:
officename,pincode,officeType,Deliverystatus,divisionname,regionname,circlename,Taluk,Districtname,statename

I will be using only ‘pincode’, ‘Taluk’, ‘Districtname’, ‘Statename’ here to avoid any unnecessary cluttering.

Create a database: ‘turnouts’
Create a table: ‘pincode’
Create 4 columns: ‘pincode’, ‘taluka’, ‘district’, ‘state’
Needless to say, these are just names and you can have what you want, but just don’t go insane over them. This is how it should look, or similar.
Having done that, move to step 3.

Step 3 – Writing the PHP script to enumerate database

So now we need to fill those database fields with data. If you take a look, the .csv file that we downloaded has around 152,000 lines. We can insert them manually, but that would take two and a half month, so we are better off writing a script. Language is on you. Python would work, but I preferred PHP, no good reason, I just choose it.
Basically we read a line in the file, select the data that we are concerned about, generate a MySQL query dynamically in a loop, and execute the query. Then move to the next line till feof or end of file.
Here is the php code.
<?php
$file = fopen("pincodes.csv", "r") or die("Open file");
$server = "localhost";
$username = "root";
$password = "password";
$db = "turnouts";
$conn = mysql_connect($server, $username, $password);
mysql_select_db("turnouts") or die();
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
while(!feof($file)) {
$line = fgets($file);
$words = explode(",", $line);
$pincode = $words[1];
$taluka = $words[7];
$district = $words[8];
$state = $words[9];
$sql = "INSERT INTO pincode (pincode, taluka, district, state) VALUES ('$pincode', '$taluka', '$district', '$state')";
mysql_query($sql, $conn);
mysql_error($conn);
}
fclose($file);
mysql_close($conn);
?>

This code will take some time to execute. On my low end box, it took 90 minutes approx. After having executed, you should have a database with some real data. Here’s the row count, a whooping 154,797.

Now that we have our database setup, we are all set to write the front end. To make it easy to follow, I will write it in the second part of this series.

Edit: Here is the Part 2 Enjoy!

Simple group messenger/chat in Python

Aaaaannd here is another post of mine on sockets, client/server models and stuff. I suppose you have started to get bored by the same stuff everyday right? Seems like I just can’t get enough of this thing. But trust me, I had no intention of doing this today, a friend of mine instigated me write a messenger for a project we were working on, and it turned out, writing this simple messaging program was more interesting than I thought.

So, instead of creating a straight forward chat program that was ‘actually’ required by my friend, I created this ‘one-server-multiple-clients’ program, which is more like the real world chat apps we use everyday.

To run the program, execute the ‘server.py’ (after changing the bind() address to the address of the server on which it is supposed to run). Then, execute the ‘client.py’ (guess what? same thing here. But you will have to add the server address in the connect() function here). Of course, you can have all of them running on the same system, but there ain’t any fun in it, right?

Last but not the least, I have commented as much as I could, unlike my last article, so I expect everyone reading this, with a bit of programming knowledge, will understand this straight forward code.

server.py

# Import the necessary libraries
import socket
import sys
import select
# Take message from an host and send it to all others
def shout(sock, message):
  for socket in LIST:
    try:
      # Don't send it back to server and yourself!
      if socket != serv and socket != sock:
        socket.send(message)
    except:
      # Assume client has got disconnected and remove it.
      socket.close
      LIST.remove(socket)
# Declare variables required later.
# To store list of sockets of clients as well as server itself.
LIST = []
# Common buffer for all purposes
buff = 1024
# Declaration of Server socket.
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serv.bind(("192.168.1.10", 1356))
# Listen for upto 6 clients. Increase if you need more.
serv.listen(6)
# Add server socket to the LIST
LIST.append(serv)
while 1:
  # Moniter clients all simultaneously
  reads, writes, err = select.select(LIST, [], [])
  for sock in reads:
    # A new client connected?
    if sock == serv:
      sockfd, addr = serv.accept()
      LIST.append(sockfd)
    # Naah, just a new message!
    else:
      try:
        # Get his shitty message.
        data = sock.recv(buff)
        if data:
          # If he wrote something, send it to shout() function for broadcast.
          shout(sock, data)
      except:
        # Shit just got real. Client kicked by server :3
        sock.close()
        LIST.remove(sock)
        # Do this till the end of time.
        continue
serv.close()

client.py

# Import the nessary libraries
import socket
import string
import select
import sys

# Socket variable declaration
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)

# Connect to server. Change this for remote servers.
s.connect(("192.168.1.10", 1356))

# A prompt asking client to enter something.
sys.stdout.write(">")
sys.stdout.flush()

while 1:
  # These are the possible events.
  # sys.stdin --> Client has typed something through keyboard.
  # s --> Server has send a new message by some other client you.
  streams = [sys.stdin, s]

  # Moniter both the streams simultaneously for inputs.
  readable, writable, err = select.select(streams, [], [])

  # If server has sent something, readable will fill up.
  for sock in readable:
    if sock == s:

      # Receive data in our variable. Check if it is empty.
      data = sock.recv(1024)
      if not data:
        sys.exit()
      else:

        # Write data to stdout and give client prompt back.
        sys.stdout.write(data)
        sys.stdout.write(">")
        sys.stdout.flush()

    # No, its not the server. Our client has typed something in.
    else:

      # Read message. Send it to server. Give prompt back to client.
      msg = sys.stdin.readline()
      s.send(msg)
      sys.stdout.write(">")
      sys.stdout.flush()

So that was the code. Here is a glimpse of the output. The server is running off my ‘raspberrypi’ and all clients are running on my computer. Looks cool right?

If you look closely, one of the clients missed a message sent by another client, LOL, so that is normal. Any suggestions or edits or corrections, drop them in the comments below. 🙂

Python vs C – How simple is it to write a pair of communicating sockets?

Lately I have been reading a lot of articles online written to compare Python to other languages. It is not a secret to anyone that the Python community is growing, and along with it, is the number of people who promote/recommend this language, of course.

Let me not add up to the already large mass of those articles by boasting about Python’s usability, speed and practicality, but rather, I will compare the two languages by writing a small socket client/server pair in each of those languages.

But first, let me give you some of my personal opinions about both the languages since I know them well enough. C is very dear to me, not only because it was the first language I had ever learnt, but also because it runs most of the GNU, and GNU is well, very dear to me! C also happens to be my only second language of choice, after Python (although I know bits of Java, I prefer not to use it, not sure why, but I hate it). I have been programming in Python only from the last couple of months and I was really impressed. I solve HackerEarth and CodeChef problems as a pass time. Although I could do all of the problems I have done in C, doing them in Python took like 1/10th of the time (literally!) and 1/10th the typing effort. I would admit, C is much more fun to write than Python, simply because you ‘feel’ the code is yours, and I love to code C whenever I am free, will I use it in an environment where time is the priority? Probably not. Maybe when C is the only way out, but most of the time, I am better off writing it in Python.

That being said, the popularity of C doesn’t get any less, and it is going to stay that way as long as, maybe the Internet. Here’s something I found.

https://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
You see the thing on top there? Yes, it is there for a reason. To make it short, C is powerful, very powerful. C gives you access to things you can not really imagine in other languages. On the other hand, Python is practical, flexible, and easy to learn. Web apps, sockets, Raspberry Pi, Arduino, Android or anything else you can imagine, there has to be a library made for it by someone, somewhere.

The code part.

I am giving the client and server code in both the languages here as is. No explanation and stuff, because that’s not the topic here. Note that all the source codes are tested running OK on Kali 1.0.6, gcc and all stock stuff, so it should be not much trouble to get it running. Windows guy, search for gcc directory and run it over the command prompt. It won’t run from any IDE.

Python

Writing a pair of communicating TCP sockets require around 30 minutes along with the understanding part, if you have got some background in networking. Python does most of the stuff for you, and you just create a socket variable, supply host and port and that’s it. Rest is left to your imagination (or not, I got too carried away!). Here comes the code:
client.py

import socket
s = socket.socket()
host = socket.gethostname()
port = 1356 
s.connect((host, port))
shit = s.recv(1024)
print shit
s.close()
server.py

s = socket.socket()
host = socket.gethostname()
s.bind((host, 1356))
s.listen(5)
while True:
    c, addr = s.accept()
    c.send("Message from server")
    c.close()

And that is it. Even if it looks lame (which it is), it is the maybe the simplest thing that qualifies to be called a server/client.

C

Now lets write the same in C. This is around 4 times the size of Python code, and much of the stuff are done by hand (nothing new for C, I suppose). This code is the shortest I could cut it to, and just does one simple task. Sends the “Client talking loud!\n” message to server over port 1356 on localhost. The parameters can be edited as per convenience to suit any inter network testing, but that’s the most this code will do. Nevertheless, this is a TCP client/server model.
client.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>

int main(int argc, char **argv) {
int sock, port, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
port = atoi("1356");
sock = socket(AF_INET, SOCK_STREAM, 0);
server = gethostbyname("127.0.0.1");
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(port);
connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
bzero(buffer, 256);
strcpy(buffer, "Client talking loud!\n");
write(sock, buffer, strlen(buffer));
close(sock);
}

server.c

#include <stdio.h> 
#include <strings.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


int main(int argc, char **argv) {
int sock, nsock, port;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
sock = socket(AF_INET, SOCK_STREAM, 0);
bzero((char*)&serv_addr, sizeof(serv_addr));
port = atoi("1356");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
bind(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
listen(sock, 2);
clilen = sizeof(cli_addr);
nsock = accept(sock, (struct sockaddr *)&cli_addr, &clilen);
bzero(buffer, 256);
read(nsock, buffer, 255);
printf("%s\n", buffer);
close(sock);
close(nsock);
}

Here is the expected output:

Sorry, there is no commenting in the above code, and it really needs some explanation. I would’ve written them, but then, the code would have grown three folds (LOL)! It will need another nice article to explain all the stuff from that client.c and server.c code. I will conclude here. Thank you for reading 🙂

Update: If you happen to run any of the above code, make sure you run server first!

Top reasons why you should start using Mozilla Firefox right now

If you have visited my blog a couple of times, it must be clear to you by now that I am a Mozillian. I love their way and goals and in this world dominated by corporate giants, they are like a candle in the darkness. I promote Mozilla everywhere, at college and in my friends’ circle. See that little banner at the right hand bottom corner, yes, its an affiliate banner from Mozilla, the only affiliated thing on my blog.

I am sure most of you have heard or even used Firefox, the browser by Mozilla Foundation. The 1.0 version was released just more than 10 years from now (In fact, they just celebrated their 10th birthday) and they are getting better with each release.

But then, you might ask, why do you have to care about all this? All you wanted to do was browse websites. That’s it. Why care about the company which creates it and all those mess. Why try to be a hero by downloading another browser, when it is just a piece of software, right? No. Not so much. Talking, not from the point of view of a Mozillian, but someone who stopped using IE and Chrome way back and has been using Firefox on all his devices from atleast 3 years, I will try to focus on the most significant reasons to drop your existing browser and start with Firefox.

Add-ons

Does anybody remembers that there was a time when people used to use browsers just for the sake of browsing, and nothing else was even expected from a browser. That all changed with Firefox. You had this thing called add-on and plugins that can be easily downloaded to do little tasks to make your browsing experience better. They have one for all your needs (or most of them, if you question that!) plus you get to install third party add-ons too.

To be honest, Chrome has a market place of their own. Their add-ons (or extensions, as they are called) are generally considered more secure than their Firefox counterparts. Also, Chrome has more extensions than Firefox. But then, no third-party installs, sandboxing makes them so. In turn you don’t get powerful add-ons in Chrome, for example No-Script and AdBlock. In short, Firefox’s add-ons are much more capable to do a particular task, than any of its competitors’.

Customization

Most of the browsers available right now are too closed to get any close to Firefox in terms of customization. Chrome looks clean and feels fast and responsive. Opera is great too, but you don’t get stuff like about:config in any browser. With some days of experience, you can literally make the browser work for you. Everything’s under your control. It feels good to have control, trust me.

If core customization was not enough for you, then themes will do the rest. Free and open, feel free to give the browser your own look and feel. Don’t like an icon at a place? Move it. No, seriously move that icon to a place you are comfortable with.

Every installation of Firefox is different, users make it. Each one is using his or her version of Firefox.

NPAPI Depreciated? We use Firefox

NPAPI is the interface developers use to develop plugins for our browsers (the Java, Flash and Adobe Reader types) and Google has decided to remove them completely, unless it approved by Google. Now why should you care about this? Yeah, actually you should not. You will still be able to watch Youtube videos and read ebooks online, but it would be like, someone giving you all the comforts of life, at the cost of your individual freedom and preference. Are you okay with it? I’m not. Thank you.

Privacy

Now who won’t agree. Companies have started to revise their privacy policies to match their personal gains. Almost all the browsers collect information about the sites you visit, sell them to other corporates to give you targeted ads. No, I’m not saying this. It’s written there, right in their privacy policy. Now-a-days most of the popular browser have a DO NOT TRACK feature to prevent sites to give you your ‘tailored ads’. No one likes random sites, that you are visiting for the first time, know as much about you as, say your mail provider knows. Not me atleast. An important thing to know here is that Google Chrome has still NOT implemented the DO NOT TRACK policy, as of the time of writing this article. So now you know it is time to switch, right?

Sync

So, it is really convenient to have all our bookmarks and stuff from our mobiles to computer and vice versa. Firefox now makes it possible, securely. For power users, who work on the web all day, this comes as a great addon. Although some other browsers have had this feature before Firefox, we know well whom to trust with our information, looking at their individual policies.

Security

Out of the box, maybe Firefox is just second in security to Chrome, thanks to Chrome’s sandboxing techniques that Firefox has not implemented yet. That said, a little customization with use of proper addons (No Scripts and Adblock, mentioned earlier make a good example here), can make Firefox way more secure than Chrome, let alone other browsers.

Speed

Apparently Firefox appears to be a bit sluggish, especially on Windows. But here is a thing I noticed. That speed is constant, regardless of the number of tabs you have open. Compared to this, I have used other browsers that seem faster and more responsive at first, but just cannot take the load of heavy use (like I have my Iceweasel running for about 15hours at a stretch, with an average of 10 tabs open at all the times, and it runs flawlessly. Crash? Yes, sometimes, but I certainly get my session back each and every single time). Next time some friend of yours shows you the quickness of any browser, ask him to try the same with 15 tabs of heavy multimedia filled sites open and see how they perform (and yes, horizontal tab scrolling! Tabs on Firefox don’t shrink in size as you add them ;).

Final words

You see, I tried my best to keep this article going into another ‘Firefox vs Chrome’ battle, but it slowly slipped into it. The reason being the competition between these two browser. Technically, Internet Explorer comes in second most widely used browser, but had Microsoft not shipped it (forcefully!) with every MS operating system, I doubt the fact had been the same. Chrome is taking the lead, head on, and others are falling back. I got no personal problem with it, of course, but I hate monoculture. There was a time when 95% browser share was of IE, and Mozilla brought us out of it, made us see the web the way it was meant to be, not the way some corporations wanted us to see. I will promote Mozilla till they stand with what they say, ‘power in the hands of user’ and I will promote them or anyone else who stands up to make the web better, give power to the individual users who actually run the web and let them take control of what they want the world to see, and what not.

Although the title suggests that this was an article about ‘Mozilla Firefox’ as a browser, it clearly isn’t limited to it. It looks at a much bigger picture of the web. Tell me, what you feel about it, even if you are cool with handing over your data to companies. I would really like to know.

Simple TCP banner grabber in C

Hello folks, Its been a great week. I got the book called Expert C Programming – Deep C Secrets, by Peter van der Linden. I read about 100 pages in a couple of days, and I had never gained so much confidence reading any other book. Many concepts got sharper, doubts cleared and confidence boasted. A must read book if you know some C and want to understand the nuts and bolts of it.

In the same wave, I decided to write a small utility with sockets later today. It went great. Lots of coding, googling (I just can’t code without Google, maybe a sign of newbie) and debuging. Finally I ended up having a program that was partially correct. It works, but it doesn’t. It actually does more than what is told, and I couldn’t find out why. Still, I am posting it here, for those interested. Please correct it, as I didn’t really get what is wrong with it. Looks like some of the array locations are interpreted as ports, in the ‘ports’ array.

usage example: ./scanner 192.168.1.2 22,80,443

 root@kali:~/Desktop/C/socket# ./client 192.168.1.10 22,80

[+]Testing port: 22
[*]SSH-2.0-OpenSSH_6.0p1 Debian-4

[+]Testing port: 80
[*]<!DOCTYPE HTML PUBLIC “-//IETF//DTD H

TML 2.0//EN”>
<html><head>
<title>501 Method Not Implemented</title>
</head><body>
<h1>Method Not Implemented</h1>
<p>garbage to /index.html not supported.<br />
</p>
<hr>
<address>Apache/2.2.22 (Debian) Server at 127.0.1.1 Port 80</address>
</body></html>

[+]Testing port: 4195840
[-]Error Connecting to port

[+]Testing port: 0
[-]Error Connecting to port

[+]Testing port: 1476291006
[-]Error Connecting to port

[+]Testing port: 32767
[-]Error Connecting to port

I am not sure what that is, the part after the actual banner I mean. I will update this article as soon I get things sorted. Here is the code, if anyone wants to have a look.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

void scanner(int port, char host[]);

int main(int argc, char **argv) {
char host[100];
char *p;
int ports[10];
int i = 0;
int var;
char tok[] = " ,";

if (argc < 2) {
fprintf(stderr,"[+]usage: %s <hostname> <port,port,port...>n", argv[0]);
exit(0);
}

p = strtok(argv[2], tok);
strcpy(host, argv[1]);
while(p != NULL) {
sscanf(p, "%d", &var);
ports[i++] = var;
p = strtok(NULL, tok);
}

for(i=0; i<(sizeof(ports)/sizeof(ports[0])); i++) {
fprintf(stdout, "n[+]Testing port: %dn", ports[i]);
scanner(ports[i], host);
}
return 0;
}

void scanner(int port, char host[]) {

int sock, n;
struct hostent *server;
struct sockaddr_in serv_addr;

char buffer[4096];

server = gethostbyname(host);

sock = socket(AF_INET, SOCK_STREAM, 0);
/* Edit the params of socket to scan UDP ports,
* should be pretty straight forward I suppose.
*/

if(sock < 0) {
fprintf(stderr, "[-]Error creating socket");
return;
}

bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
// AF_UNIX for Unix style socket

bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(port);

n = connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
sleep(2);
if(n < 0) {
fprintf(stderr, "[-]Error Connecting to portn");
return;
}

memset(buffer, 0, sizeof(buffer));
strcpy(buffer, "garbagern");

n = write(sock, buffer, strlen(buffer));
if(n < 0) {
fprintf(stderr, "[-]Error writing (Port closed maybe?!)n");
return;
}

bzero(buffer, 4096);
n = read(sock, buffer, 4096);
if(n < 0) {
fprintf(stderr, "[-]Error reading (Port closed maybe?!)n");
return;
}

fprintf(stdout,"[*]%sn", buffer);
close(sock);

}

Celebrating 10th birthday of Mozilla Firefox

Around 10 years from now, in a small room, a bunch of wizards created something that later went on to change the entire web. It was called Firefox 1.0

At that time, Internet Explorer had around 95% browser market share in client side desktops. If you didn’t catch, read it again, yes 95%. Microsoft pretty much owned the Internet, but then, Firefox came in, and the web was never the same again.

Never before did a company kept the user in front of all, give the user the ultimate power, without any expectations for profits. Yes, these people are the true non-profits you will see. They got their values and they stick to it. They are programmers, coders, technical writers or just plain office workers who want to make a change in this world. It doesn’t take a college degree or loads of cash to be one of them, just go out and start contributing (or from your computer, your choice).

I am a 19 year old. I started to use the Internet recently, like 5 years ago. The Internet Explorer was my first browser (actually didn’t know what a browser was then, it just came with the copy of Windows). Later, as I grew, I realized the software that I use to surf the web can actually be changed. It was when I found Firefox, my second and last browser. It was awesome, and I used to boast how my downloads resumed after a power cut without any kind of download manager. I didn’t know anything about Mozilla or its mission then, still, the piece of software I was using was great.

An important transition in my life too place when I switched to Linux. I had realized that if I want to follow my dream of becoming a computer wizard someday, I need to master Linux. With Linux, I experienced the true power of Firefox. I got to know what are plugins and add ons. I got to know more about Mozilla and their aim, how they started and who are its core members. I was even lucky to attend a seminar of Asa Dotzler in India, which cleared all the remaining doubts I had, if any. I knew this is the organization I want to see myself working at in the next 10 years. I knew this was it.

Today, I am writing this article as a thank you. I didn’t want to get all technical with the facts about Mozilla, because there are loads of articles on the web for that. I just wanted to let people know, what impact Mozilla had, on my life and the way I live it.

A Mozillian 🙂

Self learning – Is it worth the efforts?

Self learning implies reading and doing it yourself. Not waiting for being spoon-fed and trying your best to teach yourself. Formally it is called Autodidacticism, which I came to know at the time of writing, honestly. In this age of globalization, where majority of the basic resources are available to a large section of the society, people can go to schools and colleges for little price (at least in some countries), not many give a thought to self learning. So, I thought, lets see what I can bring up on this topic today.

Self learning is something that needs to be taught to every kid when he’s growing up. It is not just beneficial to him during academics, but also changes his attitude towards different stuff he encounters. It fills him with a feeling of ‘if anybody else can, why can’t I?’ attitude whenever he sees something hard ahead of him. It lessens the required resources for him to learn something new. For example, learning a new programming language, while some might need special coaching classes and notes, a self learner would only require a book or an Internet connection to read up all the stuff and practice. That’s the clear benefit of it. He stops being a cry baby and takes life head on.

I have argued with people over this from long. A thing which I have heard in nearly all the arguments is the ‘time’ factor. People think self learning is time consuming. Indeed it is. You require time to grasp something and to master it, don’t you? Now, join a coaching class for the same. Will you learn it in a day? Talking about crash courses, those ‘learn this in one week‘ thingy? Do you seriously believe that the stuff on which people spend their lives to master, can be mastered in a week, just because they are charging ‘way too much‘? No you can’t. After a week, you will have like tiny bits of knowledge, enough to convince others that you know the stuff, and probably even a shiny framed certificate, that proves you know the thing. It is good for the show-off types. But if you were planning to make something out of it, then you would be disappointed, because the moment you start with something on your own, you will realize that just knowing theoretically is not enough. You need to know trouble shooting, maintenance and behavior of that particular thing. Because you won’t appoint someone to drive your brand new AMG who has just got his driving license. Right?

When I say self learned, there are two groups of people that come to my  mind. First are those who are pure self learned. They never went to any formal school and succeeded in life. Yes, success is important. But more important is the scale on which you equate success. Success doesn’t necessarily mean making billions from scratch, although it surely is one of the examples. Success is an abstract term. Success, more generally means being able to do what you always wanted to, and being contented. We have famous people who worked for science and arts and were self learned. Thomas Edison, Wright Brothers, Michael Faraday and Rabindranath Tagore to name a few of my favorites. They never walked on the steps of any school, but we know what they did. Could they do the same after joining a school or college? I think not. Not in the present situation, where a fixed curriculum is followed by teachers, which is to be followed by students, no matter who understands what. An exam at the end, after which you are free to forget what you learned because that was what you learned it for in the first place.

The second group of people, who come to my mind are those who technically went to a school and some college, but what they did was completely because of their own hardships and work, and their education had not much to do with it. Consider the example of Steve Jobs, the ‘Apple Computers‘ guy, who had been to school. He was good with studies and even enrolled into a college, but dropped out six months later as his parents were not able to pay his college fees. He later went on to create a company (actually, more than one) known for its standards and he is often called one of the best marketers of all time. This is a dead solid proof, that you don’t need an MBA to know how to do business and be successful in it. Warren Buffett and Bill Gates are no different. They spent an awful time during their childhood, got the practical experience needed to do things, and they are where we see them now. So, again the question pops up. Should you leave getting formal education and go ahead, learning what you like, all by yourself?

It is a quite risky path. You never know if you will click. There is always a possibility of failing miserably. Even if you are skilled and talented, why would the world believe you? You don’t have a certificate right? How will you convince others you know that thing? Demonstrations? The world is too busy for that. Then there are people who have heavy expectations from you. They depend on you. It becomes real hard to take decisions when you have to think not only about yourself, but also about the people who are calling on you. Now having said that, it is still finally on you. You can’t just live according to others. Because if you fail living the way you want, you don’t feel bad, as you would if you fail living according to the rules of others, right?

Ok, lets see the brighter side. You go to school. You go to college. Suppose you are interested in Astronomy. You have a subject on it in your college. Rest all the subjects are of the none of your business type. Still you have to learn them to clear your examination. If you were self learned, you study what you want to, and you can concentrate entirely on your passion. Honestly, life is short. You never know if you will be there to see the next sun rise. So why spend it on something you aren’t even interested in. I totally agree basic knowledge of the world is essential. Yes, primary schooling is something that should be given to every individual, as it not only builds knowledge but also the child’s logic and understanding of the world around him. But at a stage, everyone needs to be given the choice of continuing life according to his or her way, rather then making him or her follow others and lead to a boring, monotonous life. Feels like a crime to me. Indeed some need schooling, no doubt, but it is bad to make it a standard. To make it a rule to live respectfully on this planet.

That is the way I feel. Learn formally till you get to your senses, and then you can do whatever the hell you feel like. It makes you confident about yourself and you start thinking independently, no handles required. You know when and where to look for help and that means you never stop on a jerk in the road to success. Most importantly, self learning is rewarding. It is such a good feeling when you set goals for yourself and attain them. You keep raising the bar for yourself and get to it. There is no fear of ending up last in the class or below your fellow mates. You are your only competition, and that’s when you will realize, you have left the world far behind. You got no certificates, but you can argue, and defeat anyone in it, who has spend $20,000 a year to get that crappy piece of paper which certifies his level of skills and usefulness. Thats the magic of self learning. No boundaries, no limits.

and in case you were wondering, I am not self learned. I go to college to learn what they have to teach me, and I really regret not being able to be a self learner, although I am trying hard to be one. I take as little help as possible, work my ass off trying to figure out concepts in my books. Because once I get it, the feeling is rewarding; and I love it.

Thank you for reading.

Object Oriented Programming: Concepts and explaination using Python

Object oriented programming or OOP is a new concept for me. Till now, all I had done was C and some scripting languages. All of them were ‘procedural’ type of languages. I knew nothing about OOP, and I really hate knowing nothing about anything. So I decided to try it out. I could learn or start with C++ or Java, but I choose Python. The reason being its flexibility and more importantly, it is a language of choice when it comes to creating simple utilities and exploits, which is a field of interest of mine.

So it went good. I studied Python, both in procedural and object oriented way. I am still a beginner in Python but I studied the OOP concepts well. Then my college started and I had a subject called OOPM which deals with the same OOP stuff plus Java. The teacher, who teaches us the subject, I don’t really know what is wrong with her, but her examples are only confined to banks and ATM machines. That is pretty funny and annoying. One example is good, two are Okay, but when someone goes on like a week entirely on the same examples to teach something like OOP, your brain dies.

I have attended all the lectures and I am still trying to figure out what exactly she teaches during the lecture. Just a reminder, I have recently finished with OOP concepts in Python, so it shouldn’t have to that hard. Then I can only imagine the state of all those who are actually doing it for the first time.

Sick of it, I am writing this post on OOP concepts and will try my best to keep the terms and explanation simple and practical.

Starting with Object Oriented Programming 

OOP, as the name suggests is Object Oriented. Meaning that objects are the significant em…objects in it. But what exactly are objects? I wont answer it right away, because it would require some understanding. For now, everything, from variables to functions and else, are objects. First we will see some of the terms used.

Class

A class is like a code-template for creating objects of similar types which have some dissimilarities. For example, If I had to classify the Animal Kingdom again, I would create a class called animals which will be the parent class.

    class Animals(object):
        pass
       
    dog = Animals()
    dog.legs = 4
   
    cat = Animals()
    cat.legs = 2

And to use the class, we simply create an instance of it, which can be called an object as well. Dog and Cat are the instances here, for example. Since the class is empty (see the ‘pass’). We can set attributes to the instances. ‘legs’ is an attribute to the object dog and cat, which are instances

Object

Objects are all around you. Take a look. Everything that can have an individual significance can be considered an object. All objects have two characteristics, state (like color, size) and behavior (like tasks it does, eating, sleeping). In programming, objects are much similar to that. They have state (which are variables) and they have behavior (which is through methods). In the above ‘class’ example, cat and dog are objects. Let me write something that will make it clear.

    class Foobar(object):
        def __init__(self):
            self.x = x
            self.y = y
       
        def area(self, x, y):
            return x * y
           
    rectangle1 = Foobar()
    area = rectangle1.area(4,6)

So rectangle1 is the object I created. I use the method area to find out area of the supplied rectangle.

Inheritance

Inheritance is using an existing class and creating a new class which inherits, or has all the features of the old class plus some new features. So, if one were to organize reptiles and cats separately, he could do this.

    class Reptile(Animals):
        pass
       
    class cat(Animals):
        pass

This creates classes which can be called daughter classes of parent class Animals. They inherit all the properties of Animals plus they can have their own new properties. It results in code reuse, but read any good book and they will tell you why you should avoid inheritance. Since this is not a guide, I wont.

Methods

When you write a function inside a class, it is called a method. Why? I don’t know. Some books I have read insisted on calling them functions, while some didn’t. Its upto you. For the sake of an example, I will write a class ‘Shape’ and daughter classes and methods in them for finding their respective areas.

    import math

    class Shapes(object):
        pass
       
    class Circle(Shapes):
        def area(self, radius):
            return radius * radius * math.pi
           
    class Triangle(Shapes):
        def area(self, base, height):
            return 0.5 * base * height

The ‘area’ function in both the classes calculates the area of that particular shape and returns it. You need to call the function with parameters. For example,

    import math

    class Shapes(object):
        pass
      
    class Circle(Shapes):
        def area(self, radius):
            return radius * radius * math.pi
          
    class Triangle(Shapes):
        def area(self, base, height):
            return 0.5 * base * height
          
    mytriangle = Triangle() # Creating an instance
    area_of_triangle = mytriangle.area(5,10) # 5, 10 are arguments

If you are wondering, the first parameter ‘self’ is the object itself.

So that was my brief scattered explanation on OOP concepts. I am pretty sure there are some mistakes in the above snippets of code. Please let me and others know the mistakes so I can correct them.