sneekula 969 Nearly a Posting Maven

The third-rate mind is only happy when it is thinking with the majority.
The second-rate mind is only happy when it is thinking with the minority.
The first-rate mind is only happy when it is thinking.
~~~ A. A. Milne

sneekula 969 Nearly a Posting Maven

Q: "How do you keep a moron in suspense?"
A: "Take a blank card and write "Turn over!" on both sides."

sneekula 969 Nearly a Posting Maven

The function exec() does not know where class Vent is coming from.
You could try something like:
exec(mystring, globals())

Now you are putzing around with the global dictionary, dangerous territory indeed!

sneekula 969 Nearly a Posting Maven

You could maintain a list of open file handles like this:

open_files = []
for each_name in names_list:
    open_files.append(open(each_name + '.bed', 'w'))

Then that list would be full of open file handles.

A nice feature of this approach is that the index of the file handle in open_files is the same as the index of the name in the names_list.

Note to shoemoodoshaloo: please do not use tabs for indentation!

sneekula 969 Nearly a Posting Maven

All animals are equal, but some are tastier.

vmanes commented: Orwell is turning in his grave, or laughing his a## off! +9
sneekula 969 Nearly a Posting Maven

A pecan danish with hot java.

sneekula 969 Nearly a Posting Maven

Experience is a hard teacher, because the test is given first, the lesson afterwards.
~~~ Vernon Lawson

sneekula 969 Nearly a Posting Maven

So, what are your errors?

sneekula 969 Nearly a Posting Maven

Just in case you don't fine wxGlade or BoaConstructor to be quite what you need (or if you just can't get past how ugly they are), you can try QtDesigner for pyQT (comes with the pyQT package).

Beauty and henceforth ugly is in the eye of the beholder!

Actually, the QT_Designer is pretty good and gives XML code that can be converted to a seemingly complex looking Python code.

scru commented: not seemingly, it is complex. But people who use gui builders generally don't care about this sort of stuff. +6
sneekula 969 Nearly a Posting Maven

If you just want to replace certain extensions, you can use something like this:

file_list = [
'list_nonunique1.py',
'Gene_read1.pyw',
'wx_psutil1.pyw',
'pa16names.txt',
'wxFrame_centerthings1.pyw',
'averagewords1.py',
'oneline.txt',
'tk_coinflip.pyw']

# replace extension .pyw with .py
new_list= []
for fname in file_list:
    if '.pyw' in fname:
        fname = fname[:-3] + 'py'
    new_list.append(fname)
    print(fname)

"""
my result -->
list_nonunique1.py
Gene_read1.py
wx_psutil1.py
pa16names.txt
wxFrame_centerthings1.py
averagewords1.py
oneline.txt
tk_coinflip.py
"""
sneekula 969 Nearly a Posting Maven

Also take a look at:
http://www.daniweb.com/forums/post892908-193.html

Module BeautifulSoup was not used in this example, but might help to pretty up the code before splitting it.

sneekula 969 Nearly a Posting Maven

I did some detective work to find the stock trading value for a given ticker symbol. See if you can use the fruits of my labor and turn this into a more general portfolio tracker:

# find the stock trading value for a given ticker symbol
# tested with Python25

import urllib2

def extract(text, sub1, sub2):
    """
    extract a substring from text between first
    occurances of substrings sub1 and sub2
    """
    return text.split(sub1, 1)[-1].split(sub2, 1)[0]


ticker = 'GE'
url = 'http://finance.yahoo.com/q?s='+ticker
fh = urllib2.urlopen(url)
ticker_html = fh.read()

#print(ticker_html)

for line in ticker_html.split('><'):
    if 'id="yfs_' in line:
        print(line)

print('-'*70)

# narrow it down
for line in ticker_html.split('><'):
    if 'id="yfs_l' in line:
        print(line)

print('-'*70)

# narrow it down even more
for line in ticker_html.split('><'):
    if 'id="yfs_l10_' in line:
        print(line)
        print(extract(line, '>', '<'))
        break
sneekula 969 Nearly a Posting Maven

I can see one problem,
tickerhtml=urllib2.urlopen(ticker)
needs to be:
tickerhtml=urllib2.urlopen(ticker).read()

