Category Archives: Programming & Python

Engfmt(Engineering Format) Documentation

Link : https://pypi.python.org/pypi/engfmt/1.1.0

engfmt – It is a package used to read and write numbers in engineering format.

In engineering format a number generally includes the units if available and uses SI scale factors to indicate the magnitude of the number.

For example:

1ns

1.4204GHz

This package is designed to convert quantities between the various ways in which they are represented. Those ways are:

As a tuple:

For Eg: “1ns” – would be represented as (1e-9, ‘s’).

As a string in conventional formats:

For Eg: “1ns” – would be represented as ‘1e-9 s’ or as ‘0.000000001s’.

– This form is difficult to read for people.

– engfmt treats it more as a format meant for machines rather than people.

As a string in engineering format:

For Eg: “1ns” – would be represented as ‘1ns’.

– This form is difficult to read for machines

– engfmt treats it more as a human readable format.

The Quantity class is provided for converting between these various forms.

  • A quantity is the pairing of a real number and units, though the units may be empty.

1.It takes one or two arguments.

Eg: Quantity(1e-9) or Quantity(1e-9, ‘s’)

  • The first is taken to be the value, and the second, if given, is taken to be the units.
  • The value may be given as a float or as a string.
  • The string may be in floating point notation, in scientific notation, or in engineering format and may include the units.

Some examples of the conversions are given below:

For example, any of the following ways can be used to specify 1ns:

As a tuple:

>>> from engfmt import Quantity

>>> period = Quantity(1e-9, ‘s’)

>>> print(period)

1ns

As a string in conventional formats:

>>> period = Quantity(‘0.000000001 s’)

>>> print(period)

1ns

>>> period = Quantity(‘1e-9s’)

>>> print(period)

1ns

As a string in engineering format:

>>> period = Quantity(‘1ns’)

>>> print(period)

       1ns

Note: In all cases, the giving the units is optional.

Conversions – Using quantity object you are able to convert it to any representations:

>>> h_line = Quantity(‘1420.405751786 MHz’)

# to converting to tuple with units

>>> h_line.to_tuple()

       (1420405751.786, ‘Hz’)

# to converting to string with engineering format

>>> h_line.to_eng()

       ‘1.4204GHz’

# to converting to string with conventional format

>>> h_line.to_str()

        ‘1420.405751786e6Hz’

You can also access the value without the units:

# convertig to float

>>> h_line.to_float()

       1420405751.786

# converting to a string with conventional format – without units

>>> h_line.to_unitless_eng()

       ‘1.4204G’

# converting to string with engineering format – without units

>>> h_line.to_unitless_str()

       ‘1420.405751786e6’

# Get the units only

>>> h_line.units

        ‘Hz’

There are many other functions also in this package, which is available in the link given.

Some of the functions are given below:

  • Quantities As Reals – You can use a quantity in the same way that you can use a real number, meaning that you can use it in expressions and it will evaluate to its real value.

For Example:

     >>> period = Quantity(‘1us’)

     >> print(period) 

         1us

  • Quantity Class – Quantity class can be used directly, like shortcut functions.

      For Example:

      >>> from engfmt import Quantity

      >>> h_line = Quantity(‘1420.405751786 MHz’)

      >>> str(h_line)

           ‘1.4204GHz’

      >>> float(h_line)

            1420405751.786

  • Physical Constants – The Quantity class also supports a some physical constants.

      For Example:

     Plank’s constant:

      >>> plank = Quantity(‘h’)

      >>> print(plank)

            662.61e-36J-s

  • Exceptions:

The best thing in this is it also gives Exceptions:

Eg: A ValueError is raised if engfmt cannot convert a string it into a number:

For Example:
			>>> try:
			...     value, units = quant_to_tuple('xxx')
			... except ValueError as err:
			...     print(err)
			xxx: not a valid number.

Installation / Usage :

Requires Python2.7 or Python3.3 or better.

1. Use ‘pip install engfmt’ in the cmd prompt to install.

2. By importing the .py file:

  • Download the package from the link.
  • Copy the engfmt.py from the package and put in the working directory of the python.
  • Import the file by from engfmt import* / from engfmt import Quantity.

Dynamic image changing and JavaScript debugging

I and my  colleague are creating a software to track the students plan regarding their progress in their academic . In that we wanted to upload the students pictures when they select their name. I learnt to deal with dynamic images and to debug the code in JavaScript using

<div class=”animptext” id=”animptext”>This is just a text I want to change </div>

document.getElementById(“animptext”).innerHTML = standard;

Two HTTP Request Methods: GET and POST

GET – Requests data from a specified resource
POST – Submits data to be processed to a specified resource
In computing, POST is a request method supported by the HTTP protocol used by the World Wide Web. By design, the POST request method requests that a web server accept the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form.

Note that the query string (name/value pairs) is sent in the HTTP message body of a POST request:
POST /test/demo_form.php HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
POST requests are never cached
POST requests do not remain in the browser history
POST requests cannot be bookmarked
POST requests have no restrictions on data length

jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
1) A $ sign to define/access jQuery
2) A (selector) to “query (or find)” HTML elements
3) A jQuery action() to be performed on the element(s)

