article

Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Saturday, June 11, 2016

Python How to check if a network port is open

Python How to check if a network port is open
 
import socket;
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
   print "Port is open"
else:
   print "Port is not open"

Friday, June 10, 2016

Python read csv

Python read csv
 
import csv

csvfilename = "server_L2.csv"

print "Printing all rows"
with open(csvfilename, 'rb') as csvfile:
 reader = csv.reader(csvfile, delimiter='\t')
 for row in reader:
  print "   ", row
print ""

print "Printing all rows using header line"
with open(csvfilename) as csvfile:
    reader = csv.DictReader(csvfile, delimiter='\t')
    for row in reader:
        print "   ", row
print ""

Saturday, June 4, 2016

wxpython advance widgets wx.ListBox

wxpython advance widgets wx.ListBox

A wx.ListBox widget is used for displaying and working with a list of items
 
import wx

ID_NEW = 1
ID_RENAME = 2
ID_CLEAR = 3
ID_DELETE = 4


class ListBox(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(350, 220))

        panel = wx.Panel(self, -1)
        hbox = wx.BoxSizer(wx.HORIZONTAL)

        self.listbox = wx.ListBox(panel, -1) #create an empty wx.ListBox
        hbox.Add(self.listbox, 1, wx.EXPAND | wx.ALL, 20) # put a 20px border around the listbox

        btnPanel = wx.Panel(panel, -1)
        vbox = wx.BoxSizer(wx.VERTICAL)
        new = wx.Button(btnPanel, ID_NEW, 'New', size=(90, 30))
        ren = wx.Button(btnPanel, ID_RENAME, 'Rename', size=(90, 30))
        dlt = wx.Button(btnPanel, ID_DELETE, 'Delete', size=(90, 30))
        clr = wx.Button(btnPanel, ID_CLEAR, 'Clear', size=(90, 30))

        self.Bind(wx.EVT_BUTTON, self.NewItem, id=ID_NEW)
        self.Bind(wx.EVT_BUTTON, self.OnRename, id=ID_RENAME)
        self.Bind(wx.EVT_BUTTON, self.OnDelete, id=ID_DELETE)
        self.Bind(wx.EVT_BUTTON, self.OnClear, id=ID_CLEAR)
        self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnRename) #bind a wx.EVT_COMMAND_LISTBOX_DOUBLE_CLICKED event type with the OnRename() method

        vbox.Add((-1, 20))
        vbox.Add(new)
        vbox.Add(ren, 0, wx.TOP, 5)
        vbox.Add(dlt, 0, wx.TOP, 5)
        vbox.Add(clr, 0, wx.TOP, 5)

        btnPanel.SetSizer(vbox)
        hbox.Add(btnPanel, 0.6, wx.EXPAND | wx.RIGHT, 20)
        panel.SetSizer(hbox)

        self.Centre()
        self.Show(True)

    def NewItem(self, event):
        text = wx.GetTextFromUser('Enter a new item', 'Insert dialog')
        if text != '':
            self.listbox.Append(text)

    def OnRename(self, event):
        sel = self.listbox.GetSelection()
        text = self.listbox.GetString(sel)
        renamed = wx.GetTextFromUser('Rename item', 'Rename dialog', text)
        if renamed != '':
            self.listbox.Delete(sel)
            self.listbox.Insert(renamed, sel)


    def OnDelete(self, event):
        sel = self.listbox.GetSelection()
        if sel != -1:
            self.listbox.Delete(sel)

    def OnClear(self, event):
        self.listbox.Clear()


app = wx.App()
ListBox(None, -1, 'ListBox')
app.MainLoop()

wxpython widgets wx.SpinCtrl

wxpython widgets wx.SpinCtrl

The wx.SpinCtrl widget lets us increment and decrement a value. It has two up and down arrow buttons for this purpose. 
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)

        
        wx.StaticText(self, label='Convert Fahrenheit temperature to Celsius', 
            pos=(20,20))
        wx.StaticText(self, label='Fahrenheit: ', pos=(20, 80))
        wx.StaticText(self, label='Celsius: ', pos=(20, 150))
        
        self.celsius = wx.StaticText(self, label='', pos=(150, 150))
        self.sc = wx.SpinCtrl(self, value='0', pos=(150, 75), size=(60, -1))
        self.sc.SetRange(-459, 1000)
        
        btn = wx.Button(self, label='Compute', pos=(70, 230))
        btn.SetFocus()
        cbtn = wx.Button(self, label='Close', pos=(185, 230))

        btn.Bind(wx.EVT_BUTTON, self.OnCompute)
        cbtn.Bind(wx.EVT_BUTTON, self.OnClose)
           
        self.SetSize((350, 310))
        self.SetTitle('wx.SpinCtrl')
        self.Centre()
        self.Show(True)          
        
    def OnClose(self, e):
        
        self.Close(True)    
        
    def OnCompute(self, e):
        
        fahr = self.sc.GetValue()
        cels = round((fahr - 32) * 5 / 9.0, 2)
        self.celsius.SetLabel(str(cels))        
                      
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

