bumsfeld 413 Nearly a Posting Virtuoso

Once more, please put your code into code tags to show the right indentation, see:
http://www.daniweb.com/techtalkforums/announcement114-3.html

Most people will not read any of your code unless you do that!

Your first program worked just fine, why did you change it?

This program will give you error, because you are giving it negative windspeeds! Use more meaningful variable names, t and v rather than x and y and you discover your mistakes!

Also newline is \n

bumsfeld 413 Nearly a Posting Virtuoso

wxPython has Printer Framework that allows you to do print whatever you put on a canvas. This can be colored text of any font. However, you got to get familiar with wxPython GUI. Look at wx.Printout(), wx.PrintData() and wx.PrintPreview()

bumsfeld 413 Nearly a Posting Virtuoso

Python lambda can substitute, just harder to read:

tuple1 = ('\t', '\n')
for k in range(100):
    a = (k % 10 == 9)
    b = 1
    c = 0
    # similar to C conditional expression a ? b : c
    # if a is true return b else c
    f = lambda a, b, c: (a and [b] or [c])[0]
    print "%3d%s" % (k, tuple1[f(a, b, c)]),
bumsfeld 413 Nearly a Posting Virtuoso

Which code snippet are you talking about?

bumsfeld 413 Nearly a Posting Virtuoso

Since your discount is calculated from the total purchase, you do not need to ask for it.
Discount calculations are done using conditional if statements.

Do not use % as a variable name!

All calculations are simple, no need for "from math import *"

bumsfeld 413 Nearly a Posting Virtuoso

Found code in one of the books in the CS library:

# view and delete e-mail using the POP3 protocol

import sys, getpass, poplib, re

# change according to your needs
POPHOST = "pop.domain.com"
POPUSER = "joedoe"
POPPASS = ""
# the number of message body lines to retrieve
MAXLINES = 10
HEADERS = "From To Subject".split()

# headers you're actually interested in
rx_headers  = re.compile('|'.join(headers), re.IGNORECASE)

try:
    # connect to POP3 and identify user
    pop = poplib.POP3(POPHOST)
    pop.user(POPUSER)

    if not POPPASS or POPPASS=='=':
        # if no password was supplied, ask for it
        POPPASS = getpass.getpass("Password for %s@%s:" % (POPUSER, POPHOST))

    # authenticate user
    pop.pass_(POPPASS)

    # get general information (msg_count, box_size)
    stat = pop.stat(  )

    # print some information
    print "Logged in as %s@%s" % (POPUSER, POPHOST)
    print "Status: %d message(s), %d bytes" % stat

    bye = 0
    count_del = 0
    for n in range(stat[0]):

        msgnum = n+1

        # retrieve headers
        response, lines, bytes = pop.top(msgnum, MAXLINES)

        # print message info and headers you're interested in
        print "Message %d (%d bytes)" % (msgnum, bytes)
        print "-" * 30
        print "\n".join(filter(rx_headers.match, lines))
        print "-" * 30

        # input loop
        while 1:
            k = raw_input("(d=delete, s=skip, v=view, q=quit) What?")
            k = k[:1].lower(  )
            if k == 'd':
                # Mark message for deletion
                k = raw_input("Delete message %d? (y/n)" % msgnum)
                if k in "yY":
                    pop.dele(msgnum)
                    print "Message %d marked for deletion" % msgnum
                    count_del += 1
                    break
            elif k == 's':
                print "Message %d left on server" % msgnum
                break
            elif …
bumsfeld 413 Nearly a Posting Virtuoso

G-Do,
you and vegaseat seem to share fascination with midi music files. I have explored vegaseat's code snippet
http://www.daniweb.com/code/snippet431.html
and it work well at least on Windows XP. Midi is great stuff!

I am thinking that pythonmidi is the same package as PMIDI, at least the files/directories are the same.

bumsfeld 413 Nearly a Posting Virtuoso

So the trick is to make size of ring buffer large enough to retain all pertinent data long enough?
I guess the answer is yes.

bumsfeld 413 Nearly a Posting Virtuoso

G-Do, I am buffled as much as you.
Does by reference mean that code (originally code=[]) keeps the same memory address, even as it increases?

bumsfeld 413 Nearly a Posting Virtuoso

I and some of my friends left project ideas on
http://www.daniweb.com/techtalkforums/thread32007.html

They can appply to any computer language!

bumsfeld 413 Nearly a Posting Virtuoso

Wow G-Do, your code works great!

I have to think that through to understand it.

bumsfeld 413 Nearly a Posting Virtuoso

I need to know how many times my function has been accessed in my program. Any suggestions other than global variable?

bumsfeld 413 Nearly a Posting Virtuoso

