Gribouillis 1,391 Programming Explorer Team Colleague

To know why, you could try print(QtGui.QPushButton.setText) or print(type(QtGui.QPushButton.setText)) . However, I don't like super . It's not a very useful feature.

Gribouillis 1,391 Programming Explorer Team Colleague

Sorry, I meant that you should try

QtGui.QPushButton.setText(self, "PROVA")
Gribouillis 1,391 Programming Explorer Team Colleague

Did you try

ItiaQPushButton.setText(self, "PROVA")

?

Gribouillis 1,391 Programming Explorer Team Colleague

In python, there is no difference between a variable in a for loop and a variable outside a for loop. I suggest that you forget all your batch and follow a good python tutorial step by step !

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest

>>> print("\n" * 40)

Or even better

>>> def clear():
...      print("\n"*40)
>>> clear()

Last one:

>>> def clear():
...      import sys
...      for i in range(40):
...          print(sys.ps1)
Gribouillis 1,391 Programming Explorer Team Colleague

your program stores instances of the class country in (name,value) pairs of the dictionary doesn't it? the name is the input and the value is the actual object...

exactly.

Gribouillis 1,391 Programming Explorer Team Colleague

what does it mean when "object" is provided as an argument to a class?

It means that the base class of your class is 'object'. Depending on your version of python it's necessary or not to declare a base class. My advice is to declare object until nobody uses python 2.x.

Gribouillis 1,391 Programming Explorer Team Colleague

You could use a dictionary

class Country(object):
    def __init__(self, name):
        self.name = name

def create_countries():
    countriesDict = dict()
    print("Please enter the countries names (enter 'done' to exit the loop): ")
    while True:
        userInput = raw_input("country: ").strip() # or input if python 3.x
        if userInput:
            if userInput == "done":
                break
            countriesDict[userInput] = Country(userInput)
    return countriesDict

theCountries = create_countries()
print(theCountries)
mahela007 commented: Thanks for the example.. they really help with questions like these. +1
Gribouillis 1,391 Programming Explorer Team Colleague

try

>>> print "abc" . join(['H', 'E', 'L', 'L', 'O'])
Gribouillis 1,391 Programming Explorer Team Colleague

Replace print ALLINONE by print "".join(ALLINONE) .

Gribouillis 1,391 Programming Explorer Team Colleague

The problem is that LINONE.get(letter) returns None if letter is not in LINONE (type >>> help(dict.get) in the python console). So you must handle the case where the letter is not in the dictionary.

Gribouillis 1,391 Programming Explorer Team Colleague

TypeError: 'range' object does not support item assignment

Usually, you can fix this by replacing range(*args) with list(range(*args)) .

vegaseat commented: thanks for the note +14
Gribouillis 1,391 Programming Explorer Team Colleague

Ok, here is a solution

base = "ABC"

FIVEHIGH = (
"""
X 0 X X
0 X 0 X
0 0 0 X
0 X 0 X
0 X 0 X 
""",
"""
0 0 X X
0 X 0 X
0 0 X X
0 X 0 X
0 0 X X
""",
"""
X 0 X X
0 X 0 X
0 X X X
0 X 0 X
X 0 X X
""")

class Ideogram(tuple):
    def __new__(cls, string):
        return tuple.__new__(cls, (y for y in (x.strip() for x in string.split("\n")) if y))
    def __init__(self, *args):
        assert(len(self) == 5)


base_dict = dict(zip(tuple(base), (Ideogram(x) for x in FIVEHIGH)))

def translate(word):
  lines = list(list() for i in range(5))
  for letter in (c for c in word.upper() if c in base_dict): # skip characters that dont belong to base
     for i, x in enumerate(base_dict[letter]):
        lines[i].append(x)
  return "\n".join(" ".join(L) for L in lines)

if __name__ == "__main__":
    word = raw_input("Enter word:")
    print translate(word)
Gribouillis 1,391 Programming Explorer Team Colleague

Here is how we could do in pseudo-algorithmic language. Let's call the elements of FIVEHIGH "ideograms"

create an empty list L
for each character c in word:
    find the ideogram x corresponding to c
    append x to our list L