wxpython widgets wx.Slider

wxpython widgets wx.Slider

wx.Slider is a widget that has a simple handle. This handle can be pulled back and forth. This way we can choose a specific task.
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)

        sld = wx.Slider(pnl, value=200, minValue=150, maxValue=500, pos=(20, 20), 
            size=(250, -1), style=wx.SL_HORIZONTAL)
        
        sld.Bind(wx.EVT_SCROLL, self.OnSliderScroll)
        
        self.txt = wx.StaticText(pnl, label='200', pos=(20, 90))               
        
        self.SetSize((290, 200))
        self.SetTitle('wx.Slider')
        self.Centre()
        self.Show(True)    

    def OnSliderScroll(self, e):
        
        obj = e.GetEventObject()
        val = obj.GetValue()
        
        self.txt.SetLabel(str(val))        

                      
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

wxpython widgets wx.Gauge

wxpython widgets wx.Gauge

wx.Gauge is a widget that is used, when we process lengthy tasks. It has an indicator to show the current state of a task.
 
import wx

TASK_RANGE = 50

class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   
        
        self.timer = wx.Timer(self, 1)
        self.count = 0

        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)

        pnl = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)

        self.gauge = wx.Gauge(pnl, range=TASK_RANGE, size=(250, 25))
        self.btn1 = wx.Button(pnl, wx.ID_OK)
        self.btn2 = wx.Button(pnl, wx.ID_STOP)
        self.text = wx.StaticText(pnl, label='Task to be done')

        self.Bind(wx.EVT_BUTTON, self.OnOk, self.btn1)
        self.Bind(wx.EVT_BUTTON, self.OnStop, self.btn2)

        hbox1.Add(self.gauge, proportion=1, flag=wx.ALIGN_CENTRE)
        hbox2.Add(self.btn1, proportion=1, flag=wx.RIGHT, border=10)
        hbox2.Add(self.btn2, proportion=1)
        hbox3.Add(self.text, proportion=1)
        vbox.Add((0, 30))
        vbox.Add(hbox1, flag=wx.ALIGN_CENTRE)
        vbox.Add((0, 20))
        vbox.Add(hbox2, proportion=1, flag=wx.ALIGN_CENTRE)
        vbox.Add(hbox3, proportion=1, flag=wx.ALIGN_CENTRE)

        pnl.SetSizer(vbox)
        
        self.SetSize((300, 200))
        self.SetTitle('wx.Gauge')
        self.Centre()
        self.Show(True)     

    def OnOk(self, e):
        
        if self.count >= TASK_RANGE:
            return

        self.timer.Start(100)
        self.text.SetLabel('Task in Progress')

    def OnStop(self, e):
        
        if self.count == 0 or self.count >= TASK_RANGE or not self.timer.IsRunning():
            return

        self.timer.Stop()
        self.text.SetLabel('Task Interrupted')
        
    def OnTimer(self, e):
        
        self.count = self.count + 1
        self.gauge.SetValue(self.count)
        
        if self.count == TASK_RANGE:

            self.timer.Stop()
            self.text.SetLabel('Task Completed')
                      
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()    

wxpython widgets wx.RadioButton

wxpython widgets wx.RadioButton

wx.RadioButton is a widget that allows the user to select a single exclusive choice from a group of options.
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   
            
        pnl = wx.Panel(self)

        self.rb1 = wx.RadioButton(pnl, label='Value A', pos=(10, 10), 
            style=wx.RB_GROUP)
        self.rb2 = wx.RadioButton(pnl, label='Value B', pos=(10, 30))
        self.rb3 = wx.RadioButton(pnl, label='Value C', pos=(10, 50))
        
        self.rb1.Bind(wx.EVT_RADIOBUTTON, self.SetVal)
        self.rb2.Bind(wx.EVT_RADIOBUTTON, self.SetVal)
        self.rb3.Bind(wx.EVT_RADIOBUTTON, self.SetVal)

        self.sb = self.CreateStatusBar(3)
        
        self.sb.SetStatusText("True", 0)
        self.sb.SetStatusText("False", 1)
        self.sb.SetStatusText("False", 2)   

        self.SetSize((210, 210))
        self.SetTitle('wx.RadioButton')
        self.Centre()
        self.Show(True)     

    def SetVal(self, e):
        
        state1 = str(self.rb1.GetValue())
        state2 = str(self.rb2.GetValue())
        state3 = str(self.rb3.GetValue())

        self.sb.SetStatusText(state1, 0)
        self.sb.SetStatusText(state2, 1)
        self.sb.SetStatusText(state3, 2)            
        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()  

wxpython widgets wx.StatusBar

