Gribouillis 1,391 Programming Explorer Team Colleague

replace eval by print repr(...) so that we can see the string which was eval'ed

Gribouillis 1,391 Programming Explorer Team Colleague

No it's just a trick I used. I want your AddData class to call Show(True) on your main window. For this it must have an access to the main window, so I pass the main window to the AddData object and it stores it as a member main_window. It could have been self.foo instead. It can then call self.main_window.Show(True)

Stefano Mtangoo commented: This man have highly helped me.He/She seems to be great in python and very innovative +2
Gribouillis 1,391 Programming Explorer Team Colleague

When you create a subclass, you must initialize the instances of the subclass with the parent's class, so I think your __init__ function for the AddData class should begin like this

class AddData(wx.Dialog):
    def __init__(self, parent, id, title, main_window):
        wx.Dialog.__init__(self, parent, id, title, size=(200, 150))
        ....

I misspelled this in the code I wrote above

Gribouillis 1,391 Programming Explorer Team Colleague

For the first question, I specify MainPanel as an argument because the function's body uses the MainPanel ! An alternative would be to keep the MainPanel in the object as a member self.MainPanel . The method could then access this object without a parameter.

For the second question, you must think of self.cell as a list of lists like this

[
    [ wx.TextControl, wx.TextControl, wx.TextControl],
    [ wx.TextControl, wx.TextControl, wx.TextControl],
    [ wx.TextControl, wx.TextControl, wx.TextControl],
    [ wx.TextControl, wx.TextControl, wx.TextControl],
]

I built this like this

initially
[]

I add a row
[[]]

In this row I add an item

[[wx.TextControl]]

another

[[wx.TextControl, wx.TextControl]]

etc, then another row

[
    [wx.TextControl, wx.TextControl, wx.TextControl],
    []
]

etc

For the third question, I forget to mention that you must also add the parameter when you call AddData, so in OnEdit, you should write

call = AddData(None, -1, "Please Login for Authentication", self)

Good luck for your interface with the database. I think it's a lot of work !

Gribouillis 1,391 Programming Explorer Team Colleague

Here is how you could do this

class MainWindow(wx.Frame):
    def __init__(...):
        ...
        self.ncols = 3
        self.nrows = 4
        self.create_titles(MainPanel)
        self.create_cells(MainPanel)
        """
        #DROP THIS
        self.col1 = wx.StaticText(MainPanel, -1, "Column 1", style=wx.ALIGN_CENTER)
        self.col2= wx.StaticText(MainPanel, -1, "Column 2", style=wx.ALIGN_CENTER)
        self.col3 = wx.StaticText(MainPanel, -1, "Column 3", style=wx.ALIGN_CENTER)
        #Cells, arranged by rows i.e 1st row cel1, cel2, cel3
        #Row 1
        self.cel1 = wx.TextCtrl(MainPanel, -1)
        self.cel2 = wx.TextCtrl(MainPanel, -1)
        self.cel3 = wx.TextCtrl(MainPanel, -1)
        #Row 2
        self.cel4 = wx.TextCtrl(MainPanel, -1)
        self.cel5 = wx.TextCtrl(MainPanel, -1)
        self.cel6 = wx.TextCtrl(MainPanel, -1)
        #Row 3
        self.cel7 = wx.TextCtrl(MainPanel, -1)
        self.cel8 = wx.TextCtrl(MainPanel, -1)
        self.cel9 = wx.TextCtrl(MainPanel, -1)
        #Row 4
        self.cel10 = wx.TextCtrl(MainPanel, -1)
        self.cel11 = wx.TextCtrl(MainPanel, -1)
        self.cel12 = wx.TextCtrl(MainPanel, -1)
        #-----------------------------------------
        """
        #Add to gridsizer (row, col, vgap, hgap)
        gsizer = wx.GridSizer(self.nrows, self.ncols, 4, 4)
        items = list(self.title)
        for i in range(self.nrows):
            items.extend(self.cell[i])
        gsizer.AddMany([(item, 0, wx.EXPAND) for item in items])
        """
        #DROP THIS
        gsizer.AddMany([(self.col1, 0, wx.EXPAND) , 
                        (self.col2, 0, wx.EXPAND) , 
                        (self.col3, 0, wx.EXPAND) , 
                        (self.cel1, 0, wx.EXPAND) , 
                        (self.cel2, 0, wx.EXPAND),
                        (self.cel3, 0, wx.EXPAND),
                        (self.cel4, 0, wx.EXPAND),
                        (self.cel5, 0, wx.EXPAND),
                        (self.cel6, 0, wx.EXPAND), 
                        (self.cel7, 0, wx.EXPAND), 
                        (self.cel8, 0, wx.EXPAND), 
                        (self.cel9, 0, wx.EXPAND), 
                        (self.cel10, 0, wx.EXPAND),
                        (self.cel11, 0, wx.EXPAND),
                        (self.cel12, 0, wx.EXPAND)
                        ])
        """
    def create_titles(self, MainPanel):
        self.title = []
        for i in range(self.ncols):
            self.title.append(
                wx.StaticText(
                MainPanel, -1, "Column %d" % (i+1), style=wx.ALIGN_CENTER)
            )

    def create_cells(self, MainPanel):
        self.cell = []
        for i in range(self.nrows):
            self.cell.append([]) # add a row
            for j in range(self.ncols):
                self.cell[i].append(wx.TextCtrl(MainPanel, -1))

