Friday, June 30, 2017

Learn Programming in Python in 20 days - Day 1 - Introduction

This is first article for a 20 article series to help you learn programming from scratch. The series assumes basic familiarity with programming jargons. 


This is the introduction for learning Python programming language. This is also based on the assumption that Python is easy to learn and get going with. One of the prime reasons for this is that that Python is relatively new language -Fortran (1957), C ( 1972)  , C++ (1980), Python (1991) , Java , JavaScript ,PHP (1995) , C# (2001) and so on ... To set it in correct perspective having worked on all of these languages mentioned above, the journey for learning Python will also be like a exploration to me where I will also like to relate how the same thing was done in other Programming language.

This lecture will cover only the installation of Python language on your machines : 
  1.  Check if Python is already present on your machine by typing python on command prompt. If you see version number of Python installed emitted from the Python interpreter  than we are good to go 
  2. Download python from link here http://www.python.org/download/ for appropriate release.  For these lecture series I will be using Python 2.7 though. Download the msi file and install it. For Linux install Python 2.X and Python 2.X Dev Packages
  3. Once done installing  type Python on the command prompt. Good to go ? 

Compiled vs Interpreted Language

  • A basic difference between languages like C# , Java and Python is they are complied before the execution of the program. A compiler is a program that understand the code line by line , decodes each and every declaration before hand - variables and function calls , types of variable - Integer , characters etc. and operators to generate the machine readable code i.e. the code gets optimized for that particular machine set before execution. 
  • For Interpreted languages on the other hand there is a another program - Interpreter that executes the code flow at run time i.e. when the program is run the interpreter  converts the code in machine readable format.
  • The benefit is we need not to compile the program every time we intend to run it and therefore the deployment becomes quite easy when compared to complied languages like Java. Each time we change a function in Java Application the whole application is rebuilt leading to down time of the service whereas in Python the same can be achieved by just changing the function and saving the file , the next time the code is executed the interpreter picks up a fresh piece of code


Using Variables

  • With the above in mind lets talk about the variables in a Program - a variable is used when we want to assign or store certain value within our program. A variable can be of many type - Integer ( 1,2,100 etc.) , Floats / Doubles ( 1.2, 200.22456) , characters ( A, $, b etc.) , string ("what an awesome weather"). Although character as a Type is not present in Python its available in other native languages.
  •  For Python character is nothing but string of size one. Python Interpreter understand the type of variable and stores it in appropriate type.
  • So while we have only one function to add two variables in Python , in C# or Java there will be multiple functions to add two strings as we need to define the type of variable before hand
  • Variables are the way to think about a program - suppose we want a program that gives full name of a person as output. What will we need to have full name - First Name , Middle Name & Last Name. 
  • So lets store them as variables - vFirstName , vMiddleName , vLastName. The output also we need to store somewhere say vFullName. Our program ( Any language of choice ) now will take 3 inputs and return one output by operating on them - vFullName = vFirstName+vMiddleName+vLastName.  And let the program return the vFullName as final output.
  • Tip - Try to break the problem in parts , try to think what all input we need , what kind of processing one needs to do and how to get  the output
Post your problems in the comments below. I will try and answer you back. 

Sunday, February 8, 2015

Switch Case in Python

Problem:

This is for my understanding and memory I  need to write about the Python way of writing switch case. One such way is writing the if elif and else construct but the other way as mentioned in the some of the code I have seen as is to use the dictionary as key value pair and match the key of the dictionary key as a case value and return the same from the dictionary.

Solution:

The solution below explains the logic for the same and do keep in mind why this is working out because

  • For the dictionary a = {key:value}  the expression a[key]  and {key:value}[key] are same and will give out value

Saturday, February 7, 2015

How to Conditionally execute a javascript/jquery snippet in django templates

Problem

Many times in a project while rendering html on django template we need to execute certain Javascript code to conditionally render some html component based on the value of some template variable. Using if else conditions provided by django template system was not working , then how to go about this conditional execution of script

Solution

The code snippet below gives the hint

Friday, December 26, 2014

How to make Ajax calls from jquery client side to django view

Problem - We need to make Ajax call from client side browser to the server posting some data. Instead of posting the whole form to the server we need to use ajax to post only the required data back to the server. The problem arises in how to provide URL parameter for the post call which includes the server root and the app route as well.