wxpython widgets wx.StatusBar

wx.StatusBar widget is used to display application status information.
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)

        button = wx.Button(pnl, label='Button', pos=(20, 20))
        text = wx.CheckBox(pnl, label='CheckBox', pos=(20, 90))
        combo = wx.ComboBox(pnl, pos=(120, 22), choices=['Python', 'Ruby'])
        slider = wx.Slider(pnl, 5, 6, 1, 10, (120, 90), (110, -1))        

        pnl.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
        button.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
        text.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
        combo.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
        slider.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)

        self.sb = self.CreateStatusBar()

        self.SetSize((250, 230))
        self.SetTitle('wx.Statusbar')
        self.Centre()
        self.Show(True)     

    def OnWidgetEnter(self, e):
        
        name = e.GetEventObject().GetClassName()
        self.sb.SetStatusText(name + ' widget')
        e.Skip()               
        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main() 

wxpython widgets wx.CheckBox

wxpython widgets wx.CheckBox

wx.CheckBox is a widget that has two states: on and off. It is a box with a label. The label can be set to the right or to the left of the box. 
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)

        cb = wx.CheckBox(pnl, label='Show title', pos=(20, 20))
        cb.SetValue(True) #constructor of the wx.CheckBox widget

        cb.Bind(wx.EVT_CHECKBOX, self.ShowOrHideTitle)

        self.SetSize((250, 170))
        self.SetTitle('wx.CheckBox')
        self.Centre()
        self.Show(True)    

    def ShowOrHideTitle(self, e):
        
        sender = e.GetEventObject()
        isChecked = sender.GetValue()
        
        if isChecked:
            self.SetTitle('wx.CheckBox')            
        else: 
            self.SetTitle('')        
                       
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

wxpython widgets wx.ComboBox

wxpython widgets wx.ComboBox 

wx.ComboBox is a combination of a single line text field, a button with a down arrow image and a listbox. When you press the button, a listbox appears.
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)
        
        distros = ['Ubuntu', 'Arch', 'Fedora', 'Debian', 'Mint']
        cb = wx.ComboBox(pnl, pos=(50, 30), choices=distros, 
            style=wx.CB_READONLY)

        self.st = wx.StaticText(pnl, label='', pos=(50, 140))
        cb.Bind(wx.EVT_COMBOBOX, self.OnSelect)
        
        self.SetSize((250, 230))
        self.SetTitle('wx.ComboBox')
        self.Centre()
        self.Show(True)          
        
    def OnSelect(self, e):
        
        i = e.GetString()
        self.st.SetLabel(i)
        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()  

wxpython widgets wx.StaticBox

wxpython widgets wx.StaticBox

This is a kind of a decorator widget. It is used to logically group various widgets.  
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)
        
        wx.StaticBox(pnl, label='Personal Info', pos=(5, 5), size=(240, 170))
        wx.CheckBox(pnl, label='Male', pos=(15, 30))
        wx.CheckBox(pnl, label='Married', pos=(15, 55))
        wx.StaticText(pnl, label='Age', pos=(15, 95))
        wx.SpinCtrl(pnl, value='1', pos=(55, 90), size=(60, -1), min=1, max=120)
        
        btn = wx.Button(pnl, label='Ok', pos=(90, 185), size=(60, -1))

        btn.Bind(wx.EVT_BUTTON, self.OnClose)

        self.SetSize((270, 250))
        self.SetTitle('Static box')
        self.Centre()
        self.Show(True)          
        
    def OnClose(self, e):
        
        self.Close(True)    
               
        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()   

wxpython widgets wx.StaticText

wxpython widgets wx.StaticText

A wx.StaticText widget displays one or more lines of read-only text.

 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        txt1 = '''I'm giving up the ghost of love
in the shadows cast on devotion
She is the one that I adore
creed of my silent suffocation
Break this bittersweet spell on me
lost in the arms of destiny'''

        txt2 = '''There is something in the way
You're always somewhere else
Feelings have deserted me
To a point of no return
I don't believe in God
But I pray for you'''

        pnl = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)
        
        st1 = wx.StaticText(pnl, label=txt1, style=wx.ALIGN_CENTRE)
        st2 = wx.StaticText(pnl, label=txt2, style=wx.ALIGN_CENTRE)
        
        vbox.Add(st1, flag=wx.ALL, border=5)
        vbox.Add(st2, flag=wx.ALL, border=5)
        pnl.SetSizer(vbox)
        
        self.SetSize((250, 260))
        self.SetTitle('Bittersweet')
        self.Centre()
        self.Show(True)          
                        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

Sunday, May 29, 2016

Python String and Variables Example Code

Python String and Variables Example Code
 
#!/usr/bin/python