Is there a way to limit size of a list in Python, so it does not use all memory?

bumsfeld 413 Nearly a Posting Virtuoso

Please wrap you code in code tags, see:
http://www.daniweb.com/techtalkforums/announcement114-3.html

This way the proper indentations are added.

I would not pass function on as argument, so rewrite you code:

from math import *  # to get pi

def main():
    # first get the area of the whole pizza
    area = area_of_pizza()    
    cost_per_square_inch(area)

def area_of_pizza():
    diameter = input("Enter the diameter of the pizza: ")
    radius = diameter/2.0
    a = pi * radius * radius
    return a

def cost_per_square_inch(area):
    # get the cost of the whole pizza
    cost_of_pizza = input("Enter the cost of the pizza: ")
    # calculate the cost per area unit
    cost = cost_of_pizza/area
    print "The cost per square inch of pizza is $%0.2f" % (cost)


main()

Since you only need math.pi you don't have to import all math functions/constants. You could use:

from math import pi
bumsfeld 413 Nearly a Posting Virtuoso

This small program is neat:

import calendar

calendar.prmonth(2006, 3)

"""
     March 2006
Mo Tu We Th Fr Sa Su
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
"""

Is there way to trap output in a string so it can be used in GUI like Tkinter?

bumsfeld 413 Nearly a Posting Virtuoso

There is no module called graphics in normal Python distribution! Without this custom module will be hard to help!

I suggest you print p1 and see what it looks like!
If it is tuple like (30, 45), then most likely p1x = p1[0].

bumsfeld 413 Nearly a Posting Virtuoso

Google for freax and you find this entry:

October 5, 1991 - Freax is hacked by Ari Lemke, the admin of the FTP site where Linus made his code available. The directory is named /pub/OS/Linux. v0.02 is then made available

bumsfeld 413 Nearly a Posting Virtuoso

I would learn C++ to get used to an oops language. Java is simple lame version of C++ anyway!

bumsfeld 413 Nearly a Posting Virtuoso

I knew I was in trouble when doctor dentist took many pictures during surgery, so it would make it harder to sue him afterwards! I smile anyway, at least on Halloween!

bumsfeld 413 Nearly a Posting Virtuoso

I am here to use the Linux OS on my computer.

Was Linux really called Freax originally?

bumsfeld 413 Nearly a Posting Virtuoso

well, if I were a teacher having to grade that I'd fail it immediately anyway.
Ugliest mix of C and C++ I've ever seen, global variables, very bad variable naming, etc. etc.

Looks like our friend brahle uses cstdio rather than iostream because of the much smaller executable it produces. Maybe it is bad habit to mix C and C++, but then C++ is tolerant of C. I consider that one strength of C++ anytime. NULA (must be Croation for NULL) and return NULA is optional with C++ however.

bumsfeld 413 Nearly a Posting Virtuoso

If you exclude number 2, and start you for loop with 3, you need to check only odd numbers, increment you for loop by 2.

bumsfeld 413 Nearly a Posting Virtuoso

Sounds more like Ancient's wife has him broke in!

Happy coding!

bumsfeld 413 Nearly a Posting Virtuoso

Code sample shows how to run a program and specified file(s) from commandline.

# using commandline to run a program and files

def process_datafile(filename):
    """load specified data file and process data"""
    # code to read file data
    # code to process data and show or return result
    print "Test only, file =", filename   # testing

if __name__ == '__main__':
    import sys

    # run the progam from the commandline and specify the data file(s) to be loaded
    # something like   myProgram data1.dat data2.dat
    if len(sys.argv) > 1:
        # sys.argv is a list eg. ['C:/Python24/Atest/myProgram.py', 'data1.dat', 'data2.dat']
        # sys.argv[0] is program filename, slice it off with sys.argv[1:]
        # using for loop, more than one datafile can be processed
        for filename in sys.argv[1:]:
            process_datafile(filename)
    else:
        print "usage myProgram datafile1 [datafile2 ...]"
bumsfeld 413 Nearly a Posting Virtuoso

Here is simplified approach, the number of new-line characters '\n' give number of lines, the number of spaces are approximately the number of words, and the number of characters is the length of the text string read from file.

You simply use a for loop and and iterate each character in text counting new-lines, spaces. Don't have Unix and don't know if space counts as a character, also new-line. Can use char_from_text.isalnum() to weed these out.

You can also use, I didn't test, number_of_lines = text.count('\n') function.

A more correct answer for the number of words can be obtained by splitting the text string into list of words with word_list = text.split() and then get length of this list with number_words = len(word_list).

bumsfeld 413 Nearly a Posting Virtuoso

There is something like in a C code snippet here:
http://www.daniweb.com/code/snippet377.html