$(this).hide() – hides the current element.
$(“p”).hide() – hides all <p> elements.
$(“.test”).hide() – hides all elements with class=”test”.
$(“#test”).hide() – hides the element with id=”test”.

$ is just a shortcut for jQuery. The idea is that everything is done with the one global symbol (since the global namespaces is ridiculously crowded), jQuery, but you can use $ (because it’s shorter) if you like.

// These are the same barring your using noConflict (more below)
var divs = $(“div”); // Find all divs
var divs = jQuery(“div”); // Also find all divs, because
console.log($ === jQuery); // “true”

Javascript # and . Symbols – CSS selectors

Code 1:
$(‘#row DIV’).mouseover(function(){
$(‘#row DIV’).addClass(‘testing’);
});
Code 2:
$(‘.row div’).mouseover(function(){
$(this).addClass(‘testing’);
});

The hash (#) specifies to select elements by their ID’s
The dot (.) specifies to select elements by their classname
$(‘.row’) will select any element with class=”row”
$(‘#row’) will select the element with id=row

Asteroid game

I developed an Asteroid game from the python course . I did this game since two weeks .I had some difficulties while writing the codes. My team members helped me to over come errors in the program. Here’s a video on the game .I really enjoyed developing this.

-Prathap

Trigonometry Puzzle Game

I have been working on a project for the 9th graders. They had a small puzzle game where they were supposed to find trigonometric ratios and built the puzzle piece by piece by colouring it. Children liked it and as a team we decided to build it in scratch. I took up the responsibility and build a scratch program similar to the game they had in their text book. Here’s the program.

Children were excited and they started building the program themselves.

Python Learning

This week I had a good time with python. Yes, I have learnt few things which I feel worth to share here.
Counter:
It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. One can find out  the number of occurrence of the list items.
Example:#
>>>from collections import Counter
# list1 is a list/array which contains numbers
>>>list1 = [1,2,4,5,7,3,5,0,8,5,4,5,4,5,6,7,3,1,2,0,8,3,4,5,2,1,2,3,1,2]
# Counter will convert list1 into dictionary
>>>count = Counter(list1)
>>># most_common function will give the series of all the elements and its corresponding occurrences.
>>>count.most_common()
[(5, 6), (2, 5), (1, 4), (3, 4), (4, 4), (0, 2), (7, 2), (8, 2), (6, 1)]
>>># get the most common element by sending 1 to the function
>>>count.most_common(1)
[(5, 6)]
>>>count.most_common(1)[0] # get element & no. of occurrence as dict
(5, 6)
>>>most_common = count.most_common(1)[0][0] # Get the most common element
5

Strip() :
In the past I have used strip to strip out some letters from a string. Example
>>>AuraAuro.strip(A)
uraAuro
But I strip() is also used to remove all whitespace at the start and end, including spaces, tabs, newlines and carriage returns.
Rename:
I was looking for a module in python which used to rename all the specific type (eg. .docs, .txt, .py) files in a particular directory.
# Go to a directory get all the files of specific type ( lets say “.xls”)
# and rename it with ‘os.rename’
>>> import glob  # used to get all the dir / file from a specified path
>>>import os
>>>path = C:\\Users\\Vaidegi\\Desktop\\*.xls
>>>file_names_with_path = glob.glob(path+“*.xlsx) # to get all the excel files name
>>>for i in range(len(file_names_with_path )):
. . .          os.rename(file_names_with_path[i], student+i+.xls)

Linear, Log and exponent plots – Sratch

I was always confused with log. Sometimes its difficult for me  to handle log based problems . So, I decided to do project in log in scratch to visualize the curve and also to get a clear picture of that.  I started with comparing all the basic curves. First I created Y = X and Y = X^2 as follows,

Then, I went for log(x) and log (x^2). There is no much difference in these two. The plots are same in shape.

At last I plotted the exponent curve (e^x) as follows,

Matplotlib Animation – calling animation from a function

Creating Animation in Matplotlib:
#——————————————————————————
# ANIMATION- DYNAMIC PLOTS
#——————————————————————————
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.figure import Figure
import time
def animated_plot():
def data_gen(t=0):
“””
Generator – generating data to plot the graph
“””
cnt = 0
while cnt < 1000:
cnt += 1
t += 1
a = time.localtime() # used to get seconds
yield t, a.tm_sec  # this ‘yield’ will generate two point continuously.
def init():
“””
Initiation – create the base frame upon which the animation takes place.
“””
ax1.set_ylim(0,60)
ax1.set_xlim(0, 10)
del xdata1[:]  # to clear
del ydata1[:] # to clear
line1.set_data(xdata1, ydata1)
return line1,
def run1(data):
“””
To run the animation(draw function)
“””
t1, y1 = data
xdata1.append(t1)
ydata1.append(y1)
xmin, xmax = ax1.get_xlim()
if t1 >= xmax:
ax1.set_xlim(xmin, 2*xmax)
ax1.figure.canvas.draw()
line1.set_data(xdata1, ydata1)
return line1,
fig = plt.figure(figsize =(4,1.5))
ax1 = fig.add_subplot(1, 1, 1) #  1×2 mmatrix, 1st subplot
ax1.tick_params(axis=’both’, which=’major’, labelsize=8)
line1, = ax1.plot([], [], lw=2)
ax1.grid()
fig.patch.set_facecolor(‘white’)
xdata1, ydata1 = [], []
animatn = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=1000,repeat=False, init_func=init)
plt.show()
return animatn # must to put return when the animation is calling from a function
Animat=animated_plot() # calling the function. Here ‘Animat’ is must (it just a variable). Otherwise it will return null

Important points to note:

  • Use ‘return’ to return all the values to continue the animation (when you need to call it from a function). Otherwise animation will stop at its first iteration.
  • Call the function with name. ex. ‘Animat=animated_plot()’ not simply ‘animated_plot()’. In the latter case, all the values are collected as garbage values. So it won’t draw anything in the canvas.