str = 'Hello World!'
print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 5th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string
#------------------------------------------------------------------
str = "this is string example....wow!!!";
print "str.capitalize() : ", str.capitalize()
#------------------------------------------------------------------
# This is a comment.
#Syntax str.center(width[, fillchar]) width -- This is the total width of the string. fillchar -- This is the filler character.
str = "this is string example....wow!!!";
print "str.center(40, 'a') : ", str.center(40, 'a')
#------------------------------------------------------------------
#string count
#Syntax str.count(sub, start= 0,end=len(string))
str = "this is string example....wow!!!";
sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)
#------------------------------------------------------------------
#string len
str = "this is string example....wow!!!";
print "Length of the string: ", len(str);
#------------------------------------------------------------------
myString = "abc"
stringLength = len(myString)
print stringLength
#------------------------------------------------------------------
string1 = "abra"
string2 = "cadabra"
magicString = string1 + string2
print magicString
#------------------------------------------------------------------
myNumber = "2"
print myNumber + myNumber
#------------------------------------------------------------------
myNumber = "12"
print myNumber * 3
#------------------------------------------------------------------
myNumber = "12"
print int(myNumber)
#------------------------------------------------------------------
phrase = "the surprise is in here somewhere"
print phrase.find("surprise") #== output 4
#------------------------------------------------------------------
myStory = "I'm telling you the truth; he spoke nothing but the truth!"
print myStory.replace("the truth", "lies") # I'm telling you lies; he spoke nothing but lies!
#------------------------------------------------------------------
counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string
print (counter)
print (miles)
print (name)
#------------------------------------------------------------------
long_string = '''This is a
string that spans across multiple lines'''
long_string = """This is a new string
that spans across two lines"""
#------------------------------------------------------------------
string1 = "abra"
string2 = "cadabra"
magic_string = string1 + string2
print(magic_string)
#------------------------------------------------------------------
print("abra"+"ca"+"dabra") #abracadabra
print("abra", "ca", "dabra") # abra ca dabra
#------------------------------------------------------------------
flavor = "birthday cake"
print(flavor[3]) #t
print(flavor[0]) #b
#------------------------------------------------------------------
flavor = "birthday cake"
print(flavor[0:3]) # bir
#------------------------------------------------------------------
flavor = "birthday cake"
print(flavor[:5]) # birth
print(flavor[5:]) # day cake
print(flavor[:]) # birthday cake
#------------------------------------------------------------------
my_string = "abc"
string_length = len(my_string)
print(string_length) # 3
#------------------------------------------------------------------
name1 = "Jane"
age1 = 12
print name1, age1
#------------------------------------------------------------------
baskets = 16
apples_in_basket = 24
total = baskets * apples_in_basket
print "There are total of", total, "apples" #There are total of 384 apples
#------------------------------------------------------------------
distance = 0.1
time = 9.87 / 3600
speed = distance / time
print "The average speed of" \
      " a sprinter is " , speed, "km/h" #The average speed of a sprinter is  36.4741641337 km/h
#------------------------------------------------------------------
print "eagle " * 5 # eagle eagle eagle eagle eagle 
print "eagle " "falcon" # eagle falcon
print "eagle " + "and " + "falcon" # eagle and falcon
#------------------------------------------------------------------
first = (1, 2, 3)
second = (4, 5, 6)
print "len(first) : ", len(first) # len(first) :  3
print "max(first) : ", max(first) # max(first) :  3
print "min(first) : ", min(first) # min(first) :  1
print "first + second :", first + second # first + second : (1, 2, 3, 4, 5, 6)
print "first * 3 : ", first * 3 # first * 3 :  (1, 2, 3, 1, 2, 3, 1, 2, 3)
print "1 in first : ", 1 in first # 1 in first :  True
print "5 not in second : ", 5 not in second # 5 not in second :  False
#------------------------------------------------------------------
five = (1, 2, 3, 4, 5)
print "five[0] : ", five[0] # five[0] :  1
print "five[-1] : ", five[-1] # five[-1] :  5
print "five[-2] : ", five[-2] # five[-2] :  4
print "five[:] : ", five[:] # five[:] :  (1, 2, 3, 4, 5)
print "five[0:4] : ", five[0:4] # five[0:4] :  (1, 2, 3, 4)
print "five[1:2] : ", five[1:2] # five[1:2] :  (2,)
print "five[:2] : ", five[:2] # five[:2] :  (1, 2) 
print "five[:-1] : ", five[:-1] # five[:-1] :  (1, 2, 3, 4)
print "five[:9] : ", five[:9] # five[:9] :  (1, 2, 3, 4, 5)
#------------------------------------------------------------------
mix = (1, 2, "solaris", (1, 2, 3))
print "mix[1] :", mix[1] # mix[1] : 2
print "mix[2] :", mix[2] # mix[2] : solaris
print "mix[3] :", mix[3] # mix[3] : (1, 2, 3)
print "mix[3][0] :", mix[3][0] # mix[3][0] : 1
print "mix[3][1] :", mix[3][1] # mix[3][1] : 2
print "mix[3][2] :", mix[3][2] # mix[3][2] : 3
#------------------------------------------------------------------
s = " Eagle  "
s2 = s.rstrip()
s3 = s.lstrip()
s4 = s.strip()
print s, len(s) # Eagle   8
print s2, len(s2) # Eagle 6
print s3, len(s3) # Eagle   7
print s4, len(s4) # Eagle 5
#------------------------------------------------------------------
print "Incompatible, it don't matter though\n'cos someone's bound to hear my cry"
print "Speak out if you do\nYou're not easy to find"
#------------------------------------------------------------------
print "12" == "12" # True
print "17" == "9" # False
print "aa" == "ab" # False
print "abc" != "bce" # True
print "efg" != "efg" # False
#------------------------------------------------------------------
import math
pi = 3.14
print math.cos(3) # -0.9899924966
print math.pi # 3.14159265359
print math.sin(3) # 0.14112000806
print pi # 3.14