bumsfeld 413 Nearly a Posting Virtuoso

This was part of a game, I modified slightly the code. The code checks that input is correct and within a supplied range.

def checkInput(type_string, present_value, low, high):
    '''uses a while loop, loops until an acceptible answer is given, then returns it'''
    prompt = "Present %s is %d, enter a new value (%d-%d): " % (type_string, present_value, low, high)
    while True: 
       try:
          a = int(raw_input(prompt))
          if low <= a <= high:
             return a
       except ValueError:
          print "Enter an integer number, please!"


# modify the present strength of 10 within the range (1-18)
modified_strength = checkInput("strength", 10, 1, 18)
print modified_strength
bumsfeld 413 Nearly a Posting Virtuoso

This small code allow you to list your computer's environment, things like processor, os, user and so on:

# list the environmental settings of your computer

import os

keys = os.environ.keys()
keys.sort()
for item in keys:
    print "%-22s : %s" % (item, os.environ[item])

As a bonus another small code to find the IP address of your computer:

# Get the IP address of the machine this program is running on
# or go to http://www.whatismyip.com/

import socket

print socket.gethostname()
print socket.getaddrinfo(socket.gethostname(), None)
# get just the IP address from the list's tuple
print socket.getaddrinfo(socket.gethostname(), None)[0][4][0]

Networks using the TCP/IP protocol route messages based on the IP address of the destination. An IP address is a 32-bit numeric address written as four numbers separated by periods.

bumsfeld 413 Nearly a Posting Virtuoso

This code shows how to input a series of integers each separated by a space and then convert that input to a list of those integers:

# input a sequence of integer numbers separated by a space and convert to a list

def get_integer_list():
    while True:
        # get the sequence string and strip off any trailing space (easy mistake)
        str1 = raw_input("Enter a sequence of integers separated by a space: ").rstrip()
        try:
            # create a list of integers from the string using list comprehension
            return [int(num) for num in str1.split(" ")]
        except ValueError:
            print "Error: '%s' is not an integer! Try again." % num
            
print get_integer_list()

For example the input 1 2 3 4 5 turns into [1, 2, 3, 4, 5]

bumsfeld 413 Nearly a Posting Virtuoso

This would be example from one of the tutorials:

# Tkinter top-level menus

from Tkinter import *
from tkMessageBox import *

# temporary function to call from menu
def notdone():
    showerror('Not yet', 'Work in progress!')

def makemenu(win):
    top = Menu(win)
    win.config(menu=top)
    
    file = Menu(top)
    file.add_command(label='New...', command=notdone, underline=0)
    file.add_command(label='Open...',command=notdone, underline=0)
    file.add_command(label='Quit', command=win.quit, underline=0)
    top.add_cascade(label='File', menu=file, underline=0)

    edit = Menu(top, tearoff=0)
    edit.add_command(label='Cut', command=notdone, underline=0)
    edit.add_command(label='Paste', command=notdone, underline=0)
    edit.add_separator()
    top.add_cascade(label='Edit', menu=edit, underline=0)

    submenu = Menu(edit, tearoff=0)
    submenu.add_command(label='Spam', command=win.quit, underline=0)
    submenu.add_command(label='Eggs', command=notdone, underline=0)
    edit.add_cascade(label='Stuff', menu=submenu, underline=0)

root = Tk()
root.title('menu_win')
makemenu(root)
msg = Label(root, text='Window menu basics')
msg.pack(expand=YES, fill=BOTH)
msg.config(relief=SUNKEN, width=40, height=7, bg='beige')
root.mainloop()
bumsfeld 413 Nearly a Posting Virtuoso

Design a text driven adventure game. Draw a map with features like meadows, woods, mountains, rivers, lakes, caves, cottages and such. You know the map, the player does not! Start in the center and give a description in all directions.

Ask the player which direction she/he wants to go (E,W,S,N). Keep descriping the new environment according to your map and ask player for directions to go.

The goal is to find a treasure hidden somewhere on the map(give hints on how close the player is) and then find the way back to the start. Hopefully the player can remember some of the more distinctive features along the path taken.

bumsfeld 413 Nearly a Posting Virtuoso

You mean something like that:

import tkFileDialog
# examples:
def open_it():
    filename = tkFileDialog.askopenfilename()
    print filename  # test
    
def save_it():
    filename = tkFileDialog.askopenfilename()
    print filename  # test
    
def save_as():
    filename = tkFileDialog.asksaveasfilename()
    print filename  # test
bumsfeld 413 Nearly a Posting Virtuoso

Yes, thanks monkeyy!

bumsfeld 413 Nearly a Posting Virtuoso

