Ene Uran 638 Posting Virtuoso

Just a note:
The easiest way to break out of the innermost loop of nested loops is to put them into a function and use return instead of break.

Ene Uran 638 Posting Virtuoso

Oh dear,
my advice to any beginner, start with small programs and experiment with them to get a feeling of what those widgets do. A mini frame can not be used as a toolbar! It is just like a frame with limitations.

Ene Uran 638 Posting Virtuoso

Put the ListBox in a sizer.

Ene Uran 638 Posting Virtuoso

Just for the sake of being pythonic:

book = ['1234', '1235', '1236', '1237', '1238']
# you only need to open the file once
f = open('/home/tandberg/booklist', 'w')
for a in book:
	f.write(a + '\n')
f.close()
Ene Uran 638 Posting Virtuoso

You could try this approach:

def extract_number(data_str):
    """
    extract the numeric value from a string
    the string should contain only one number
    return the number string
    """
    s = ""
    for c in data_str:
        if c in '1234567890.-':
            s += c
    return s

mydata = """\
density = -1.0
number = 2004
"""

# write a test data file
fout = open("my_data.txt", "w")
fout.write(mydata)
fout.close()

newdata = ""
for line in file("my_data.txt"):
    newdata += extract_number(line) + '\n'

# test
print(newdata)

# write the new data file
fout = open("my_numbers.txt", "w")
fout.write(newdata)
fout.close()
Ene Uran 638 Posting Virtuoso

shadwickman is right,
data = [x.strip() for x in line.split('=')]
works because x inside the list comprehension is still a string and not a list yet.

You might want to convert the numeric strings to actual numbers you can do calculations with using int() or float(). Here is my dime's worth:

mydata = """\
density = -1.0
number = 2004
"""

# write a test data file
fout = open("mydata.txt", "w")
fout.write(mydata)
fout.close()

for line in file("mydata.txt"):
    data = [x.strip() for x in line.split('=')]
    if 'density' in data:
        density = float(data[1])
    if 'number' in data:
        # if it's always a whole number use int()
        number = int(data[1])

# test
print(density)  # -1.0
print(number)   # 2004
Ene Uran 638 Posting Virtuoso

Simply use list():

list1 = ['a', 'b', 'c', 'd']
# this will create a new list with a different mem ref
temp_list1 = list(list1)
for i in range(len(list1)):
    temp_list1[i] = "1"
print list1;              # ['a', 'b', 'c', 'd']
print temp_list1;         # ['1', '1', '1', '1']

For nested lists you need to use deepcopy() from module copy.

shadwickman commented: Well I learned something new about using list() :P +4
Ene Uran 638 Posting Virtuoso

Can anyone give me a qick review about Python

Why its good ?

Why its not ?

What is the most suitable type of project for it ?? (application)

And so one

Thanks for your help

You strike me as the kind of inquisitive person that is made for learning C++, with the ever so powerful C++ you can do any project!

Ene Uran 638 Posting Virtuoso

Might as well go with:

...
background = "C:\\python26\\stuff\\bg.jpg"
background_surface = pygame.image.load(background)
...

Since that kind of directory name is meant for Windows only.

Ene Uran 638 Posting Virtuoso

Where are your FileIn and FileOut strings?

Ene Uran 638 Posting Virtuoso

You mean something like this:

# data string read from a file
data = """\
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 95 20 1 0 68 87 31017559 31017578 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 91.67 24 2 0 63 86 35247737 35247714 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 91.67 24 2 0 64 87 40549054 40549031 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 92 24 2 0 63 86 42462636 42462659 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 95 20 1 0 63 82 45774066 45774085 4.4 32.3
"""

new_data = ""
for line in data.split('\n'):
    # replace each space with a tab
    line = line.replace(" ", "\t")
    new_data += line + '\n'

# test only ...
print(new_data)

# now write new_data string to a file
lllllIllIlllI commented: ahh! Beat me too it :P +4
Ene Uran 638 Posting Virtuoso