Python Package Example

Python Package Example
 
#A package is a collection of modules which have a common purpose. Technically a package is a directory which must have one special file called __init__.py
#user interface code structure
#read.py
#constants/
    # __init__.py
    #names.py

#In our current working directory we have a constants directory and a read.py script.
# __init__.py
from names import names # import names (names.py)
print "initializing constants package"

# names.py
names = ('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')

# read.py = root directory
import constants # import constants (folder name constants)
print constants.names
#output
#initializing constants package
#('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')

# create subpackages. To access subpackages, we use the dot operator
#read.py
#constants/
          #__init__.py
          #names.py 
          #numbers/
                   #__init__.py
                   #integers.py
#This is the new hierarchy. We have a subpackage called numbers.
#constant/numbers/__init__.py
from integers import integers

# integers.py
integers = (2, 3, 45, 6, 7, 8, 9)

# read.py
import constants
import constants.numbers as int

print constants.names
print int.integers
#output
#initializing constants package
#('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')
#(2, 3, 45, 6, 7, 8, 9)


Python OOP object oriented programming Example code

Python OOP object oriented programming Example code
 
#OOP object oriented programming
#class keyword
class First:
   pass
fr = First()
print type(fr)
print type(First)
#---------------------------------------------------------------------
class Cat:
   def __init__(self, name):
      self.name = name
missy = Cat('Missy')
lucky = Cat('Lucky')
print missy.name # Missy
print lucky.name # Lucky
#---------------------------------------------------------------------
class Cat:
   species = 'mammal'
   def __init__(self, name, age):
      self.name = name
      self.age = age
missy = Cat('Missy', 3)
lucky = Cat('Lucky', 5)
print missy.name, missy.age # Missy 3
print lucky.name, lucky.age # Lucky 5
print Cat.species # mammal
print missy.__class__.species # mammal
print lucky.__class__.species # mammal
#---------------------------------------------------------------------
#Methods
#Methods are functions defined inside the body of a class
class Circle:
   pi = 3.141592
   def __init__(self, radius=1):
      self.radius = radius 
   def area(self):
      return self.radius * self.radius * Circle.pi
   def setRadius(self, radius):
      self.radius = radius
   def getRadius(self):
      return self.radius
c = Circle()
c.setRadius(5)
print c.getRadius() # 5
print c.area() # 78.5398
#---------------------------------------------------------------------
class Methods:
   def __init__(self):
      self.name = 'Methods'
   def getName(self):
      return self.name
m = Methods()
print m.getName() # Methods
print Methods.getName(m) # Methods
#---------------------------------------------------------------------
#Inheritance
#inheritance is a way to form new classes using classes that have already been defined
class Animal:
   def __init__(self):
      print "Animal created"
   def whoAmI(self):
      print "Animal"
   def eat(self):
      print "Eating"
class Dog(Animal):
   def __init__(self):
      Animal.__init__(self)
      print "Dog created"
   def whoAmI(self):
      print "Dog"
   def bark(self):
      print "Woof!"
d = Dog()
d.whoAmI()
d.eat()
d.bark()
#---------------------------------------------------------------------
class Animal:
   def __init__(self, name=''):
      self.name = name
   def talk(self):
      pass
class Cat(Animal):
   def talk(self):
      print "Meow!"
class Dog(Animal):
   def talk(self):
      print "Woof!"
a = Animal()
a.talk()
c = Cat("Missy")
c.talk()
d = Dog("Rocky")
d.talk()
# Meow! Woof!
#---------------------------------------------------------------------
#Special Methods name
class Book:
   def __init__(self, title, author, pages):
      print "A book is created"
      self.title = title
      self.author = author
      self.pages = pages
   def __str__(self):
      return "Title:%s , author:%s, pages:%s " % \
              (self.title, self.author, self.pages)
   def __len__(self):
      return self.pages
   def __del__(self):
      print "A book is destroyed"
