Monday, November 20, 2017

Python 3.6 Handling errors and exceptions

Error handling one of the great feature of python and it offers a lot of versatility. Let us first build up the need for this feature of python.

if 1<2:
    print('Hello world'
File "<ipython-input-1-83ff31806b18>", line 2
    print('Hello world'
                       ^
SyntaxError: unexpected EOF while parsing

You will notice that the missing parenthesis causes the above error. Correcting the above just works fine.


if 1<2:
    print('Hello world')
Hello world

Let us take another example.

x = int(input("Please enter a number: "))
Please enter a number: hey
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-553ece37be8b> in <module>()
----> 1 x = int(input("Please enter a number: "))

ValueError: invalid literal for int() with base 10: 'hey'

Here x was expecting an integer but we gave it a string and thus we see the error above. The error above is very self explanatory. We were not prepared for this but we should be. You see that this was a ValueError.


try:
    x = int(input("Please enter a number: "))
except ValueError:
    print ('Please enter an integer')
Please enter a number: hey
Please enter an integer

We now have a way of handling the exception called ValueError. We display a message instead of the error. What if this is not enough.


try:
    x = int(input("Please enter a number: "))
    print('batman')
    y = x//0
    print('superman')
    print(y)
except ValueError:
    print ('Please enter an integer')

Please enter a number: 8
batman
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-9a959f723c86> in <module>()
      2     x = int(input("Please enter a number: "))
      3     print('batman')
----> 4     y = x//0
      5     print('superman')
      6     print(y)

ZeroDivisionError: integer division or modulo by zero

Now this is getting interesting. The code threw an error at line 4 and thus everything ran before than but nothing after that. That is the beauty of try except. On the very first exception it jumps directly to the except clause.
Here you will also see that you have another exception called ZeroDivisionError. If you are unsure of what exceptions might arise then just catch them all and display which one occurred.

try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception:
    print ('something went wrong')

Please enter a number: hey
something went wrong


try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception:
    print ('something went wrong')

Please enter a number: 8
something went wrong

Now we are just displaying something went wrong irrespective of what the exception is. Let us change that.
In the following 2 code blocks you see that the exact exception is displayed.

try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception as e:
    print (e)

Please enter a number: 8
integer division or modulo by zero


try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception as e:
    print (e)
Please enter a number: hey
invalid literal for int() with base 10: 'hey'

Let us look at the code below

try:
    x = int(input("Please enter a number: "))
    y = x//1
    print(y)
except Exception as e:
    print (e)
else:
    print('we did not encounter any exceptions')

Please enter a number: 8
8
we did not encounter any exceptions

Here we have changed the y = x//0 to y = x//1. Since we did not encounter any exceptions the else clause executed. The else clause only executes if there are no exceptions. There is however finally which gets executed at the end irrespective of all these.


try:
    x = int(input("Please enter a number: "))
    y = x//1
    print(y)
except Exception as e:
    print (e)
else:
    print('we did not encounter any exceptions')
finally:
    print('I will run no matter what and that is why I am called finally')

Please enter a number: 8
8
we did not encounter any exceptions
I will run no matter what and that is why I am called finally


try:
    x = int(input("Please enter a number: "))
    y = x//1
    print(y)
except Exception as e:
    print (e)
else:
    print('we did not encounter any exceptions')
finally:
    print('I will run no matter what and that is why I am called finally')

Please enter a number: hey
invalid literal for int() with base 10: 'hey'
I will run no matter what and that is why I am called finally

You can see that else executed when there were no exceptions but finally always gets executed. Sometimes you might want to have your own exceptions defined. You might want to check or assert for certain things and raise an exception there. Here is how we can do it.


try:
    x = int(input("Please enter a number: "))
    if x < 1:
        raise Exception
    y = x//1
    print(y)
except Exception as e:
    print ('The vallue is less than one')
else:
    print('we did not encounter any exceptions')
finally:
    print('I will run no matter what and that is why I am called finally')

Please enter a number: -1
The vallue is less than one
I will run no matter what and that is why I am called finally

clone my github here.
https://github.com/MrAmbiG/LearningPython

Tuesday, November 14, 2017

My configuration of atom for python

install Atom
open settings (ctrl+,) [windows] or file>settings
font type: consolas
settings>your stylesheet>styles.less
settings>editor>font family-->consolas
settings>editor>font size-->20
settings>editor>show indent guide-->true/check
settings>editor>tab lentgh-->4 for python
settings>editor>scroll past end
packages
--------
>>script
configure script's font size
.script-view .line {
  font-size: 14px;
}
packages>script>viewCode>keymaps>scripts.cson-->change code run keymap to ctrl-b from ctrl-shift-b

>>minimap
>>minimap-highlight-selected
>>flake8
>>python-autopep8
>>file-icons
>>autocomplete-python
settings>format on save>check

Monday, November 13, 2017

Add Dns entries to your DNS server

We have an amazing web portal which takes care of generating such scripts for us. We upload data to the portal and gives us scripts with values in it which we can right click and run to complete a task. Today I am going to give you a script which does the same but it takes use input in the form of csv. This is useful when the hosts are not in series or you have only few hosts to update to the dns.
It gives you a csv file.
you update the csv file.
you close the csv file.
you hit enter.
you wait.
it is done.
you can find it at my github repository.
github.com/mrambig/windows


function addDnsEntries {
<#
.SYNOPSIS
    add dns entries to microsoft dns server
.DESCRIPTION
    This will create a csv file with the headers. Fill the details and hit enter.
    Then the script will add the dns entries.
.NOTES
    File Name      : addDnsEntries.ps1
    Author         : Gajendra d ambi
    updated        : November 2017
    Prerequisite   : PowerShell v4+ win7 and upper.
    Copyright      - None
.LINK
    Script posted over: github.com/MrAmbig/
#>
Write-Host "make sure you are running it on dns server"

Write-Host "
A CSV file will be opened (open in excel/spreadsheet)
populate the values,
save & close the file,
Hit Enter to proceed
" -ForegroundColor Blue -BackgroundColor White
$csv = "$PSScriptRoot/HostVds.csv"
get-process | Select-Object netbiosName,ip,zone | Export-Csv -Path $csv -Encoding ASCII -NoTypeInformation
Start-Process $csv
Read-Host "Hit Enter/Return to proceed"

$csv = Import-Csv $csv

foreach ($line in $csv) 
    {  # importing data from csv and go line by line
    $hostname = $($line.netbiosName)  
    $ip  = $($line.ip)  
    $zone  = $($line.zone)
    add-dnsserverresourcerecordA -name $hostname -ipv4address $ip -zonename $zone -createptr
    }
} addDnsEntries

Does it work?
you let me know...

Sunday, November 12, 2017

Friday, November 10, 2017

Python 3.6 turtles or drawing stuff


"Turtle" is a module in python which helps us to create some basic drawings. Imagine this as a scrible or whiteboard and you use your code to draw. Why the name turtle? well, Imagine a turtle whose tails is dipped in ink and when it is moving on a whiteboard or paper, the tail leaves the ink on the paper creating thus a diagram or drawing. you control the movement of the turtle and turtle's tail dipped in ink takes care of the drawing. cool..haan..i know. Let us get started with your python shell. I always run 3 commands when i am using a new module to know more and explore it.
help()
dir()
<modulename>.__doc__
make it a habit and it will help you.

import turtle
help(turtle)

also run
>>> dir(turtle)
['Canvas', 'Pen', 'RawPen', 'RawTurtle', 'Screen', 'ScrolledCanvas', 'Shape', 'TK', 'TNavigator', 'TPen', 'Tbuffer', 'Terminator', 'Turtle', 'TurtleGraphicsError', 'TurtleScreen', 'TurtleScreenBase', 'Vec2D', '_CFG', '_LANGUAGE', '_Root', '_Screen', '_TurtleImage', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__forwardmethods', '__func_body', '__loader__', '__methodDict', '__methods', '__name__', '__package__', '__spec__', '__stringBody', '_alias_list', '_make_global_funcs', '_screen_docrevise', '_tg_classes', '_tg_screen_functions', '_tg_turtle_functions', '_tg_utilities', '_turtle_docrevise', '_ver', 'addshape', 'back', 'backward', 'begin_fill', 'begin_poly', 'bgcolor', 'bgpic', 'bk', 'bye', 'circle', 'clear', 'clearscreen', 'clearstamp', 'clearstamps', 'clone', 'color', 'colormode', 'config_dict', 'deepcopy', 'degrees', 'delay', 'distance', 'done', 'dot', 'down', 'end_fill', 'end_poly', 'exitonclick', 'fd', 'fillcolor', 'filling', 'forward', 'get_poly', 'get_shapepoly', 'getcanvas', 'getmethparlist', 'getpen', 'getscreen', 'getshapes', 'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'inspect', 'isdown', 'isfile', 'isvisible', 'join', 'left', 'listen', 'lt', 'mainloop', 'math', 'mode', 'numinput', 'onclick', 'ondrag', 'onkey', 'onkeypress', 'onkeyrelease', 'onrelease', 'onscreenclick', 'ontimer', 'pd', 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position', 'pu', 'radians', 'read_docstrings', 'readconfig', 'register_shape', 'reset', 'resetscreen', 'resizemode', 'right', 'rt', 'screensize', 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle', 'setundobuffer', 'setup', 'setworldcoordinates', 'setx', 'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle', 'simpledialog', 'speed', 'split', 'st', 'stamp', 'sys', 'textinput', 'tilt', 'tiltangle', 'time', 'title', 'towards', 'tracer', 'turtles', 'turtlesize', 'types', 'undo', 'undobufferentries', 'up', 'update', 'width', 'window_height', 'window_width', 'write', 'write_docstringdict', 'xcor', 'ycor']

>>> turtle.__doc__
'\nTurtle graphics is a popular way for introducing programming to\nkids. It was part of the original Logo programming language developed\nby Wally Feurzig and Seymour Papert in 1966.\n\nImagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it\nthe command turtle.forward(15), and it moves (on-screen!) 15 pixels in\nthe direction it is facing, drawing a line as it moves. Give it the\ncommand turtle.right(25), and it rotates in-place 25 degrees clockwise.\n\nBy combining together these and similar commands, intricate shapes and\npictures can easily be drawn.\n\n----- turtle.py\n\nThis module is an extended reimplementation of turtle.py from the\nPython standard distribution up to Python 2.5. (See: http://www.python.org)\n\nIt tries to keep the merits of turtle.py and to be (nearly) 100%\ncompatible with it. This means in the first place to enable the\nlearning programmer to use all the commands, classes and methods\ninteractively when using the module from within IDLE run with\nthe -n switch.\n\nRoughly it has the following features added:\n\n- Better animation of the turtle movements, especially of turning the\n  turtle. So the turtles can more easily be used as a visual feedback\n  instrument by the (beginning) programmer.\n\n- Different turtle shapes, gif-images as turtle shapes, user defined\n  and user controllable turtle shapes, among them compound\n  (multicolored) shapes. Turtle shapes can be stretched and tilted, which\n  makes turtles very versatile geometrical objects.\n\n- Fine control over turtle movement and screen updates via delay(),\n  and enhanced tracer() and speed() methods.\n\n- Aliases for the most commonly used commands, like fd for forward etc.,\n  following the early Logo traditions. This reduces the boring work of\n  typing long sequences of commands, which often occur in a natural way\n  when kids try to program fancy pictures on their first encounter with\n  turtle graphics.\n\n- Turtles now have an undo()-method with configurable undo-buffer.\n\n- Some simple commands/methods for creating event driven programs\n  (mouse-, key-, timer-events). Especially useful for programming games.\n\n- A scrollable Canvas class. The default scrollable Canvas can be\n  extended interactively as needed while playing around with the turtle(s).\n\n- A TurtleScreen class with methods controlling background color or\n  background image, window and canvas size and other properties of the\n  TurtleScreen.\n\n- There is a method, setworldcoordinates(), to install a user defined\n  coordinate-system for the TurtleScreen.\n\n- The implementation uses a 2-vector class named Vec2D, derived from tuple.\n  This class is public, so it can be imported by the application programmer,\n  which makes certain types of computations very natural and compact.\n\n- Appearance of the TurtleScreen and the Turtles at startup/import can be\n  configured by means of a turtle.cfg configuration file.\n  The default configuration mimics the appearance of the old turtle module.\n\n- If configured appropriately the module reads in docstrings from a docstring\n  dictionary in some different language, supplied separately  and replaces\n  the English ones by those read in. There is a utility function\n  write_docstringdict() to write a dictionary with the original (English)\n  docstrings to disc, so it can serve as a template for translations.\n\nBehind the scenes there are some features included with possible\nextensions in mind. These will be commented and documented elsewhere.\n\n'

Once you are done exploring it then let us proceed to some fun stuff. Let us draw a
a line
a triangle
a rectangle
a circle and some fun with all of them.

a turtle always starts from left to right. clear the screen. run the following.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90) # tell amy to move forward for about 90 units

you will see that our amy (turtle) draws a straight line or in other words moves from left to right for about 90 units and leaves a trace of ink on its path.
Let us turn that into a triangle.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)

you will now see that in the new window amy/turtle draws a triangle.
Let us make a rectangle around it. I am sure now you know how it works. So let us try it out.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)

Now our triangle is inside the new rectangle. Why stop there? let us have a circle on these too.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)
amy.circle(180) # a circle with 180 units of radius

I want you to explore more since the motto of this post is only to enable you to explore and not explore. Help you to learn cooking so that you cook for yourself and not to cook and steal the fun of cooking from you. FYI I don't much like cooking. I just make oats twice a day with water/salt/spice and thats it.