sneekula 969 Nearly a Posting Maven

wtf?

where is Lynx?

What is Lynx?

sneekula 969 Nearly a Posting Maven

Statistics are like bikinis. What they reveal is suggestive, but what they conceal is vital.
-- Frank Barkow

sneekula 969 Nearly a Posting Maven

Come play with me!

sneekula 969 Nearly a Posting Maven

Some cause happiness wherever they go; others, whenever they go.
-- Oscar Wilde

sneekula 969 Nearly a Posting Maven

Also look into (wxPython is used by Boa and wxGlade):
Starting wxPython (GUI code)
http://www.daniweb.com/forums/thread128350.html

and:
Python GUI Programming
http://www.daniweb.com/forums/thread191210.html

Some words of advice, GUI programming will be a steep learning curve. You have to rethink your approach to use the best GUI widget/component to do what you want. For instance, most GUI toolkits will give a large number of input (text entry, sliders, check boxes, radio buttons, list boxes ...) and output (labels, sound, image, canvas, plotters, spreadsheet ...) devices. A GUI Builder will only position the selected widget on a window/frame, you still have to write the code to make it do something.

I look at this way, console programs are for learning Python, GUI programs are for showing what you have learned. Learn Python coding real well, then apply it to a GUI!

sneekula 969 Nearly a Posting Maven

Here is an example using the module pygame:

# experiments with module pygame
# free from: http://www.pygame.org/
# load, display and move an image

import pygame as pg

# initialize pygame
pg.init()

# pick an image you have (.bmp  .jpg  .png  .gif)
# if the image file is not in the working folder,
# use the full pathname like "C:/Images/gifs/Pooh.gif"
image_file = "Pooh.gif"

# RGB color tuple used by pygame
white = (255, 255, 255)

# create a 300x300 white screen
screen = pg.display.set_mode((300,300))
screen.fill(white)

# load the image from a file
# convert() unifies the pixel format for faster blit
image = pg.image.load(image_file).convert()

# draw image, position the image ulc at x=50, y=20
screen.blit(image, (50, 20))

# get the rectangle the image occupies
# rec(x, y, w, h)
start_rect = image.get_rect()

# set up the timed event loop
x = 0
y = 0
clock = pg.time.Clock()
keepGoing = True
while keepGoing:
    # set rate of move
    clock.tick(30)
    for event in pg.event.get():
        # quit when user clicks on window x
        if event.type == pg.QUIT:
            keepGoing = False
    # move the image ...
    x += 1
    y += 1
    # stop when x exceeds limit
    if x > 270:
        keepGoing = False
    image_rect = start_rect.move(x, y)
    # this erases the old sreen with white
    screen.fill(white)
    # put the image on the screen at new location
    screen.blit(image, image_rect)
    # update screen
    pg.display.flip()
sneekula 969 Nearly a Posting Maven

There are a number of GUI drag and drop builders.
Boa Constructor:
http://www.daniweb.com/forums/post400296-107.html
wxGlade:
http://www.daniweb.com/forums/post400189-106.html

sneekula 969 Nearly a Posting Maven

Runtime versions (in your case msvcr90.dll) of the Microsoft C compiler have to be shipped with any program that has been compiled with it. Since Python26.dll has been compiled with this version, the appropriate runtime version can be included without problems. In the matter of fact, your Python 2.6 Windows binary distribution had to include it to work on your machine.

sneekula 969 Nearly a Posting Maven

i,ROBOT
Will Smith fights a robot conspiracy to break the "a robot can't harm a human" union rules.

sneekula 969 Nearly a Posting Maven

Python is not using 100% CPU time, your program is. Without some code it will be hard to help.

sneekula 969 Nearly a Posting Maven

A sample of your code would help.

sneekula 969 Nearly a Posting Maven

Clear clears the canvas not the panel. Your listbox is on the panel and not the canvas.

If you want to clear the listbox, use self.process_list.Clear()

sneekula 969 Nearly a Posting Maven

The { and } keys.

sneekula 969 Nearly a Posting Maven

This demonstrates a little function to extract the numeric value from a string like "$12.34/pound" where you want just 12.34 to do calculations:

# extract the numeric value from a data string
# snee