With this, you can now access the colum titles with self.title[i] where 0 <= i …

Gribouillis 1,391 Programming Explorer Team Colleague

I think a simple way to do it is give AddData objects a pointer to the main window like this

classAddData(...):
    def __init__(self, parent, id, title, main_window, size = (200, 150)):
        self.main_window = main_window
        ....
    def OnCancel(self):
        ...
        self.main_window.Show(True)

As a constructive criticism of your code, I think you should really define an array for the colums and the cells, and have an acces like self.col[i] and self.cell[i][j] so that many operations can be done with loops!

Gribouillis 1,391 Programming Explorer Team Colleague

It's very simple, the if statement looks like this

if expression:
    statements

optionally followed by zero or more blocks like

elif expression:
    statements

and finally zero ore only one block like

else:
    statements

The "statements" part may contain other if statements, but for a given if statement, the keywords "if", "elif" and "else" must have the same indentation. :)

Gribouillis 1,391 Programming Explorer Team Colleague

I think, replace "\n" by ", " in the method __str__ of the Matrix class.

Gribouillis 1,391 Programming Explorer Team Colleague

Here http://docs.python.org/lib/built-in-funcs.html#l2h-60 is the explanation ! Now, try to understand this example

def foo(x, y):
  return 10 * x + y

num = range(1, 7)
print num
print reduce(foo, num)

However, sum is nice too, for your specific problem.

Gribouillis 1,391 Programming Explorer Team Colleague

Use the reduce built-in function like this

number = reduce(lambda x, y: x + y, num)
Gribouillis 1,391 Programming Explorer Team Colleague

The -10 means that she reserves a space of 10 characters to write the string (filled with blanks) and the minus sign means left justification I think. Read this page http://diveintopython.org/native_data_types/formatting_strings.html and the links from this page.

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

A faster way

wordlistfile = open('wordlist.txt', 'r')
possiblefile = open('possible.txt', 'r')

D = {}
for line in wordlistfile:
  word = line.strip()
  s = "".join(sorted(word))
  if not s in D:
    D[s] = []
  D[s].append(word)

for line in possiblefile:
  scrambled = line.strip()
  s = "".join(sorted(scrambled))
  if s in D:
    print scrambled, sorted(D[s])

:)

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a way to open an object file and make it a string

text = open('data.xrc').read()

:)

Gribouillis 1,391 Programming Explorer Team Colleague
>>> L = range(1, 10)
>>> L
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> reduce(int.__mul__, L)
362880
>>>

but there are other problems in your program :) for example float should be int . Also, what is b ?

Gribouillis 1,391 Programming Explorer Team Colleague

I think the problem is that you always use the same image_sonic . For example, each time you go through the double for i ... for j ... , the value of image_sonic[0][0] is modified, but since all self.TileSnc[stat][pos] are this same image_sonic object (or array), evrey loop erases the previous one.
What you should do is to define a new image_sonic object at each loop like this

for h in ...:
  image_sonic = create_frame(int(height), int(frame))
  ...
  for i ...
    for j ...

And create frame is a function returning a new object, like this one if your objects are just arrays

def create_frame(height, width):
  L = []
  for i in range(height):
    L.append([None] * width)
  return L

But may be your array are Numerical python arrays or something else, so write your own create_frame :)

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

An alternative to using a password to communicate with your friend is to send them a picture of your favorite pet and to use the sha128 digest of the picture as a key, together with a standard encryption algorithm (RSA or a better one). This way, only the people with your pet's picture can decipher your messages, which is quite secure I think.

