Simple JavaScript program that handle Keyboard events

In this post I am going to talk about one of important aspect in programming i.e. handling keyboard events. Now being important doesn’t mean that it is difficult but I have to admit that I haven’t tried it from the day I had started programming. Now I was working with one of my friend and she wanted me to do it for her. I found the task interesting as I haven’t done it earlier.

Here in this post I am not going to create a simple JavaScript program that will raise an alert whenever any of the arrow key is pressed. The program will detect the arrow key at any point while the browser is working. But before diving in we will discuss the very basics of the keyboard event handling in JavaScript.

There are three basic types of keyboard event Listener in JavaScript that handles this type of event.

  1. keydown
  2. keyup
  3. keypress
  • Keydown stands for the stage when the any key is pressed.
  • Keyup is the exact opposite of keydown
  • Keypress only works when one of the character key is pressed. You might like to work with this when you want to work with something fixed.

After reading this you should have got a clear view that what we want to try is keydown event.

Now lets dive right into the program and write some code.

<!DOCTYPE html>
<html>
  <head>
    <title>Nothing</title>
    
      window.addEventListener("keydown", onkeypress, false);
      function onkeypress(key){
        if(key.keyCode == "37"){
          alert("Left key is pressed");
        }
        if(key.keyCode == "38"){
          alert("Up key is pressed");
        }
        if(key.keyCode == "39"){
          alert("Right key is pressed");
        }
        if(key.keyCode == "40"){
          alert("Down key is pressed");
        }
      }
    
  </head>
  <body>
  </body>
</html>

Now the coding part is pretty straight forward but still if you find something odd about this program please drop a comment and I will get back to you.

Adding a tuple to the end of the basic tuple in python

Another problem was encountered while working on the python web framework, Django. But this time the problem was more of the language oriented rather than being framework oriented. As I am not a python programmer so I never knew these basic things. So, first of all I was getting an error, whose statement went like this :

First of all I will like to tell the things that I wanted to iterate over were stored in list and the list has many tuples inside it.

 

[('name1'), ('name2')]

There was a large list of names. The only plus point in this journey was that I already had a tuple that was showing the required result. And the tuple which worked was looking like this..

 

(('abc1','xyz1'),('abc2', 'xyz2'))

So, The first thing I did was that I converted the list into the tuple if ‘l’ is the name of the list.

Convert a python list into tuple

l=tuple(l)

The final tuple will be stored in l. After working on this error I went forward to run the python server. The server showed an error. The error said..

Need more than one value to unpack.

I went forward and again compared my tuple with the working tuple and after comparing I came to know that I must have a pair of two values in the single tuple so that they can the django can unpack them accordingly(I don’t know the basic reason behind this, This can be because the takes this format). This link can help you to learn more in the right direction.

For this I went forward to create a loop which can add a new items in the end of the tuple. Now as the tuple in python is immutable so that when we add the data to tuple the data is added as a tuple. This is what I wanted but whenever I searched for something like this on the internet I got other ways of doing that and one of them said that you need to convert the tuple into a list and then add the data.

But the problem was solved by using this code in the for loop:

x = 0
for q in name:
	z=((q.id, q.Name),)+z
	x = x+1

This is how I solved the most persistent problem in the project. Please share your views about the post in the comments.

Creating a custom form in Django with special options

In this post I am going to elaborate my journey of creating a html form in django and then extracting the python variables from the inserted data. After doing that we can do almost anything with this data.

We can retrieve data from the django models or we can print them out in the browser. There was a specific reason for which I wanted to do that. Actually my database was created using admin panel. There was a lot of data in the database. I just wanted to retrieve that data using the data given by the user.

The user can select the data according to the categories and I had to show that data using the given filters. So, I started the journey by using a simple form. I never knew that in Django we have to create a separate file for forms due to this, I went forward to create a simple html form in the Django templates. I spent a lot of in this and finally came to know that there existed an easier path.

Creating a custom form in Django

First of all you have to create a file named forms.py in the app on which you are working(Now many smart people suggest that we must create another app for different purposes in the particular web app but for the simpler process we will work on a single app). Now the content of the forms.py should be according to the form that we want to show as the output form. For example if we want to create a form with a name field and an age field then the content of forms.py will look like.

 

from django import forms
class nameform(forms.Form):
	name = forms.CharField()
	age = forms.IntegerField()