def extract_number(data_str):
    """
    extract the numeric value from a string
    the string should contain only one number
    return the number as int, float or None
    """
    s = ""
    for c in data_str:
        if c in '1234567890.-':
            s += c
    if s:
        # convert number to int or float
        return eval(s)
    else:
        return None


data_raw = """
header
23 bushels
 43 years old
4323 Maiden Lane
-$23.44/kg
 +$12.32
footer
"""

# create a list of the string data
data_list = data_raw.split('\n')
print(data_list)  # test

print('-'*60)

# extract numeric values from the data in the list
for data_str in data_list:
    print(extract_number(data_str))

"""
my result -->
['', 'header', '23 bushels', ' 43 years old', '4323 Maiden Lane',
'-$23.44/kg', ' +$12.32', 'footer', '']
------------------------------------------------------------
None
None
23
43
4323
-23.44
12.32
None
None
"""
sneekula 969 Nearly a Posting Maven

I simply added the question number to the key's correct answer letter to make it unique. Also prettied the dictionary a little and gave the short version. Here is an example:

#!/usr/bin/python

# a biology quiz using a dictionary
# some improvements would be:
# count total correct answers
# maybe reloop wrong answers


# key "a1" is a composite of correct answer letter + question number
# this makes the key unique
words = {
"a1":
"""The placing of sperm cells in the oviducts of the females is called
a. internal fertilization
b. milting
c. spawning
d. moting
e. external fertilization
f. tremendously invigorating""",
"c2":
"""The brain region which controls the coordinates muscular activity
a. medulla oblongata
b. cerebrum
c. cerebellum
d. optic lobe
e. brain stem""",
"c3":
"""The brain region which attaches brain to spinal column and controls
internal organs
a. cerebellum
b. cerebrum
c. medulla oblongata
d. hypothalamus""",
"c4":
"""The sac that stores the fluid cellular wastes of the body
a. gall bladder
b. medulla oblongata
c. urinary bladder
d. villi
e. mesentary""",
"f5":
"""The muscle that divides the abdominal and thoracic cavities in
mammals is the
a. rugae
b. tricep
c. bicep
d. caecum
e. peritenium
f. diaphragm"""
}


for key, val in words.items():
    print val
    print '-'*30
    choice = raw_input("Enter your choice letter: ").lower()
    if choice[0] in key:
        print "correct"
    else:
        print "wrong, the correct answer is %s" % key[0]
    print '-'*30
sneekula 969 Nearly a Posting Maven

A yummy grilled cheese sandwich with chilled pomegranate juice.

sneekula 969 Nearly a Posting Maven

There would not be any carbon-based life - maybe it would be silica-based.

Wow, imagine the silicon units are breathing out silicon dioxide (sand)!

sneekula 969 Nearly a Posting Maven

Even evolution had to start with something, let's call it creation.

sneekula 969 Nearly a Posting Maven

I have chosen both and it worked fine.

sneekula 969 Nearly a Posting Maven

I heard there is empty space inside nucleus
of atoms , I guess there will many such example of empty spaces.

What keeps this space from collapsing? There must be something there!

sneekula 969 Nearly a Posting Maven

You can use Google Groups to check your favorite newsgroup:
http://groups.google.com/group/alt.models.railroad.ho/topics?lnk=srg

sneekula 969 Nearly a Posting Maven

Hey, don't be sorry, it's a great approach to a quiz. Now you found out that dictionary keys have to be unique. So, what did you do to correct this?

sneekula 969 Nearly a Posting Maven

You might be thinking about something like this:

# a wxPython frame full display-screen size
# position widgets in the center

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, -1, mytitle, size=mysize)
        # the panel is needed for proper positioning
        panel = wx.Panel(self)
        panel.SetBackgroundColour("green")
        w, h = mysize
        
        self.mychoices = ['image1', 'image2', 'image3', 'image4']

        # create a box with 4 radio buttons, no labels here
        label_choices = [' ', ' ', ' ', ' ']
        self.radiobox = wx.RadioBox(panel, -1,
            " click on a button ",
            choices=label_choices,
            style=wx.VERTICAL)
        # bind mouse click to an action
        self.radiobox.Bind(wx.EVT_RADIOBOX, self.onAction)
        # show first selection
        self.onAction(None)
        
        rbw, rbh = self.radiobox.GetSize()
        # put the radiobox in the center of the display area
        # assume title bar takes about 25 pixels
        self.radiobox.SetPosition(((w-rbw)/2, (h-rbh)/2 - 25))

    def onAction(self, event):
        """show the selected choice"""
        index = self.radiobox.GetSelection()
        s = "Selected " + self.mychoices[index]
        # show the result in the frame title
        self.SetTitle(s)