Solution - 

  • Let the form include the csrf token as provided by django framework by placing {% csrf_token %}
  • The javascript function that will make the required call at :

          var host = document.location.host; // host + port
          var protocol = document.location.protocol;
          var sr_origin = '//' + host;
          var origin = protocol + sr_origin;
          $.ajax({
                         type:"POST",
                         url :origin+"/appName/post_view",
                         data:{
                                     "DATA_X": x,
                                     "DATA_Y" : y,
                                      csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val() 
                                   },
            datatype:"json",
            error:function(data){ alert('Error:');},
            success:function(data){ alert("Success");}

          });
  • On the view side we need to provide a map for the URL : /appName/post_view mentioned above as : url (r'^post_view$',views.post_view,name='post_view') in the url.py file located within the appName folder [appName is the name of django app from which we want to make the call to view function]
Once this mapping is done we are good to make our ajax call ! 


Tuesday, December 9, 2014

Get Last N Recent Django Model Instances

Problem:
We have our good old Django employee application and we want to show 5 recent joiners in the team on a Django template.

Solution:

Lets take the case of Employee instance having a created_date as one of the attribute that will define the datetime when the employee entered the system. We will follow the following approach:

  1. Get the queryset of django instance sorted in decending by created_date attribute
  2. Pull out top 5 or n from this list
  3. Please note the method in the sis a static method as it is not dependent on the instance but the Class itself
Code Sample:



 



Thursday, November 27, 2014

Deleting a Foreign Key Model Instance

Problem:

Consider a scene where you have a django model with a Foreign Key reference to another Model Instance.  Now when you try and update the Foreign Key Instance , one need to remove the already existing instance. While trying to do that django also delete the model instance hosting the Foreign Key reference. So how to delete the Foreign Key Reference object without deleting the host instance.


Solution:

The solution is to update the model with on_delete attribute  set as models.SET_NULL. Django by default assumes cascading behavior while deleting any model object.

Not knowing this costed me some precious time to figure this out.




Tuesday, November 18, 2014

How to get GIS coordinates from the address using Google Geo Location API

Problem : One of the requirement to enter data for client on boarding might be to enter the location data for the customer. The location data can then be used to generate specific insights based on client locations.The client form consists of typical form fields like - Name,Age,Email and Address. The Address as you might have seen is various applications is divided into 3-4 fields like

Address:
  • Address Line 1 
  • Locality 
  • City 
  • State 
  • Country
  • Zip Code
The problem now is to use this address to get latitude & longitude details of the address using the Google Map API. Once we have latitude & longitude data we can plot this point on map and make the analytics more interactive.

Solution:

  • Parse the form to get the values out from the form field - Lets store them in variables as: addressLine,locality,city,state,country, zip
  • Create a location string by adding all the above variables separated by  "+" sign as:
       loc = addressLine+ '+' + locality + '+' + city + '+' + country + '+' + zip
       (above expression assumes that we have converted all the variable to string)
  • Declare a variable to point to geo location Google API and a dictionary to pass the encode location arguments
        GEOLOC_URL = 'http://maps.googleapis.com/maps/api/geocode/json'
        GEO_ARGS = {}
        GEO_ARGS.update({'address': loc })
        Geolocation API needed 'sensor': "false"/ "true" attribute in earlier versions
        indicating the use of sensors to collect data
  • Appended the GEO_ARGS to GEOLOC_URL to create new URL
        url = GEOLOC_URL + '?' + urllib.urlencode(GEO_ARGS)
  • Once the url is encoded we now need to send the request for which we will import urllib and get the result back which is a dictionary with all the details
        result = json.load(urllib.urlopen(url))
        ( import urllib & json before calling the above line of code )
  • If everything went well one can check the status using result['status'] which will be OK
  • Now our Lat / Long Values be 
  • latitude =  result['results'][0]['geometry']['location']['lat']
  • longitude =  result['results'][0]['geometry']['location']['lng']
  • If the API is able to find the location accurately it returns only one results element and if the results are ambiguos it returns a list of probable elements so checking this might be important while parsing the JSON
  • The code below shows summarizes what we discussed above
Now we can store these values in our database to be retrieved later to be plotted on Google Maps