Now we need to need to create a view for this form. So that we can show this form.

Creating the views of the custom form

 

from .forms import nameform
def nameageform(request):
	form = nameform(request.POST or None)
	context = {
		"form" : form
	}
	return render(request, "yourapp/forms.html", context)

Now your job is to create a template named forms.html inside yourapp/templates/yourapp/

Creating template of your custom form

This is the content of the file named forms.html

{% extends 'webportal/base.html' %}
{% load staticfiles %}
{% block content %}
<h1>Form</h1>
<form method="POST" action="output/">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create Post" name="">
</form>
{% endblock %}

You can look your form working once you will set up the urls for the form in the urls.py file.

After this you have to create a function named output in the views.py that will render the views when the data is posted on the form.

 

def output(request):
	query1 = request.POST.get('name')
	return HttpResponse(query1)

Now we need to do the final step i.e. to create a url of this view. The content of the file urls.py will look like this :-

 

urlpatterns = [
    url(r'^product/output/$', views.output, name="output"),
]

Hope this post will help you to save a lot of your time. Thanks for reading and feel free to comment.

Creating a header which changes style on scrolling | From transparent to colored

Hello everyone, I am back with one more exciting post. In this post we are going to discuss something great. This is something that I always wanted to learn but waiting for someone who can force me search through the Google and create the desired results.

I promised myself that I will surely make use of this concept in my next project. Finally I used it while creating the main page of the website of Duggal Building Materials using Django(github link to the code) and now I am showing off my latest acquired skill.

Task :

So the final result that we want is a header with navigation bar that changes style when we scroll down on the browser. Let’s clarify the situation and talk about the final result first. Finally we will have a transparent header if the user is at the top and opaque as soon as the user starts scrolling down. Now we are taking this as an example but you can do whatever you want to do after this.

Also by the end I will provide a single code file you must keep the code in the separate files. For example CSS, JavaScript must be in different files.

Used Technologies :

HTML, CSS, JS, jquery, Bootstrap and some more.

That is it for the prerequisites of the task and now is the time to accomplish it.

  1. First of all add the requirements in the head of the html.
  2. Now let’s make a navbar using bootstrap.
  3. Give this nav a id of header. We will target this id.
  4. Then add a div that will provide the required room to see the scrolling action.
  5. Now add the  following script.
<!DOCTYPE html>
<html>
<head>
 <title>Some Title</title>
 <!-- Code for number 1 start -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">
 https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
 <link href="https://fonts.googleapis.com/css?family=Ubuntu:400,700" rel="stylesheet">
 <!-- Code for number 1 ends -->
</head>
<body>

<ul class=”nav navbar-nav” id=”nav-list” style=”float:right; color: #EA4525;”> <li class=”active”><a href=”/”>Home</a></li> <li><a href=”#”>Products</a></li> <li><a href=””>Contact Us</a></li> <li><a href=””>About Us</a></li> </ul> </div> </nav> <!– Code for number 2 ends –> </div> <!– Code for number 4 start : height of 2000px is given –>

//script starts for number 5 $(document).ready(function(){ var scroll_start = 0; var startchange = $(‘#header’); var offset = startchange.offset(); $(document).scroll(function() { scroll_start = $(this).scrollTop(); if(scroll_start > offset.top) { $(‘#header’).css(‘background-color’, ‘rgba(34,34,34,0.9)’); } else { $(‘#header’).css(‘background-color’, ‘transparent’); } }); }); </body> </html>

That’s it for this post. If this doesn’t work out feel free to post a comment.

How to install django using virtual environment

Virtual environment is made when you want to run different version on single system. In this example I am going to setup a virtualenv for installing django 1.9. This is because the default version of python in the ubuntu system is 2.7(approx.) and the django is in the version 1.7. And the python is very important in the case of Ubuntu graphics. (If you want to test this try to remove python from your system and get ready to waste 2-3 hours of your time trying to figure out what happened. You might have to install Ubuntu again).

Now it’s time to start creating the virtual environment. So the before installing virtualenv you need to have pip installed in your system. For that use this command.
sudo apt-get install python-pip
Now install virtualenv
sudo pip install virtualenv
and then
sudo pip install virtualenv –upgrade for the most recent version.
Now make a directory where you want to run the virtualenv.
mkdir django1_9_7
cd django1_9_7
Now create a virtualenv inside this folder.
virtualenv .
Now apply this command everytime you want to start the use the virtualenv
source bin/activate
Now you are in the virtualenv and you can see the various packages inside this env are going to stay in this env only. Use this command to find the packages in the env
pip freeze
Now use this command to install django
pip install django
Now you can start a django project inside this folder.
django-admin startproject myprojectname.
This env will as same as the way as the real installed softwares will work..