Gribouillis 1,391 Programming Explorer Team Colleague

why not "%.3f" ?

Gribouillis 1,391 Programming Explorer Team Colleague

I also suggest that you modify load_takings so that you don't have to create the txt file manually the first time, like this:

import os.path

def load_takings():
    if not os.path.exists(TXTFILE):
        dump_takings({})
    fin = open(TXTFILE, "r")
    dic = eval(fin.read())
    fin.close()
    return dic
Gribouillis 1,391 Programming Explorer Team Colleague

A problem with your program is that each time you restart the program, it will overwrite takings[1], takings[2], etc . So you should consider replacing the line n=1 by n = 1 + len(takings) .

Gribouillis 1,391 Programming Explorer Team Colleague

You must indent the clientsock.sendall(...) . Otherwise, it seems to work ;)

Gribouillis 1,391 Programming Explorer Team Colleague

Another way to build the lists

words = """
    aero aesthet andr arch arch ast baro
    biblio bio cardi chron cosm crat cycl dem
    dont dogma dox esth
""".strip().split()
Gribouillis 1,391 Programming Explorer Team Colleague

In the server program, I would write

while 1:
        data =clientsock.recv(BUFSIZ)
        if not data:
            break
        clientsock.sendall('echoed ' + data)

and in the client program

tcpCliSock.sendall(data)
    data = tcpCliSock.recv(1024)
    if not data:
        break
    print data
Gribouillis 1,391 Programming Explorer Team Colleague

Shoudn't you open the file with mode "r" in load_takings and with mode "w" in "dump_takings" ?

Gribouillis 1,391 Programming Explorer Team Colleague

raw_input returns a string, so your test should be

if choice == "military":
    ...

With your code, python thinks that military is a variable's name and complains because there is no such variable.

Gribouillis 1,391 Programming Explorer Team Colleague

I think the indentation is wrong. May be it should be this

def LoadImage(image_name):
    file_name = self.clssSnc.sprites[slf.clssSnc.stat]
    if self.clssSnc.stat == 0:
        file_name = self.clssSnc.spritesi[slf.clssSnc.stati]
        #carrega a imagem do cenrio ou do personagem
    fl = None
    image_path = "sprites/" + image_name
    fl = open(image_path, 'r')
    if (image == "sonic"):
        file_path = "sprites/" + file_name
        fl = open(file_path, 'r')
Gribouillis 1,391 Programming Explorer Team Colleague

There is a technique from the world of parsing and compilation, which uses a dictionary for the keywords. In the text, you look for all identifiers, and if the identifier is in the dictionary (it's a keyword), then it's replaced by a certain value. Here is a way to implement this

import re

kwords = {
  "OUR_HERO" : "James Bond",
  "debug" : "fix",
  "foo": "bar",
}

# a regular expression matching all identifiers
identifier = re.compile(r"[A-Za-z_]\w*")

def repl(match_obj):
  # this function will be called for each identifier in the text during substitution
  word = match_obj.group(0)
  return kwords.get(word, word)

text = """
THis is the text i'm trying to debug with
the help of OUR_HERO and OUR_HEROIN, but it's
a damned foo bar.
"""

print identifier.sub(repl, text)
Gribouillis 1,391 Programming Explorer Team Colleague

The argument of re.compile is a string which represents a regular expression, (or a variable having this value). However, the value returned by re.compile is not a string, but a regular expression object, which doesn't have a method replace . That's why I'm using sub . See http://docs.python.org/lib/node46.html#l2h-393 I think you should describe your problem more completely. Will the keyword change ? etc.

Gribouillis 1,391 Programming Explorer Team Colleague

This regular expression searches for "debug" not followed by an alphanumeric character or underscore

import re

pat = re.compile(r"debug(?!\w)")

sentence = "I'm trying to debug a problem but the debugger is not working"
print pat.sub("fix", sentence)

However it wouldn't work for "I'm trying to debug a problem but the variable my_debug has a wrong value" ;)

Gribouillis 1,391 Programming Explorer Team Colleague

The problem is that your line is a character string, so line[5] is the fifth character. You must split the lines to obtain arrays of 7 items, and get the fifth item like this

data_list.sort(key= lambda line: float(line.split(",")[5]))

also you don't nedd to write a loop to get the data

data_list = [line.strip() for line in open("sample_data.txt")]

produces the same data ;)

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