In complete darkness we are all the same, it is only our knowledge and wisdom that separates us.
-- Janet Jackson

Ene Uran 638 Posting Virtuoso

The burn unit at the hospital I work has received large donations from Michael. He was a great man in every way!

Ene Uran 638 Posting Virtuoso

I am amazed.

that hamburger and fries is crazy. i'd love to be on the judging team to sample those.

Why, it would taste like Jello.

Ene Uran 638 Posting Virtuoso

I believe you.
...

Did you do your slightest bit of independent research on that?

Members of the Raelian sect believe the human soul dies when the body dies, believe in recreating individuals from their own genetic make-up.

Ene Uran 638 Posting Virtuoso

Let's see if the Omron Smile Scan system works on holders of State of California short term debts and bonds. California has started pay off with I.O.U.'s rather than actual money.

jephthah commented: ouch :( +12
Ene Uran 638 Posting Virtuoso

One way to do this is to pad each word with spaces at the end to make the words equal in length (max length + 2):

s = """\
dasj    dhsahdwe	dhasdhajks	ewqhehwq	dsajkdhas
edward das	dsaw	das	daswf
fjdk    ewf	jken	dsajkw	dskdw
hklt    ewq	vn1	daskcn	daskw
"""

# create a word list
mylist = s.split()
#print mylist

# find maximum word length
length = 0
for w in mylist:
    size = len(w)
    if size > length:
        length = size

#print length

# pad spaces to the end of each word
# add a newline to every fifth word
newlist = []
# max length + 2 spaces
pad = length + 2
ix = 1
for w in mylist:
    size = len(w)
    # pad with spaces
    w = w + ' '*(pad - size)
    if ix % 5 == 0:
        # add a newline
        w = w + '\n'
    newlist.append(w)
    ix += 1

#print newlist

# now show the words in the new list
for w in newlist:
    print w,

"""
my display -->
dasj         dhsahdwe     dhasdhajks   ewqhehwq     dsajkdhas
edward       das          dsaw         das          daswf
fjdk         ewf          jken         dsajkw       dskdw
hklt         ewq          vn1          daskcn       daskw
"""

I used space padding, because tabs are set differently depending on the editor you want to display with.

Ene Uran 638 Posting Virtuoso

Oh that Aia!
Will she save America?

Ene Uran 638 Posting Virtuoso

I failed to be amazed!

Ene Uran 638 Posting Virtuoso

Judging from the poll, the end of the world will be "other", avoid "other"!

Ene Uran 638 Posting Virtuoso

Hey, Look!

It's AIA!

:)

???

Ene Uran 638 Posting Virtuoso

Shame is the mother of apprenticeship

Ene Uran 638 Posting Virtuoso

Why did we get into such a mess?
Instant food
Instant credit
Instant war
Instant debt

.. just to mention four reasons.

jephthah commented: succinct +12
Ene Uran 638 Posting Virtuoso

The last update of MS IE did me in, after it fooled around with my 'favorite folders'. I am now a very happy Firefox user.

tux4life commented: Firefox FTW!! +12
Ene Uran 638 Posting Virtuoso

The debt per person in the USA is cheap compared to other countries. Let's celebrate with Chinese fireworks! I love the stench of burning sulfur from the fireworks, much better than the normal LA stench.

ahihihi... commented: yeah +1
Ancient Dragon commented: So do I :) +36
Ene Uran 638 Posting Virtuoso

History has been kind to Winston Churchill, as it usually is to those who help save the world,
-- George W. Bush.

Ene Uran 638 Posting Virtuoso

In Python it would look like:

fout = open("test1.txt", "w")
fout.write("save something ...\n")
fout.write("save something more ...\n")
fout.close()

# or C++ style (allowed in Python2)
fout = open("test2.txt", "w")
print >>fout, "save something ..."
print >>fout, "save something more ..."
fout.close()

# more like PERL
import sys