app = wx.App(0)
# create a MyFrame instance and show the frame
mytitle = 'my title'
# make the frame full display-screen size and show
MyFrame(None, mytitle, wx.DisplaySize()).Show()
app.MainLoop()

In this case you need to calculate the center position for every widget you want to bring up. Easily done.

sneekula 969 Nearly a Posting Maven

Looks like you could simplify your code a little:

data = """\
<SYNC Start=5047><P Class=ENCC>
Back, back, back, back!
<SYNC Start=7235><P Class=ENCC>&nbsp;
<SYNC Start=10725><P Class=ENCC>
Yeah, Dan!"""

# this would be like the file data
lines = data.split('\n')

new_data = ""
for line in lines:
    if not line.startswith('<'):
        new_data += line + '\n'

# test it
print(new_data)

"""
my output -->
Back, back, back, back!
Yeah, Dan!
"""
sneekula 969 Nearly a Posting Maven

The Bible is full of rules to live by, not secret code!

If someone claims to have discovered secret code, then it is only to pull ignorant folks nose for financial gain or influence peddling.

Salem commented: I thought that's what religion was all about - separating the gullible from their money :) +32
sneekula 969 Nearly a Posting Maven

I guess you can play around with lists and lists of lists.

For example:

# create a 2D matrix of zeros and populate it

def make_list(size):
    """create a list of size number of zeros"""
    mylist = []
    for i in range(size):
        mylist.append(0)
    return mylist

def make_matrix(rows, cols):
    """
    create a 2D matrix as a list of rows number of lists
    where the lists are cols in size
    resulting matrix contains zeros
    """
    matrix = []
    for i in range(rows):
        matrix.append(make_list(cols))
    return matrix

mx = make_matrix(3, 3)

print(mx)

print('-'*34)

# now populate the zero matrix
# for instance put a 5 in row 0, column 0
mx[0][0] = 5
# put a 7 in row 1, column 1
mx[1][1] = 7
# put a 9 in row 2, column 2
mx[2][2] = 9

print(mx)

"""
my result -->
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
----------------------------------
[[5, 0, 0], [0, 7, 0], [0, 0, 9]]
"""

Another example:

# create a 2D matrix of zeros and populate it

def make_list(size):
    """create a list of size number of zeros"""
    mylist = []
    for i in range(size):
        mylist.append(0)
    return mylist

def make_matrix(rows, cols):
    """
    create a 2D matrix as a list of rows number of lists
    where the lists are cols in size
    resulting matrix contains zeros
    """
    matrix = []
    for i in range(rows):
        matrix.append(make_list(cols))
    return matrix

rows = 5
cols = 5
mx = make_matrix(rows, cols)

# pretty show the matrix
for x in mx:
    print(x) …
sneekula 969 Nearly a Posting Maven

woooee, you only missed this:
ararik pulled up an old thread to attach a homework question.

I already told him not to double post.

sneekula 969 Nearly a Posting Maven

ararik, please do not double post!

You are almost there, as slate says, simply sum up word counts and word lenghts:

myfile = open(filename, "r")
wordcount_sum = 0
wordlength_sum = 0
for line in myfile:
    words = line.split()
    # sum up the word counts
    wordcount_sum += len(words)
    for word in words:
        # sum up the word lengths
        wordlength_sum += len(word)

# invoke floating point division for Python versions < 3.0
wordlength_average = wordlength_sum/float(wordcount_sum)
sneekula 969 Nearly a Posting Maven

use mouseover or mousefocus at X,Y

We are talking about the Tkinter GUI toolkit. There are no such methods.

widget.focus() puts the cursor to a widget