Since your TestTable objects are instances of this class http://wxpython.org/docs/api/wx.grid.GridTableBase-class.html,
I suppose you can use directly it's methods on your objects (like SetValue ). Also your method redefinitions hide the original methods, so may be you should drop, or rewrite your methods so that they call the methods of the parent class.

Gribouillis 1,391 Programming Explorer Team Colleague

I tried this, with strange results. It looks like python tries to load modules...

Gribouillis 1,391 Programming Explorer Team Colleague

1/ if you type "statistics module python" in a google search engine, you'll find easily some modules with functions for statistics, so don't say you've searched the web !
2/ The list of all modules which come by default with the python distribution can be browsed in the documentation here http://docs.python.org/modindex.html . Other modules installed on your system should be in a folder called "site-packages" in your python library. Of course, you may have installed python modules elsewhere on your system. Run python like this

>>> import sys
>>> print sys.path
['', '/usr/lib/python2.5/site-packages/Pygments-0.8.1-py2.5.egg', '/home/eric/pymods', '/usr/lib/ooo-2.2/program', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10', '/usr/lib/python2.5/site-packages/gtk-2.0', '/usr/lib/python2.5/site-packages/wx-2.6-gtk2-unicode']

The result is a list of folders where python looks for modules when you 'import' something. So you could look in these folders if you see some other modules installed (the list will be different on your system of course) !

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a good tutorial for a beginner http://www.openbookproject.net/thinkCSpy/

Gribouillis 1,391 Programming Explorer Team Colleague

It makes sense, but you should perhaps transform the value instead of the whole array, like this

if otherfunc(valueA) in arr:
  ...

for example here

arr = ["valueA", "valueB"]
if " valueA ".strip() in arr:
  ...
Gribouillis 1,391 Programming Explorer Team Colleague

I looks like homework, it's almost the same problem as JA5ONS's. You should try to work with him, or tell us more about your problem.

Gribouillis 1,391 Programming Explorer Team Colleague

It would be easier if we could see the if statement you need. Is it something like this ?

if map(unstrip, theArray) == [" red ", " blue "]:
  ...
Gribouillis 1,391 Programming Explorer Team Colleague

When you want to transform the elements of a list one by one, use the map function like this

def unstrip(theStr):
  return " %s " % theStr

theArray = ["red", "blue"]
# prints [" red ", " blue "]
print map(unstrip, theArray)

The list comprehension is posible too :)

Gribouillis 1,391 Programming Explorer Team Colleague

bind the item like this, with a keyword argument

self.Bind(wx.EVT_MENU, self.OnPrint, id=ID_PRINT)

Note, with the traceback, you were able to find out that the error happened during this call !

Gribouillis 1,391 Programming Explorer Team Colleague

No, it should have the same indentation as def __init__() . As it is, your function OnPrint is defined in the scope of the __init__ function, and does not exist outside this scope.

Gribouillis 1,391 Programming Explorer Team Colleague

You can also visit this site http://pydoc.org/ and fill the form with

floor

to discover it's in the math module ...

Gribouillis 1,391 Programming Explorer Team Colleague

I tried it here, and it works very well. But, I'm on linux, so I don't use backslashes :)

Gribouillis 1,391 Programming Explorer Team Colleague

ok, the previous line should be

temp.write("%s %d\n" % (name, os.path.getsize(p)))
Gribouillis 1,391 Programming Explorer Team Colleague

I'd suggest something like this

import os

def writeSizes(folder, tmpfile):
  temp = open(tmpfile, "w")
  for name in sorted(os.walk(folder).next()[2]):
    p = os.path.join(folder, name)
    temp.write("%s %d\n)" % (name, os.getsize(p))
  temp.close()

writeSizes("C:\path\to\my\folder", "C:\path\to\my\temp\file")
Gribouillis 1,391 Programming Explorer Team Colleague

didn't you try to parse your xml file with a standard module like xml.dom.minidom ? You just need to write parse("C:/infile.xml") and you get a Document object from which you can extract your data...

Gribouillis 1,391 Programming Explorer Team Colleague

try this:

import os, sys
print "Total: %d .txt files" % len(map(lambda f: sys.stdout.write(f+"\n"),sorted(filter(lambda f: f.endswith(".txt"), os.listdir(".")))))
Gribouillis 1,391 Programming Explorer Team Colleague

same in perl

#!/usr/bin/env perl
$text = "hello world";
$rev = reverse $text;
print $text, "\n", $rev, "\n";
Gribouillis 1,391 Programming Explorer Team Colleague

With os.walk(".").next()[2] , you already have a file list. You don't see it because you take it's len(...) :)