book = Book("Inside Steve's Brain", "Leander Kahney", 304)
print book
print len(book)
del book

Python List Example code

Python List Example code
 
#!/usr/bin/python
#list is a mutable sequence data type

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd till 3rd 
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists
#------------------------------------------------------------------
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
#------------------------------------------------------------------
#Updating Lists
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2];
list[2] = 2001;
print "New value available at index 2 : "
print list[2];
#------------------------------------------------------------------
colors = ["red", "green", "burnt sienna", "blue"]
print colors
print colors[0:2]
#------------------------------------------------------------------
colors = ["red", "green", "burnt sienna", "blue"]
colors[0] = "burgundy"
colors[3] = "electric indigo"
print colors
#------------------------------------------------------------------
animals = []
animals.append("lion")
animals.append("tiger")
animals.append("frumious Bandersnatch")
print animals
#------------------------------------------------------------------
groceries = "eggs, spam, pop rocks, cheese"
groceryList = groceries.split(", ")
print groceryList
#------------------------------------------------------------------
zero = 1
one = 2
two = [5, 4, 3, 2, 1, 0]
three = "I love Python!"
four = [["P", "y", "t", "h", "o", "n"],["i", "s"],["h", "a", "r","d"]]
five = {"happy":"birthday"}
six = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
days = ("Fri", "Sat", "Sun")
x, y, seven = days
print "zero: {}".format(zero == 0)
print "one: {}".format(one > 22)
print "two: {}".format(len(two) == 5)
print "three: {}".format(three[2] == "Python!")
print "four: {}".format(four[0][5] == 'n' and four[0][0] == "P" and four[2][1] == "u")
print "five: {}".format(five.get("fish") == "chips")
print "five: {}".format(len(five) == 3)
print "six: {}".format(len(six & {2,5,7}) == 2)
print "seven: {}".format(seven == "Wed")
#------------------------------------------------------------------
num = [0, 2, 5, 4, 6, 7]
print num[0] # 0
print num[2:] # [5, 4, 6, 7]
print len(num) # 6
print num + [8, 9] # [0, 2, 5, 4, 6, 7, 8, 9]
#------------------------------------------------------------------
numbers = [4, 3, 6, 1, 2, 0, 5 ]
print numbers # [4, 3, 6, 1, 2, 0, 5]
numbers.sort()
print numbers # [0, 1, 2, 3, 4, 5, 6]
numbers.reverse() 
print numbers #  [5, 4, 3, 2, 1, 0]
#------------------------------------------------------------------
numbers = [0, 0, 2, 3, 3, 3, 3]
print "zero is here ",  numbers.count(0), "times"  # zero is here  2 times
print "one is here ",   numbers.count(1), "times" # one is here  0 times
print "two is here ",   numbers.count(2), "time"  # two is here  1 time
print "three is here ", numbers.count(3), "times" # three is here  4 times
#------------------------------------------------------------------
names = []
names.append("Frank")
names.append("Alexis")
names.append("Erika")
names.append("Ludmila")
print names # ['Frank', 'Alexis', 'Erika', 'Ludmila']
names.insert(0, "Adriana")
print names # ['Adriana', 'Frank', 'Alexis', 'Erika', 'Ludmila']
names.remove("Frank")
names.remove("Alexis")
del names[1] 
print names # ['Adriana', 'Ludmila']
del names[0]
print names # ['Ludmila']
#------------------------------------------------------------------
first = [1, 2, 3]
second = [4, 5, 6]
first.extend(second)
print first # [1, 2, 3, 4, 5, 6]
first[0] = 11
first[1] = 22
first[2] = 33
print first # [11, 22, 33, 4, 5, 6]
print first.pop(5) # 6
print first # [11, 22, 33, 4, 5]
#------------------------------------------------------------------
numbers = [0, 1, 2, 3, 3, 4, 5]
print numbers.index(1) # 1
print numbers.index(3) # 3
#------------------------------------------------------------------
set1 = set(['a', 'b', 'c', 'c', 'd'])
set2 = set(['a', 'b', 'x', 'y', 'z'])
print "set1: " , set1 # set1:  set(['a', 'c', 'b', 'd'])
print "set2: " , set2 # set2:  set(['a', 'x', 'b', 'y', 'z'])
print "intersection: ", set1 & set2 # intersection:  set(['a', 'b'])
print "union: ", set1 | set2 # union:  set(['a', 'c', 'b', 'd', 'y', 'x', 'z'])
print "difference: ", set1 - set2 # difference:  set(['c', 'd'])
print "symmetric difference: ", set1 ^ set2 # symmetric difference:  set(['c', 'd', 'y', 'x', 'z'])
#------------------------------------------------------------------
set1 = set([1, 2])
set1.add(3)
set1.add(4)
set2 = set([1, 2, 3, 4, 6, 7, 8])
set2.remove(8)
print set1 # set([1, 2, 3, 4])
print set2 # set([1, 2, 3, 4, 6, 7])
print "Is set1 subset of set2 ? : ", set1.issubset(set2) # Is set1 subset of set2 ? :  True
print "Is set1 superset of set2 ? : ", set1.issuperset(set2) # Is set1 superset of set2 ? :  False
set1.clear()
print set1 # set([])
#------------------------------------------------------------------
words = { 'girl': 'Maedchen', 'house': 'Haus', 'death': 'Tod' }
print words['house'] # Haus
print words.keys() # ['house', 'girl', 'death']
print words.values() # ['Haus', 'Maedchen', 'Tod']
print words.items() # [('house', 'Haus'), ('girl', 'Maedchen'), ('death', 'Tod')]
print words.pop('girl') # Maedchen
print words # {'house': 'Haus', 'death': 'Tod'}
words.clear()
print words # {}
#------------------------------------------------------------------
a = []
b = list()
print a == b # True
print list((1, 2, 3)) # [1, 2, 3]
print list("ZetCode") # ['Z', 'e', 't', 'C', 'o', 'd', 'e']
print list(['Ruby', 'Python', 'Perl']) # ['Ruby', 'Python', 'Perl']
#------------------------------------------------------------------
n1 = [1, 2, 3, 4, 5]
n2 = [3, 4, 5, 6, 7]
print n1 == n2 # False
print n1 + n2 # [1, 2, 3, 4, 5, 3, 4, 5, 6, 7]
print n1 * 3 # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
print 2 in n1 # True
print 2 in n2 # False
#------------------------------------------------------------------
n = [1, 2, 3, 4, 5, 6, 7, 8]
print "There are %d items" % len(n) # There are 8 items
print "Maximum is %d" % max(n) # Maximum is 8
print "Minimum is %d" % min(n) # Minimum is 1
print "The sum of values is %d" % sum(n) # The sum of values is 36
#------------------------------------------------------------------
langs = list()
langs.append("Python")
langs.append("Perl")
print langs # ['Python', 'Perl']
langs.insert(0, "PHP")
langs.insert(2, "Lua")
print langs # ['PHP', 'Python', 'Lua', 'Perl']
langs.extend(("JavaScript", "ActionScript"))
print langs # ['PHP', 'Python', 'Lua', 'Perl', 'JavaScript', 'ActionScript']
#------------------------------------------------------------------
#IndexError, TypeError
n = [1, 2, 3, 4, 5]
try:
    n[0] = 10
    n[6] = 60