You can write much more clean code if you start with Python over again. VB code is usually just to "helter skelter"! Look at your application and rewrite it in Python.

bumsfeld 413 Nearly a Posting Virtuoso

There is also Glade IDE for Pygtk toolkit and something called PyCard.

bumsfeld 413 Nearly a Posting Virtuoso

I hope you are talking about Tkinter as GUI. This code might help you. You have to use a if statements to get the right key value to go to the proper function then.

# bind and show a key event with Tkinter 

from Tkinter import *

root = Tk()
prompt = '      Press any key      '
label1 = Label(root, text=prompt, width=len(prompt))
label1.pack()

def key(event):
    if event.char == event.keysym:
        msg = 'Normal Key %r' % event.char
    elif len(event.char) == 1:
        msg = 'Punctuation Key %r (%r)' % (event.keysym, event.char)
    else:
        msg = 'Special Key %r' % event.keysym
    label1.config(text=msg)

label1.bind_all('<Key>', key)

root.mainloop()
bumsfeld 413 Nearly a Posting Virtuoso

This littel program allows you to find which key had been pressed using the Tkinter GUI.

# bind and show a key event with Tkinter 

from Tkinter import *

root = Tk()
prompt = '      Press any key      '
label1 = Label(root, text=prompt, width=len(prompt))
label1.pack()

def key(event):
    if event.char == event.keysym:
        msg = 'Normal Key %r' % event.char
    elif len(event.char) == 1:
        msg = 'Punctuation Key %r (%r)' % (event.keysym, event.char)
    else:
        msg = 'Special Key %r' % event.keysym
    label1.config(text=msg)

label1.bind_all('<Key>', key)

root.mainloop()
bumsfeld 413 Nearly a Posting Virtuoso

Working with SQL I found this site. It may help!
http://www.mayukhbose.com/python/ado/index.php

bumsfeld 413 Nearly a Posting Virtuoso

Maybe GTK is only for Linux?

bumsfeld 413 Nearly a Posting Virtuoso

I get "Page Not Found"

bumsfeld 413 Nearly a Posting Virtuoso

Take shower when it rains!

bumsfeld 413 Nearly a Posting Virtuoso

A logic shortcut:

x, y, z = 1, 2, 3
# test if y value is between x and z value
if x < y < z:
    print x, y, z  # 1 2 3
print
# same test, longer logic
if x < y and y < z:
    print x, y, z  # 1 2 3
print

Notice you can even do logic tests like:

if u < w < v < y < x:
    do some things
bumsfeld 413 Nearly a Posting Virtuoso

Something like this works fine:

try:
    case = int(raw_input("enter a number less then 3 or more than 4: "))
except:
    case = 0
while case <=2 or case >=5:
    # do something to get out of loop
    case += 1
    print case
    if case > 10: break

Notice that case is reserved keyword in C++, also notice that && is and || is or in Python. A simple & is bitwise and in C++ and Python.

bumsfeld 413 Nearly a Posting Virtuoso

ABC:

WRITE "Hello World! using ABC language "

Perl:

print "Hello, World! using Perl language"

Python was supposed to be from ABC and Perl?

bumsfeld 413 Nearly a Posting Virtuoso

If you have five dice, how often do you have to throw (average) the dice to get a hand of four sixes? Try with other poker hands too.

bumsfeld 413 Nearly a Posting Virtuoso

A friend of me says that you can play mp3, mid and ogg files with Pygame but you need extra install modules for SDLs.

bumsfeld 413 Nearly a Posting Virtuoso

I am trying things with wxStaticText (a label). I can chnage background colour, but not the text colour:

import wx

class MyPanel(wx.Panel):
  def __init__(self, parent, id):
    wx.Panel.__init__(self, parent, id)
    str1 = "Camembert cheese is the best!"
    self.label1 = wx.StaticText(self, -1, str1 , wx.Point(15, 30))
    self.label2 = wx.StaticText(self, -1, str1 , wx.Point(15, 50))
    self.label2.SetBackgroundColour("Yellow")
    #self.label2.SetTextColour("blue")  # gives error!
    
    
app = wx.PySimpleApp()
myframe = wx.Frame(None, -1, "wxPython Labels", size = (330, 150))
MyPanel(myframe, -1)
myframe.Show(1)
app.MainLoop()

How to change text colour?

bumsfeld 413 Nearly a Posting Virtuoso

Maybe Vegaseat was joking?

bumsfeld 413 Nearly a Posting Virtuoso

The Internet has many animated GIF files, they are funny to watch. Does Python have a way to play those?

I am asking to much?

bumsfeld 413 Nearly a Posting Virtuoso

Thank you mawe,

so when I take the list with duplicates and make it one set then the duplicates are gone. How can I find out which were those duplicates?