Creating documentation using Doxygen in Ubuntu

This post was originally posted on my blog.

Doxygen is a tool to create a documentation for your program/project written in the languages like C, C++, Java, python and so on. It reads the well formatted and special doxygen comments to create the required documentation. This documentation is very important for the new developers who want to help in the development of the project. Documentation is one of the main pillar of an open-source project.

Read this post to more about the importance of  documentation in software development.

Let us discuss how to create documentation using doxygen. First of all you need to have doxygen installed on your system. For that you can type these commands in the terminal.

sudo apt-get update

sudo apt-get install doxygen

This is good for the beginning. But if you want to create the documentation using the graphical user interface then you can use this command. I will not be discussing this method so you have to figure it out yourself. I am taking this method to be fairly easy that you can figure it out yourself.

sudo apt-get install doxygen-gui

Now you can run the GUI using the command.

doxywizard

Now that’s it for the GUI we are going to create the documentation using the terminal. Excited… so am I. So, let’s start. For the example purpose I am going to create a simple hello world program in C++(The strategy is different for python but is similar to many other languages whose support is present).

This is what program looks like :-

/**
* @file         helloworld.cc
* @brief        helloworld
* @detail       this is a simple hello world program using a function
* @author       Ranvir
* @include      string.h
*/
#include <iostream>
using namespace std;
/**
* @class   hello
* @brief   simple brief intro
* @detail  detailed intro
*/
class hello{
public:
/**
* @class   hello
* @fn      helloworld
* @brief   print helloworld on the terminal
*/
    void helloworld(){
        cout<<"hello world";
    }
};
int main(){
   cout<<"Hello world";
   cout<<"\n";
   hello obj1;
   obj.hello();
   return 0;
}

Is this the basic context of a C++ file. No, it contain some extra components written in the a block of comment section. These are the Doxygen comments and they are used by this tool to depict the various parts of the program. According to the official site of Doxygen, there are many ways to start a comment in a file. For eg:- We can do it by these ways:-

  • /**      ———–          comments                   */
  • ///      single line comment in Doxygen
  • “”” special comment block for python “””
  • /*!                  comment                                 */

While writing the comments we have to follow a pattern with the tags i.e. before every tag we should have something special so that Doxygen can understand what are we creating. Actually Doxygen read these tags and place them at special location in the generated output. So, we have to specify them explicitly. So the two common sign used are

  1. @
  2. \

We have used @ in the shown example. We can also use \ in place of @.

Now we need to generate the configuration file for the project. The configuration file contain the content in which the various variables of the Doxygen file are defined. While you are in the directory where your project is present. You can also create a separate folder for the doxygen content.For this purpose use this command.

$ doxygen -g filename

From above command filename is optional, if no filename is given a file named Doxygen is generated. Now I will assume that you have not used any file name.

Next you can edit this file and add the content according to your needs. For example you can give a name to your project using this file. For editing use this command.

$ vim Doxygen

I hope you know something about vim. If no read this post. 

Great now this is the time to generate the Documentation. Go on and type this command in the terminal.

$ doxygen Doxygen

Where Doxygen is the name of file we generated earlier. Now you will find two directories in the place where your files were present. Use these commands to see the generated html documentation.

$ cd html

$ firefox index.html

To see the latex output, Move out of this directory by using these commands.

$ cd ..

$ cd latex

$ make

Now open the pdf output. You will see the documentation in the pdf format.

Still unable to figure out. Post a comment and I will love to help.

Thanks for reading 🙂

Using my own coded software to study for Exams

Some time ago sir hosted a hackathon to make some progress to enhance the ebook software that he was using on his website. Everyone was given a specific task on that day. My task was to read the script and make some changes in the script. But some reason we had to drop that idea. So I decided to start building something new instead.

I wrote some code and was able to create a replica of the software( Although It was not as great as that software). The code of the software can be found here.

Due to dropping of the idea the task become much more complex and we are still figuring it out. But I showed the new code written by me to sir and sir asked me to test it for the books of my choice. I was not able to test it because I don’t read much books unless it is very important (although I love to read books).