# now the problem is to display the result
# we display the 5 lines one after the other
for each i in 1, 2, 3, 4, 5:
    initialize the i-th line S to the empty string
    for each ideogram x in L:
        find the i-th line y of x # for example 2nd line of the first ideogram is 0 X 0 X
        concatenate y to S
    print S

Now, you write the python code for this strategy !

Gribouillis 1,391 Programming Explorer Team Colleague

First, make a list with the strings which correspond to CAB, then think about how to produce your output with this list.

Gribouillis 1,391 Programming Explorer Team Colleague

You must not add the triple quoted strings in FIVEHIGH.

Gribouillis 1,391 Programming Explorer Team Colleague

You can create a dictionary to associate a string to each letter

translation = dict()
for i in range(len(base)):
    translation[base[i]] = FIVEHIGH[i]

and then use translation[c] to get the string corresponding to c. Post your new code when it's written.

Gribouillis 1,391 Programming Explorer Team Colleague

Look at the documentation of maketrans. It can only replace a character by a single character. This means that you can't use maketrans and translate for your purpose. Here is how you could iterate over the characters

if word == "":
    print "No word entered"
else:
    print "Your word is",word
    for c in word:
        print(c)

Now, instead of printing the character, you must find the triple quoted string which corresponds to this character (if any). You should then put all these strings in a list and finally concatenate all the strings of the list.

Gribouillis 1,391 Programming Explorer Team Colleague

I've also toyed with dictionaries, but couldn't get them to work either. Any help would be greatly appreciated.

When "it doesn't work" in python, most of the time, there is an exception traceback (python complains). Here is what I get in my terminal when I try to run your program

[t215809] python cypher.py
Traceback (most recent call last):
  File "cypher.py", line 31, in <module>
    cypher = string.maketrans(base, FIVEHIGH)
NameError: name 'string' is not defined

Python tells us that when it reaches the line cypher = string.maketrans(base, FIVEHIGH) , it fails because you didn't say what the variable "string" is. When it doesn't work, you must study the traceback and understand what it means. Now your problem is to tell python what "string" is. After this problem, there are other problems waiting for you, with other tracebacks.
So, go one step after the other, and when you have a traceback, put it in your posts because it's very useful for helpers.

Gribouillis 1,391 Programming Explorer Team Colleague

Any suggestions about my crazy and annoying "are you sure" messages when you attempt to close the frame? I know that there should be a way to just wire this once and bind to the close frame button as well as the exit in the menu function?

I suggest

def annoy(parent, how_much):
    for i in range(how_much):
        exitInfo = "Are you %ssure you want to exit ?" % ("really " * i)
        exitBox = wx.MessageDialog(parent, message=exitInfo, caption='Exit',
                                    style=wx.ICON_INFORMATION | wx.STAY_ON_TOP | wx.OK)
        if exitBox.ShowModal() == wx.ID_OK:
            exitBox.Destroy()
Gribouillis 1,391 Programming Explorer Team Colleague

hmm

import re
pat = re.compile(r"((?:\\.|[^^])+)")
data = r"Autocolli\^sion:No^Pack\^age:10DB15"
print(pat.findall(data))
""" my output --->
['Autocolli\\^sion:No', 'Pack\\^age:10DB15']
"""
Gribouillis 1,391 Programming Explorer Team Colleague

Also, check this page.

PetuniaRose commented: Excellent! +1
Gribouillis 1,391 Programming Explorer Team Colleague

Mathematically, round(x, n) is the number of the form integer * (10**(-n)) which is closest to x. For example round(2.12345678, 3) is 2.123. Python prints 2.1230000000000002 because it uses a binary representation internally and 2.123 has an infinite number of binary digits, but it means 2.123. For example if I compute 1000 * round(2.12345678, 3) - 2123 , it prints 0.0

Gribouillis 1,391 Programming Explorer Team Colleague

Oh... one more question.
How would you write the code so that the content between the two tags are printed? Is that possible?
For example <p> Hello World </p> the output should be, Hello World

Well, if you only want to print the text content of the first paragraph, you could go this way