old = sys.stdout
sys.stdout = file("test3.txt", "w")
print "save something ..."
print "save something more ..."

# reset
sys.stdout = old
The_Kernel commented: Yep, that about covers it :-) +1
Ene Uran 638 Posting Virtuoso

What do you expect to happen with your test code?
If you test the module properly, it will work:

# create two separate windows with a button on it
# notice that the close button will close both windows

from PyQt4 import QtGui, QtCore

class QuitButtonAA(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(100, 200, 250, 150)
        self.setWindowTitle('Icon AA')

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        self.connect(quit, QtCore.SIGNAL('clicked()'),
            QtGui.qApp, QtCore.SLOT('quit()'))

class QuitButtonBB(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Icon BB')

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        self.connect(quit, QtCore.SIGNAL('clicked()'),
            QtGui.qApp, QtCore.SLOT('quit()'))


# test the potential module
if __name__ == '__main__':
    import sys
    app =  QtGui.QApplication(sys.argv)
    b1 = QuitButtonAA()
    b1.show()
    b2 = QuitButtonBB()
    b2.show()
    app.exec_()
Ene Uran 638 Posting Virtuoso

Take the spaces out of ""[code = python]"

Ene Uran 638 Posting Virtuoso

@sravan953
also remember that in Python2 ' /' is an integer division by default.
For instance 12/15 gives you a zero. This has changed in Python3.

Ene Uran 638 Posting Virtuoso

Here is a general notebook widget class for Tkinter:

# testing a notebook widget class for Tkinter (modified)
# Python 2.5.4 ene

import Tkinter as tk

class Notebook(object):
    """
    a notebook widget class for Tkinter applications
    """
    def __init__(self, parent):
        self.active_page = None
        self.count = 0
        self.selected = tk.IntVar(0)
        # orientation of initial tab (can go 'bottom' too)
        side = 'top'
        # new tabs go
        self.side= 'left'
        # create notebook's initial page frame
        self.tab = tk.Frame(parent)
        self.tab.pack(side=side, fill='both')
        self.page = tk.Frame(parent)
        self.page.pack(fill='both')

    def __call__(self):
        """
        parent page reference
        """
        return self.page

    def add_page(self, pg, title):
        """
        add a new page to the notebook
        """
        rb = tk.Radiobutton(self.tab, text=title, indicatoron=0, variable=self.selected,
            value=self.count, command=lambda: self.display_page(pg))
        rb.pack(fill='both', side=self.side)
        # first page is slected by default
        if not self.active_page:
            pg.pack(fill='both', expand=True)
            self.active_page = pg
        self.count += 1
        # returns reference
        return rb

    def display_page(self, pg):
        """
        shows selected page, hides former page
        """
        self.active_page.forget()
        pg.pack(fill='both', expand=True)
        self.active_page = pg


# testing the module
if __name__ == '__main__':
    root = tk.Tk()
    # use width x height + x_offset + y_offset (no spaces!)
    root.geometry("400x200+100+50")
    root.title('Testing a Tkinter notebook widget')

    nb = Notebook(root)

    # create first page (notice the instance call)
    page1 = tk.Frame(nb())
    nb.add_page(page1, 'page 1')
    # put something on the page
    # text entry field, width=width in chars, height=lines text
    text1 = tk.Text(page1, width=60, height=12, bg='yellow')
    text1.pack(fill='both')
    text1.insert(tk.INSERT, ' this is page number 1')

    # create second page, also has a button
    page2 = tk.Frame(nb())
    nb.add_page(page2, 'page 2')
    # put something on the page …
Ene Uran 638 Posting Virtuoso

Not quite sure what you want, but maybe function zip() will help:

buy_list = [1,2,3,4,9,11,77,99]
sell_list = [0,7,8,10,12,15]

# removes the excess items of the longer list
buy_sell = zip(buy_list, sell_list)

print buy_sell

for buy, sell in buy_sell:
    print buy, sell

"""
my display -->
[(1, 0), (2, 7), (3, 8), (4, 10), (9, 12), (11, 15)]
1 0
2 7
3 8
4 10
9 12
11 15

"""
Ene Uran 638 Posting Virtuoso

Your problem is too simple to bother with regex:

mylist = ['adam', 'bill', 'jon/juan']

newlist = [item.replace('/', '') for item in mylist]

print(mylist)   # ['adam', 'bill', 'jon/juan']
print(newlist)  # ['adam', 'bill', 'jonjuan']
Ene Uran 638 Posting Virtuoso

I you are on Windows and have several versions of Python installed, you can write a little batch file to make sure the IDLE of the correct version is runnig:

REM a batch file to force IDLE to use Pyhon30
REM saved as IDLE30.bat
C:\Python30\pythonw.exe -u C:\Python30\Lib\idlelib\idle.pyw

The poor quality keyboard on my HP notbook coputer is givig me the fits!

Ene Uran 638 Posting Virtuoso

Maybe something like this:

import random

low = 1
high = 9

mylist = [(random.randint(low, high), ) for k in range(10)]

print(mylist)

"""
a possible display of one element tuples -->
[(9,), (5,), (6,), (2,), (8,), (3,), (4,), (2,), (6,), (1,)]
"""
Ene Uran 638 Posting Virtuoso

I wonder if they ever got all that salmonella contaminated peanut butter off the shelves?

Ene Uran 638 Posting Virtuoso

Half of all North Americans live within 50 miles of their birthplace.

Ene Uran 638 Posting Virtuoso

Sushi and green tea

Ene Uran 638 Posting Virtuoso

The only reason many people get lost in thought is because it's unfamiliar territory."
-- Paul Dontee

Ene Uran 638 Posting Virtuoso

PyQT has an interesting widget called a dial (circular slider). Here is a simple applcation:

# use a PyQT QDial knob to select a temperature
# show Celsius and corresponding Fahrenheit values
# as the knob is rotated
# tested with PyQT4.5 and Python3.0
# ene

import sys
# has minimal namespace conflicts
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyFrame(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(150, 150, 328, 440)
        self.setWindowTitle('Convert Temperature')
        
        self.dial = QDial(self)
        self.dial.setGeometry(QRect(10, 20, 311, 351))
        self.dial.setMinimum(-50)
        self.dial.setMaximum(310)
        self.dial.setPageStep(10)
        # initial dial pointer position
        dial_pos = 50
        self.dial.setSliderPosition(dial_pos)
        self.dial.setWrapping(True)
        self.dial.setNotchTarget(3.6)
        self.dial.setNotchesVisible(True)

        self.label_c = QLabel(self)
        self.label_c.setGeometry(QRect(30, 390, 121, 31))
        font = QFont()
        font.setPointSize(11)
        self.label_c.setFont(font)
        self.label_c.setAlignment(Qt.AlignCenter)

        self.label_f = QLabel(self)
        self.label_f.setGeometry(QRect(170, 390, 131, 31))
        font = QFont()
        font.setPointSize(11)
        self.label_f.setFont(font)
        self.label_f.setAlignment(Qt.AlignCenter)
        
        # start up
        self.show_temps()
        # update show_temps()
        self.connect(self.dial, SIGNAL("sliderMoved(int)"),
            self.show_temps)

    def show_temps(self):
        """
        get the C value from the dial label
        calculate F value and show
        """ 
        c = float(self.dial.value())
        s_c = "%0.1f Celsius" % c
        self.label_c.setText(s_c)
        f = c*9/5.0 + 32
        s_f = "%0.1f Fahrenheit" % f
        self.label_f.setText(s_f)
        

app = QApplication(sys.argv)
frame = MyFrame()
frame.show()
sys.exit(app.exec_())

Sorry, I am having real problems with my HP notebook, the keyboard is of very poor quality and misses keystrokes a lot!

Ene Uran 638 Posting Virtuoso

Those who know how to win are more numerous than those who know how to make proper use of their victories.
--- Polybius

Ene Uran 638 Posting Virtuoso

Draw a simple bar chart with PyQT:

# use PyQT to draw a simple vertical bar chart
# tested with PyQT4.5 and Python3.0
# ene

import sys
# simplified import, hopefully no namespace conflicts
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class BarChart(QWidget):
    def __init__(self, data, parent=None):
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(300, 300, 360, 320)
        self.setWindowTitle('A Simple Bar Chart')
        self.data = data

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        
        # set color and width of line drawing pen
        painter.setPen(QPen(Qt.black, 2))
        
        # drawLine(x1, y1, x2, y2) from point (x1,y1) to (x2,y2)
        # draw the baseline
        painter.drawLine(20, 280, 340, 280)        

        # set up color and width of the bars
        width = 20
        painter.setPen(QPen(Qt.red, width))
        delta = width + 5
        x = 30
        for y in self.data:
            # correct for width
            y1 = 280 - width/2
            y2 = y1 - y + width/2
            # draw each bar
            painter.drawLine(x, y1, x, y2)
            # add values to the top of each bar
            s = str(y)
            painter.drawText(x-8, y2-15, s)
            x += delta        

        painter.end()


# data to be graphed
data = [30, 45, 80, 150, 220, 180, 110, 75, 50, 35, 20, 10]
app = QApplication(sys.argv)
bc = BarChart(data)
bc.show()
app.exec_()
Ene Uran 638 Posting Virtuoso

The latest Python version has added some candy:

# Python3.1 allows formatting of thousands
# and defaults format indexing in print()
# ene

n = 123456789
print(format(n, ',d'))

"""
my display -->
123,456,789
"""

m = 1234567.8912
print(format(m, ',.2f'))

"""
my display -->
1,234,567.89
"""

amount = format(1234567, ',d')
price = format(1234.56, ',.2f')
# note that {} defaults to the proper arg index
print('{} bottles at ${} each'.format(amount, price))

"""
my display -->
1,234,567 bottles at $1,234.56 each
"""

I have Python25, Python26, Python30, and Python31 installed on my homely Vista computer. To easily select which Python version to use I like the IDE Editra (wxPython based) and its Launch plugin.

Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

I think we may have talked about this before, but I can't find it. Here is a way to use a sound file inside the Python code and play it. First create a base64 encoded string of the binary sound file:

# create a base64 encoded string from binary sound data
# and limit the length of each data line to n characters
# ene

import base64

def text_lines(data, n):
    """
    write a long one line text as lines of n char each
    """
    s = ""
    for ix, c in enumerate(data):
        if ix % n == 0 and ix != 0:
            s += c + '\n'
        else:
            s += c
    return s

# pick a wave file that is in the working folder
wave_file = "pop.wav"
# this is a binary read
data = base64.b64encode(open(wave_file, 'rb').read())
data = text_lines(data, 70)
print "wav_base64='''\\\n" + data + "'''"

"""
highlight and copy the resulting base64 wav string to embed in program
code, use wav = base64.b64decode(wav_base64) to decode to binary data:

wav_base64='''\
UklGRuABAABXQVZFZm10IBAAAAABAAEAESsAABErAAABAAgAZGF0YbsBAACAgICAgICAgIC
AgICAfX12aVtQS0hJSk5TZpWyv8LBwMC/vry2nWxLPTs9PT5AR05pn77BwcC/vruxlGtJP
T09PkBHU3qrv8DAv7+7tKiGWUA8PT4+Qk1tm7fAv7++ubKmhl1CPD0+P0NPbZayv8C/vbe
vooNdRD0+PkBIWXWVrru/vbmypo5uU0I+P0NLWG6JorO7vLm0rJyBZlBEQkNIUF5xiJ2wu
bq4s6qZg21ZTUhITFRhcoaaqLGzsayilIFvYFVQUFNZY29/j52orKunnpKFdmheWFVWWmF
seYiXoqmrqaKXi390amRfXmBka3aDj5ifoqGemZGIfXJpY2FiZmx0fYePlpqcmpSNhHpyb
Wloam91foaNk5eXlZGMhH12b2xqam1xd32Ei5CVlpSPiYF6dHFvbnByd36Fi4+SkY6KhoN
+end3d3h8gYaKjIyMioeDf3t4dnZ3eX2BhYiKi4uJhoJ+eXZ1dnd6fICFiY2PjoyHgnx3d
XNzdHZ6f4WKjpCPjIiEf3t3dHNzdXh8goeLjY2NiYWBfHh0cnJzdnl9gYSGh4aFg398eXd
2d3l8foCChIaIh4aEgQA='''

"""

Now you can transfer the result to your Python program and play the sound without having to attach the sound file:

# playing a base64 encoded wave sound string with wxPython's
# wx.SoundFromData(sound_data) and sound.Play()
# ene

import wx
import base64

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize, sound_data):
        wx.Frame.__init__(self, parent, -1, mytitle, size=mysize)
        self.SetBackgroundColour("blue")
        # use a small delay to display the frame before sound …
Nick Evan commented: Random rep for effort put in 'beginner' threads :) +18
sneekula commented: wonderful +8
Ene Uran 638 Posting Virtuoso

For those of you who like to calculate in fractions:

# Python30 has a module fraction that allows you to
# calculate with fractions, the result is a fraction
# is more precise than using floating point numbers
# ene

from fractions import Fraction

# Fraction(numerator, denominator)
# for instance fraction 2/3 would be Fraction(2, 3)
a = Fraction(2, 3)
b = Fraction(2, 5)
c = Fraction(3, 7)

print( "%s + %s = %s" % (a, b, a + b) )
print( "%s + %s + %s = %s" % (a, b, c, a + b + c) )
print( "(%s + %s)/(%s) = %s" % (a, b, c, (a + b)/c) )

"""
my display -->
2/3 + 2/5 = 16/15
2/3 + 2/5 + 3/7 = 157/105
(2/3 + 2/5)/(3/7) = 112/45
"""
Ene Uran 638 Posting Virtuoso

Python 2.5.4 is the version I have installed. Python 2.6 has all sorts of problems at least on Windows, since it is compiled with a different MS C compiler. A good number of modules are simply not available for Python 2.6. Python 2.6 is supposed to help you to transition better to the new Python3. I think that is questionable.

Ene Uran 638 Posting Virtuoso

In order to make buttons behave like standard buttons in your dialog box, you simply create an image button from a standard button and an image:

class BitmapDialog(wx.Dialog):
    def __init__(self, text):
        wx.Dialog.__init__(self, None, -1, title="BitmapDialog", 
            size=(250,150))
        
        bmp = wx.Bitmap('ok.png')
        w, h = bmp.GetSize()
        x = 35
        y = 90
        wx.StaticBitmap(self, -1, bmp,
            pos=(x, y))
        okButton = wx.Button(self, wx.ID_OK, ' OK ', 
            pos=(x+w, y), size=(w*2, h))
        okButton.SetDefault()

        bmp = wx.Bitmap('cancel.png')
        w, h = bmp.GetSize()
        x = 135
        y = 90
        wx.StaticBitmap(self, -1, bmp,
            pos=(x, y))
        cancelButton = wx.Button(self, wx.ID_CANCEL, ' Cancel ', 
            pos=(x+w, y), size=(w*2, h))

Actually, the way these buttons respond to keystrokes depends on the OS.

Ene Uran 638 Posting Virtuoso

What are old C/C++ programmers supposed to do then ? :(

Get involved in politics, that takes little brain power.

Ene Uran 638 Posting Virtuoso

The Bearded Person Contest was held in Alaska this year and was won by an American for the first time!
No, it was not Miss Alaska!