So, the time came when it become very important to read as it was the Exam time. I was not having the notes of the subject so I went to one of my friend and asked him to give me the notes. As he was also studying so I decided not to disturb him and take the pictures of the notebook. I used my phone for this purpose. I started studying the pictures from the phone and soon enough become fed up because of the small screen then I decided to move the pictures to my laptop. I started studying but before the completion of the page it become difficult for me concentrate.

Then I decided to use the software that I have coded some time ago. First of all I decided to change the name of the pictures as for the pictures to get imported we have to change the name and bring the images to the png format and It was a large task to change the name of each and every file so I looked for some python script on the internet. Soon enough I found something that was explained enough so that I can use it. I changed the script according to my needs and was able to successfully change the name of images.

After I saw the images carefully I was able to find that the images were not in the right order so I went to one of my senior(Amarjeet). He told me to create a list first and then send the list to the function which changed the name of the images. Earlier it was a dictionary by default and since the values in the dictionary are in a random order so we were not getting the correct order.

So in the end I solved this problem and took the pictures and put them into the required folder. And in the end I manipulated the JSON file and finally was able to run the image on the browser.

On opening the browser I found that the images were 90 degree toward the left. So, I used this command to rotate it back to normal.

mogrify -rotate “90” *.png

Necessity of documentation while programming

This is a post which discusses the one of the most important requirement of software development phase i.e. documentation.

What is Documentation?

Documentation is a way of telling other programmers and users about your program. It is basically writing comments in the code. Documentation can either for the user or it can be for the programmer.

  • User Documentation can be very helpful for user. It declares the set of rules and define the various ways in which user is allowed to use the software. It can also tell the way of setting up the various environments so that he/she can use the program.
  • Programmers Documentation is used to make the code understandable for the other programmers so that they can understand the code and help in the development and removal of the bugs in the code.

Why is it necessary to document the code?

  • You are going to read your code again in a while : So, you are going to read your code after a while. And when you are going to read it you are going to think why have you done this if and only if the code is not documented properly.
  • To make progress in your open source project : If you want the programmers to look at your code and help you so that your code becomes less and erroneous then you must attract users. Users are only going to come if it is fairly easy to use your program. You can also make it easy by telling the user how to use the software. If you have a large database of users them developers are going to come with them increasing the condition of the program. (Twitter Bootstrap is one of the great example for this. They have set up a great user manual which tells very simply about the project.)

Now you know the basic reasons for creating a documentation of the program. So let’s create documentation using Doxygen. To know more read this post. 

 

How to simplify command’s name in Ubutnu

I love the amount of freedom given to you as a user when you work on a system with Ubuntu installed on it. So, I was not having sudo powers for the installing meteor on the server, So I asked one of the server admin(Mandeep) to do it for me. He told me that I don’t need to be signed as a root admin. I was not sure about it as their was a error when I was running the command to install meteor.

So he showed me the way to use the meteor commands on the server. A hidden folder was attached to my home directory with this name .meteor. He told me that if I go inside this folder then I can use the meteor commands by the name ./meteor. For example when I have to type meteor create appname, I will use ./meteor create appname. This wasn’t looking great so he told me that I can change it accordingly. He left this job to me.

So I was thinking that how can I solve this problem. First I tried to make a variable of ./meteor command by using this. By using this command.

meteor=’./meteor’

Now I was using $meteor command in place of .meteor. This was something better then ./meteor. But I wanted to make it work as required so after searching a bit I came to know about aliases in the Ubuntu.

So, when in home directory use this command.

vim .bash_aliases

Else everything is explained in this post. Just one thing, that sometimes you need to close the terminal to make this thing work.

http://www.howtogeek.com/73768/how-to-use-aliases-to-customize-ubuntu-commands/

I used this and everything was working on the server. But I wanted to implement on my local so I used the same procedure on the local. But somehow It was not working I tried to quit the terminal and tried to turn it on but it was not working.

I searched some more and found the solution. So you have to add some data into the file .bashrc(rc stands for “run commands”) which is in the home directory. So add this data to the end of this file.

if [ -f  $ HOME/.bash_aliases  ]
then
.  $HOME/.bash_aliases
fi

Now try to restart the terminal and this will work for you.

Still not getting put your questions in the comment section. Thanks 🙂