except IndexError, e:
    print e # list assignment index out of range
#------------------------------------------------------------------
# TypeError
n = [1, 2, 3, 4, 5]
try:
    print n[1]
    print n['2']
except TypeError, e:
    print "Error in file %s" % __file__
    print "Message: %s" % e # Message: list indices must be integers, not str
#------------------------------------------------------------------    
#Removing elements
langs = ["Python", "Ruby", "Perl", "Lua", "JavaScript"]
print langs # ['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript']
langs.pop(3)
langs.pop()
print langs # ['Python', 'Ruby', 'Perl']
langs.remove("Ruby")
print langs # ['Python', 'Perl']
#------------------------------------------------------------------   
#Modifying elements
langs = ["Python", "Ruby", "Perl"]
langs.pop(2)
langs.insert(2, "PHP")
print langs # ['Python', 'Ruby', 'PHP']
langs[2] = "Perl"
print langs # ['Python', 'Ruby', 'Perl']
#------------------------------------------------------------------  
#Indexing list elements
n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[0] # 1
print n[-1] # 8
print n[-2] # 7
print n[3] # 4
print n[5] # 6
#------------------------------------------------------------------ 
n = [1, 2, 3, 4, 1, 2, 3, 1, 2]
print n.index(1) # 0
print n.index(2) # 1
print n.index(1, 1) # 4
print n.index(2, 2) # 5
print n.index(1, 2, 5) # 4
print n.index(3, 4, 8) # 6
#------------------------------------------------------------------ 
#Slicing
n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[1:5] # [2, 3, 4, 5]
print n[:5] # [1, 2, 3, 4, 5]
print n[1:] # [2, 3, 4, 5, 6, 7, 8]
print n[:] # [1, 2, 3, 4, 5, 6, 7, 8]
#------------------------------------------------------------------
basket = { 'oranges': 12, 'pears': 5, 'apples': 4 }
basket['bananas'] = 5
print basket # {'bananas': 5, 'pears': 5, 'oranges': 12, 'apples': 4}
print "There are %d various items in the basket" % len(basket) # There are 4 various items in the basket
print basket['apples'] # 4
basket['apples'] = 8 
print basket['apples'] # 8
print basket.get('oranges', 'undefined') # 8
print basket.get('cherries', 'undefined') # undefined
#------------------------------------------------------------------
domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }
for key in domains:
    print key