class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.count_paragraph = 0
        self.print_data = False
    def handle_starttag(self, tag, args):
        if tag == "p":
            self.count_paragraph += 1
            if self.count_paragraph == 1:
                self.print_data = True
    def handle_data(self, data):
        if self.print_data:
            print(data)
    def handle_endtag(self, tag):
        if tag == "p" and self.print_data:
            self.print_data = False
Gribouillis 1,391 Programming Explorer Team Colleague

I don't call the methods, the parser does. When I call theParser.feed and theParser.close, the parser "reads" the html input and calls the methods; For example, when it encounters <h1>, it calls handle_starttag('h1'), etc.

Gribouillis 1,391 Programming Explorer Team Colleague

You can run this program to see how the parser's methods are called while the parser reads your html data

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, *args):
        print "handle_starttag%s called." % str(args)

    def handle_startendtag(self, *args):
        print "handle_startendtag%s called." % str(args)

    def handle_endtag(self, *args):
        print "handle_endtag%s called." % str(args)

    def handle_data(self, *args):
        print "handle_data%s called." % str(args)

    def handle_charref(self, *args):
        print "handle_charref%s called." % str(args)

    def handle_entityref(self, *args):
        print "handle_entityref%s called." % str(args)

    def handle_comment(self, *args):
        print "handle_comment%s called." % str(args)

    def handle_decl(self, *args):
        print "handle_decl%s called." % str(args)

    def handle_pi(self, *args):
        print "handle_pi%s called." % str(args)

myData = """

<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>
"""

theParser = MyHTMLParser()
theParser.feed(myData)
theParser.close()

"""my output  ------>
handle_data('\n\n',) called.
handle_starttag('html', []) called.
handle_data('\n',) called.
handle_starttag('body', []) called.
handle_data('\n\n',) called.
handle_starttag('h1', []) called.
handle_data('My First Heading',) called.
handle_endtag('h1',) called.
handle_data('\n\n',) called.
handle_starttag('p', []) called.
handle_data('My first paragraph.',) called.
handle_endtag('p',) called.
handle_data('\n\n',) called.
handle_endtag('body',) called.
handle_data('\n',) called.
handle_endtag('html',) called.
handle_data('\n',) called.
"""

The next step is to fill the methods' body so that your parser does something more useful than just printing the order of the calls and their arguments.

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest that you write your own program to see what it does.

Gribouillis 1,391 Programming Explorer Team Colleague