module turtle (uses tkinter) has a method goto(x,y)

sneekula 969 Nearly a Posting Maven

A good old American standard:
Kraft Macaroni and Cheese

sneekula 969 Nearly a Posting Maven

Just in the news:

ATLANTA – Scientists have identified a lethal new virus in Africa that causes bleeding like the dreaded Ebola virus. The so-called "Lujo" virus infected five people in Zambia and South Africa last fall. Four of them died.

It's not clear how the first person became infected, but the bug comes from a family of viruses found in rodents, said Dr. Ian Lipkin, a Columbia University epidemiologist involved in the discovery.

"This one is really, really aggressive" he said of the virus.

sneekula 969 Nearly a Posting Maven

Try something like this:

try:
    lightblue.obex.sendfile(device.getAddr(), c[1],"advertisement.jpg")
except lightblue._obexcommon.OBEXError, error:
    if error.args[0] == 111:
        print "Connection refused!"
    elif error.args[0] == 11:
        print "Resource temporarily unavailable!"
    else:
        pass
sneekula 969 Nearly a Posting Maven

Look into Python modules audioop and sunaudiodev
Sun's .au audio file format is rather simple and flexible. Here is an example that vegaseat left some time ago, it shows you how to create an .au files from scratch:

# create a soundfile in AU format playing a sine wave
# of a given frequency, duration and volume
# tested with Python25   by vegaseat     29jan2008

from struct import pack
from math import sin, pi

def au_file(name='test.au', freq=440, dur=1000, vol=0.5):
    """
    creates an AU format audio file of a sine wave
    of frequency freq (Hz)
    for duration dur (milliseconds)
    at volume vol (max is 1.0)
    """
    fout = open(name, 'wb')
    # header needs size, encoding=2, sampling_rate=8000, channel=1
    fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))
    factor = 2 * pi * freq/8000
    # write data
    for seg in range(8 * dur):
        # sine wave calculations
        sin_seg = sin(seg * factor)
        fout.write(pack('b', vol * 127 * sin_seg))
    fout.close()

# test the module ...
if __name__ == '__main__':
    au_file(name='sound800.au', freq=800, dur=2000, vol=0.8)
    
    # if you have Windows, you can test the audio file
    # otherwise comment this code out
    import os
    os.startfile('sound800.au')

I think the webbrowser module allows you to play .au files too.

sneekula 969 Nearly a Posting Maven

You can use string slicing if you assume a few things:

#!/usr/bin/env python

# has
old = "AND Category 07|Spec 01|ABC 01 AND Category 07|Spec 02|XYZ 02 \
AND Category 07|Spec 03|PQR 03 "
# wants
new = "AND Category 07|Spec 01 AND Category 07|Spec 02 AND Category 07|Spec 03"

# assuming that 'Spec xx' and what you want to remove does not change in length

q = old.split('|S')

for x in q:
    print(x)  # test

print('-'*30)


new2 = ""
for x in q:
    if x.startswith('pec'):
        # skips the chars from index 6 to 12
        x = '|S' + x[:6] + x[13:]
        print(x)  # test
    new2 += x

print('-'*30)

print(new2)

"""
my result -->
AND Category 07
pec 01|ABC 01 AND Category 07
pec 02|XYZ 02 AND Category 07
pec 03|PQR 03
------------------------------
|Spec 01 AND Category 07
|Spec 02 AND Category 07
|Spec 03
------------------------------
AND Category 07|Spec 01 AND Category 07|Spec 02 AND Category 07|Spec 03
"""
sneekula 969 Nearly a Posting Maven

A man is smoking a cigarette and blowing smoke rings into the air. His girlfriend becomes irritated with the smoke and says, “Can’t you see the warning on the cigarette pack? Smoking is hazardous to your health!”

To which the man replies, “I am a programmer. We don’t worry about warnings; we only worry about errors.”

kvprajapati commented: Great! +3
sneekula 969 Nearly a Posting Maven

My neighbor was kind enough to look the other way, as I picked a bunch of flowers out of her garden to bring to mom.

sneekula 969 Nearly a Posting Maven

Today it's Santa Fe rice and beans with spicy jalapeño sauce and cheese topping. Goes down easy with xxx beer.