for k in domains:
    print domains[k]
for k, v in domains.items():
    print ": ".join((k, v))
#------------------------------------------------------------------
items = { "coins": 7, "pens": 3, "cups": 2, 
    "bags": 1, "bottles": 4, "books": 5 }
kitems = items.keys()
kitems.sort()
for k in kitems:
    print ": ".join((k, str(items[k]))) # bags: 1 books: 5 bottles: 4 coins: 7 cups: 2 pens: 3
#------------------------------------------------------------------
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];

Python Date and time Example code

Python Date and time Example code
 
#!/usr/bin/python
import time;  # This is required to include time module.

ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks


localtime = time.localtime(time.time())
print "Local current time :", localtime

#formated time
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)

#Getting calendar for a month
import calendar
cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)

Python Class Example code

Python Class Example code
 
class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print ("Total Employee %d" % Employee.empCount)

   def displayEmployee(self):
      print ("Name : ", self.name,  ", Salary: ", self.salary)
#This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
#This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
#--------------------------------------------------------------
class Square:
   def __init__(self, x):
      self.a = x
   def area(self):
      print self.a * self.a
sq = Square(12)
sq.area()

Saturday, May 28, 2016

wxpython widgets wx.StaticText

wxpython widgets wx.StaticText

A wx.StaticText widget displays one or more lines of read-only text. 
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        txt1 = '''I'm giving up the ghost of love
in the shadows cast on devotion
She is the one that I adore
creed of my silent suffocation
Break this bittersweet spell on me
lost in the arms of destiny'''

        txt2 = '''There is something in the way
You're always somewhere else
Feelings have deserted me
To a point of no return
I don't believe in God
But I pray for you'''

        pnl = wx.Panel(self) #create panel
        vbox = wx.BoxSizer(wx.VERTICAL)
        #This is a string to be shown in the wx.StaticText widget.
        #wx.StaticText(variable panel,lable,style)
        st1 = wx.StaticText(pnl, label=txt1, style=wx.ALIGN_CENTRE)
        st2 = wx.StaticText(pnl, label=txt2, style=wx.ALIGN_CENTRE)
        
        vbox.Add(st1, flag=wx.ALL, border=5)
        vbox.Add(st2, flag=wx.ALL, border=5)
        pnl.SetSizer(vbox)
        
        self.SetSize((250, 260))
        self.SetTitle('Bittersweet')
        self.Centre()
        self.Show(True)          
                        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

wxpython widgets wx.StaticLine

wxpython widgets wx.StaticLine

This widget displays a simple line on the window. It can be horizontal or vertical.
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI() #call function def InitUI(self):
        
    def InitUI(self):   

        pnl = wx.Panel(self) #create panel

        font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD)
        heading = wx.StaticText(self, label='The Central Europe', pos=(130, 15))
        heading.SetFont(font)

        wx.StaticLine(self, pos=(25, 50), size=(300,1))

        wx.StaticText(self, label='Slovakia', pos=(25, 80))
        wx.StaticText(self, label='Hungary', pos=(25, 100))
        wx.StaticText(self, label='Poland', pos=(25, 120))
        wx.StaticText(self, label='Czech Republic', pos=(25, 140))
        wx.StaticText(self, label='Germany', pos=(25, 160))
        wx.StaticText(self, label='Slovenia', pos=(25, 180))
        wx.StaticText(self, label='Austria', pos=(25, 200))
        wx.StaticText(self, label='Switzerland', pos=(25, 220))

        wx.StaticText(self, label='5 445 000', pos=(250, 80))
        wx.StaticText(self, label='10 014 000', pos=(250, 100))
        wx.StaticText(self, label='38 186 000', pos=(250, 120))
        wx.StaticText(self, label='10 562 000', pos=(250, 140))
        wx.StaticText(self, label='81 799 000', pos=(250, 160))
        wx.StaticText(self, label='2 050 000', pos=(250, 180))
        wx.StaticText(self, label='8 414 000', pos=(250, 200))
        wx.StaticText(self, label='7 866 000', pos=(250, 220))

        wx.StaticLine(self, pos=(25, 260), size=(300,1))

        tsum = wx.StaticText(self, label='164 336 000', pos=(240, 280))
        sum_font = tsum.GetFont()
        sum_font.SetWeight(wx.BOLD)
        tsum.SetFont(sum_font)

        btn = wx.Button(self, label='Close', pos=(140, 310))

        btn.Bind(wx.EVT_BUTTON, self.OnClose)        
        
        self.SetSize((360, 380))
        self.SetTitle('wx.StaticLine')#form panel title
        self.Centre()
        self.Show(True)      
        
    def OnClose(self, e):
        
        self.Close(True)    
                      
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

Related Post