You could also consider loading all the schools and children in memory and modify the database only when you know in which school each child goes (this can be done if you're able to compute the distance between a child and a school without the ST_DISTANCE function).
Also, try to use the cProfile module to tell you where time is spent.

Gribouillis 1,391 Programming Explorer Team Colleague

It looks much better now. Congratulations.

Gribouillis 1,391 Programming Explorer Team Colleague

No, you probably entered something different from what I said above. Now good luck for your presentation, I can't help you more because it's very late here. bye.

Gribouillis 1,391 Programming Explorer Team Colleague

The last line should be

Competitions().main()

Your mission is to understand why. Also, the word 'global' should not appear in your code.

Gribouillis 1,391 Programming Explorer Team Colleague

You don't need to put every function in the class, but it's the easiest thing to do. You must create an instance. If you replaced the call main() by Competitions().main() it should work (note that calling the class creates an instance).

Gribouillis 1,391 Programming Explorer Team Colleague

A standard design to avoid global variables is to define a class like this

class Competitions(object):
    def __init__(self):
        self. old_leader = 0
    def read_file(self, database):
        ...
    def make_object(self, file1):
        ...
    etc

if __name__ == "__main__":
    Competitions().main()
Gribouillis 1,391 Programming Explorer Team Colleague

Also you should check if there is something to put between the words in the morse code.

Gribouillis 1,391 Programming Explorer Team Colleague

I suppose that the sound for "a" is played when beeps.a() is called. Your program plays all the letters when you fill your dict. What you could do is forget about the dict and write this

for letter in utext:
    if hasattr(beeps, letter):
        getattr(beeps, letter)()

Also, when you have a traceback, put the traceback in your posts. It's very useful for helpers.

Gribouillis 1,391 Programming Explorer Team Colleague

At first sight, it seems that you forget to call lower() .

Gribouillis 1,391 Programming Explorer Team Colleague

Dear kk2628,
you're lucky, I have a live CD with Ubuntu, so I could test the program on ubuntu and I had the same problem. The problem is that the call to Popen with the argument shell=True creates 2 processes, a /bin/sh process and a /.../firefox process. The call to terminate() only kills the sh process. So I opened the subprocess with the command

child = sp.Popen(['firefox', '-p',  'foo', '-no-remote', url])

and it works. I don't know why the behaviour is different on my system (mandriva).
By the way, I don't think it's very useful to run python with the -v option.

Gribouillis 1,391 Programming Explorer Team Colleague

I managed to close the window on linux by creating a second instance of firefox. To do this I create a new profile for filefox (which I called "foo"). You can do this with the command firefox -profilemanager . Then I start firefox with

child = sp.Popen('firefox -p foo -no-remote %s' % url, shell=True)

The window closes on child.terminate()

Gribouillis 1,391 Programming Explorer Team Colleague

Hello, I'm pretty new to network programming as well. But I have managed to get some simple codes working such as a sniffer which can moniter all packets traveling in and out. I would assume that something like this would be useful so maybe read up as much as you can about socket programming.

Can you post the sniffer's code ?

Gribouillis 1,391 Programming Explorer Team Colleague

It allows your program to launch other programs and communicate with them.

mahela007 commented: thanks.. +1
Gribouillis 1,391 Programming Explorer Team Colleague

Popen.terminate() is new in python 2.6, as well as Popen.kill() .

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a rather crude method, using subprocess

import subprocess as sp
import time
def browse(url, how_long):
    child = sp.Popen("firefox %s" % url, shell=True)
    time.sleep(how_long)
    child.terminate()
browse("http://www.python.org", 3)

However, on my system, this closes firefox only if it's not already running when the call to Popen happens.
If you only need to display an html page and then close the window, you could also use wxpython instead of your web browser, see this code snippet.

Gribouillis 1,391 Programming Explorer Team Colleague

You can run it with module subprocess as well

import subprocess
child = subprocess.Popen("sysargs1.py myarg1 myrag2", shell=True)
Gribouillis 1,391 Programming Explorer Team Colleague

Parsing often means "perform syntax analysis" on a program or a text. It means check if a text obeys given grammar rules and extract the corresponding information. For example, suppose that you define the rule that the structure of a question in english is auxiliary verb + subject + main verb + rest . Then the output of the statement parse("Are they playing football?") could be a hierarchy of tuples, or other objects, like this

("question",
    ("auxiliary verb", "are"),
    ("subject", "they"),
    ("verb", "playing"),
    ("rest", "football"),
)

Programs and compilers handle such trees more easily than raw text.

mahela007 commented: Thanks a lot +1
Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

Just an idea, I fell on this page. I think it should be possible to access the usb devices through HAL (sorry, I don't have enough time to investigate the idea now).

Gribouillis 1,391 Programming Explorer Team Colleague

I think it would be a good idea to make a post with
1) a part of your input file, say 20 lines
2) the precise output that you're expecting from your program or some of the functions that you're trying to write.

Gribouillis 1,391 Programming Explorer Team Colleague

You can try this:

from collections import defaultdict

match = defaultdict(int)
for values in a:
    match[tuple(values[:3])] += 1

print(match)
Gribouillis 1,391 Programming Explorer Team Colleague

It means that tkinter is the "glue" code necessary to use TCL/Tk's functions from a python program.

Gribouillis 1,391 Programming Explorer Team Colleague

You open a DOS shell (from the windows main menu, you should be able to open a command line (I don't use vista, so I don't know which terminology is used)). Then in this shell, you move to the Pmw folder that you downloaded, whith a command like

cd C:\.....\Pmw

(put the path to the folder containing the file "setup.py"), press return, then type the command

python setup.py install

and return. To test your installation, open a python shell (for example idle) and execute import Pmw . If python doesn't complain, everything is ok.