bumsfeld 413 Nearly a Posting Virtuoso

I added some needed lines to your code, now it works. Somehow you have to refresh your drawing as you scroll:

import wx

class Canvas(wx.ScrolledWindow):
    def __init__(self,parent):
        self.okno=parent
        self.radic = wx.FlexGridSizer(3,2,0,0)
        self.canvas = wx.ScrolledWindow(self.okno, -1)
        
        # EnableScrolling(bool x_scrolling, bool y_scrolling)
        self.canvas.EnableScrolling(True, True)
        
        # SetScrollbars(int pixelsPerUnitX, int pixelsPerUnitY, int noUnitsX, 
        #      int noUnitsY, int xPos=0, int yPos=0, bool noRefresh=False)
        PAGE_WIDTH = 1000
        PAGE_HEIGHT = 1000 
        self.canvas.SetScrollbars(20, 20, PAGE_WIDTH/20, PAGE_HEIGHT/20)

        self.radic.Add(self.canvas, 1, wx.EXPAND)
        self.radic.Add((0,0))
        self.radic.Add((0,0))
        self.radic.Add((0,0))
        self.radic.AddGrowableRow(0, 1)
        self.radic.AddGrowableCol(0, 1)
        self.canvas.SetCursor(wx.CROSS_CURSOR)
        self.canvas.Bind(wx.EVT_PAINT, self.OnPaint)
        self.okno.SetSizer(self.radic)
        
    def vykresli_graf(self,dc):
        dc.BeginDrawing()
        lines=[(-500,-500,507,507)]
        dc.DrawLineList(lines)
        dc.EndDrawing()
        
    def OnPaint(self, evt):
        dc = wx.PaintDC(self.canvas)
        self.vykresli_graf(dc)
        
        
if __name__ == "__main__":
    okno = wx.App(0)
    parent=wx.MDIParentFrame(None,size=wx.Size(500,500))
    child=wx.MDIChildFrame(parent,title="Graf",id=-1)
    Canvas(child)
    child.Maximize()
    parent.Show()
    okno.MainLoop()
bumsfeld 413 Nearly a Posting Virtuoso

The other problem with Tkinter is that you are going back and forth between two languages, TCL and Python, so Python rules don't always apply.

bumsfeld 413 Nearly a Posting Virtuoso
from Tkinter import *
import inspect

# find out if Tkinter's PhotoImage is a class
print inspect.isclass(PhotoImage)  # True
bumsfeld 413 Nearly a Posting Virtuoso

Keyword variable image=object needs an object not a function call. You need to use
image1=PhotoImage(file="image.gif")
and then
self.Button = Button(self, image=image1)

bumsfeld 413 Nearly a Posting Virtuoso

For button1 use : self.myboxsizer.Add(self.button1,0,wx.EXPAND|wx.ALL,30) I works on Windows OS, Linux may behave differently.

bumsfeld 413 Nearly a Posting Virtuoso

Here is the code for a title-free Tkinter window.

import Tkinter as tk

root = tk.Tk()
# eliminate the titlebar
root.overrideredirect(1)

# your code here ...

root.mainloop()

You have to exit the program somehow and could create one exit/quit button that needs secret password to quit.

bumsfeld 413 Nearly a Posting Virtuoso

I don't know about phthon but I know that can be done in C or C++ using sockets. Computers attached to a LAN (Local Area Network) do not require internet service provider but others do.

Here is your answer! Use C++! You may want to repost your request in the C/C++ section of the forum.

bumsfeld 413 Nearly a Posting Virtuoso

Looks like someone at the office has been messing with the code field again, sorry!
Copy and pasting code is a mess now!!!!!!!!!!!

Gee, vegaseat you are old and blind. This is supposed to be improvement. See the little line 'Toggle Plain Text' just below the code, click on it, the line numbers are gone and now you can highlight, copy and paste as usual. Merry coding!
Your friend Henri

bumsfeld 413 Nearly a Posting Virtuoso

Looks like you really butchered vegseat's code. Let me rewrite it a little:

""" assume part of your list1.txt data file looks like this:
1846440556
1846440521
1846440491
1846440505
1846441137
1846441102
1846441080
1846441331
1846441323
1846441315
"""

# read the data file in as a list
fin = open( 'list1.txt', "r" )
data_list = fin.readlines()
fin.close()
# test first 5 list items ...
print data_list[:5]

print '-'*60

# remove list items from index 3 to 5 (inclusive)
del data_list[3:5+1]
# test first 5 list items ...
print data_list[:5]

# write the changed data (list) to a file
fout = open("list2.txt", "w")
fout.writelines(data_list)
fout.close()
bumsfeld 413 Nearly a Posting Virtuoso

What is your error message?

bumsfeld 413 Nearly a Posting Virtuoso

I know printing primes isn't anything new, but (like always) I'd love to hear some feedback on how I can make my code more efficient and other constructive criticism.

def print_primes(r=10):
    primes = [ ]
    for i in range(2,r+1):
        prime = 1
        for divisor in range(2,i):
            if i % divisor == 0:
                prime = 0
                break
        if prime:
            primes.append(i)
    print "primes between 1 and %d:" % (r)
    for prime in primes:
        print prime,

print_primes()

Thanks.


EDIT: BAH! I CAN'T DELETE THIS! I just realized there's another prime thread and it has more advanced versions of this program. Sorry for the nuisance!

LaMouche, I am glad you posted this typical beginner's example! I improved your code a little bit and also showed the timing needed to follow positive progress. If you are interested, then see my code snippet at:
http://www.daniweb.com/code/snippet641.html

Mat has done much of interesting things too in his thread.

bumsfeld 413 Nearly a Posting Virtuoso

What's slicing

Also, what's the difference between xrange and range?

Here are some slicing examples (takes a while to get it, but very powerful):

# slicing operator seq[begin : end : step]
# step is optional
# defaults are index begin=0, index end=len(seq)-1, step=1
# -begin or -end --> count from the end backwards
# step = -1 reverses sequence
 
a = [0,1,2,3,4,5,6,7,8]
# if you get lost, put in the defaults in your mind
print a[3:6] # [3, 4, 5]
print a[:3] # [0, 1, 2]
print a[5:] # [5, 6, 7, 8]
print a[-3:] # [6, 7, 8]
print a[2:-2] # [2, 3, 4, 5, 6]
print a[1::2] # [1, 3, 5, 7]
print a[::-1] # [8, 7, 6, 5, 4, 3, 2, 1, 0]
 
# makes true copy of list a
b = a[:]
 
b[2:5] = [77, 88]
print b # [0, 1, 77, 88, 5, 6, 7, 8]

The function range() returns the whole list requested, xrange() returns only the next possible value each time as you iterate in the for loop. This saves time and memory with large list ranges.

bumsfeld 413 Nearly a Posting Virtuoso

... and old code will break frequently, since division will no longer yield integers. :eek:

Jeff

Pascal always had two different divisors, one for integers and one for floats. So I was used to using '//' when I wanted integer division. Lucky me!? In C this problem comes up with beginners a lot.

bumsfeld 413 Nearly a Posting Virtuoso

yea, ditch the printing and append it to a list and it'll be almost instant. :)

Even with ditching print and returning list of primes, this algorithm is not like speed demon. It takes 6,000ms for primes up to 10,000 compared to 4ms with standard sieve algorithm.

bumsfeld 413 Nearly a Posting Virtuoso

Just in case others may wonder, you put the event loop mainloop() in the wrong place:

from Tkinter import *

class Main:
    def __init__(self, master):
        self.master = master
        self.master.title('Role Playing Form V1.0')
        self.master.geometry('300x250+350+450')
        #self.master.mainloop()  #!!!!!!!!!!
        self.cmdCreate = Button(self.master, text='Create Character', command=self.create)
        self.cmdCreate.grid(row=0)
    def create(self):
        pass

root = Tk()
main=Main(root)
# put event loop here
root.mainloop()
bumsfeld 413 Nearly a Posting Virtuoso

So your file has one word per line?

The missing indentations are most like fault of your code editor.
What editor are you using?

bumsfeld 413 Nearly a Posting Virtuoso

Boa Constructor has very many features, for beginner takes time to get familiar. I use it, but some things are not intuitive and hard to find in the extensive menu. You can try it, and I can answer some of your questions. I think vegaseat knows more about it.

You can of course also use Boa for your regular console programs too, it has nice editor/IDE. I think Boa is great tool to learn wxPython things.

Try to download the installer exe for Windows from:
http://downloads.sourceforge.net/boa-constructor/boa-constructor-0.4.4.win32.exe

bumsfeld 413 Nearly a Posting Virtuoso

Thanks this info ghostdog! You must be one great regex expert!

re.findall(r"(\d+)",data_raw) works great on raw_data, but when I changed 40 to 40.5 it gave me [..., '40', '5', ...]
Looks like '\d+ only works on integers.
Do you have any suggestions for floats?

Maybe I should start new thread? Did start own thread see "Extract Numbers from Data Stream"

Thanks in advance!

Henri

bumsfeld 413 Nearly a Posting Virtuoso

Any hints on how you solved it?

bumsfeld 413 Nearly a Posting Virtuoso

Right now the main thing wrong are all the missing indentation that Python uses to block code.

It would be nice to know what 'wordlist.txt' looks like.

bumsfeld 413 Nearly a Posting Virtuoso

I looked at Ene's wxPython remake of vegaseat's fancy Tkinter GUI "Hello World!" code, and used the Boa Constructor IDE to do this. It took only a few minutes to create this wxPython code, since Boa has a drag/drop frame builder and writes most of the code:

# fancy "Hello World!" wxPython code generated mostly by Boa Constructor
# Boa Constructor (needs wxPython, has drag/drop frame builder, debugger etc.)
# Further development may have stopped.  Download free from:
# http://freshmeat.net/redir/boa-constructor/832/url_zip/boa-constructor-0.4.4.zip

#Boa:Frame:Frame1

import wx

def create(parent):
    return Frame1(parent)

[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1STATICTEXT1, 
] = [wx.NewId() for _init_ctrls in range(4)]

class Frame1(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
              pos=wx.Point(396, 174), size=wx.Size(391, 178),
              style=wx.DEFAULT_FRAME_STYLE, title=u'Hello World from DaniWeb!')
        self.SetClientSize(wx.Size(383, 138))

        self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,
              label=u' Hello World! ', name='staticText1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(385, 84), style=0)
        self.staticText1.SetBackgroundColour(wx.Colour(255, 255, 0))
        self.staticText1.SetForegroundColour(wx.Colour(255, 0, 0))
        self.staticText1.SetFont(wx.Font(36, wx.SWISS, wx.NORMAL, wx.NORMAL,
              False, u'Comic Sans MS'))

        self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label=u'white on blue',
              name='button1', parent=self, pos=wx.Point(56, 96),
              size=wx.Size(96, 28), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
              id=wxID_FRAME1BUTTON1)

        self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label=u'blue on green',
              name='button2', parent=self, pos=wx.Point(216, 96),
              size=wx.Size(103, 28), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
              id=wxID_FRAME1BUTTON2)

    def __init__(self, parent):
        self._init_ctrls(parent)

    def OnButton1Button(self, event):
        # I had to add these lines, Boa generates the rest
        self.staticText1.SetBackgroundColour("blue")
        self.staticText1.SetForegroundColour("white")
        self.staticText1.SetLabel(" Hello World! ")        
        #event.Skip()

    def OnButton2Button(self, event):
        # I had to add these lines, Boa generates the rest
        self.staticText1.SetBackgroundColour("green")
        self.staticText1.SetForegroundColour("blue")
        self.staticText1.SetLabel(" Hello World! ")        
        #event.Skip()


if __name__ == '__main__':
    app = wx.PySimpleApp()
    wx.InitAllImageHandlers()
    frame = create(None)
    frame.Show()

    app.MainLoop()
bumsfeld 413 Nearly a Posting Virtuoso

This will print your PYTHONPATH. If the path you want is not listed, and it shouldn't be because your program isn't found, then you have to use sys.path.append to add it.

import sys
path_list= sys.path
for eachPath in path_list :
   print eachPath

PYTHONPATH is only used by Python internally to find modules etc.
This person wants to use Window's Environment Variable.

bumsfeld 413 Nearly a Posting Virtuoso

This puts little more light on it:

def fib(n):
    print "Computing fib:", n
    if 0 < n < 3:
        value = 1
        print "1Returning value: ", value
    elif n == 0:
        value = 0
        print "2Returning value: ", value
    else:
        value = fib(n-1)+fib(n-2)
        print "3Returning value: ", value
    return value
                     
def main():
    n = input("Enter a positive number: ")
    print fib(n)

main()
bumsfeld 413 Nearly a Posting Virtuoso

I think wxPython demos were written by my C++ professor or his father. He always uses the C++ trick of putting in obscure header files, to make student's life harder!

I have simplified some code that works without those extra imports at:
http://www.daniweb.com/code/snippet615.html

bumsfeld 413 Nearly a Posting Virtuoso

Lists are mutable, Dictionaries are not.

That is not true! Dictionaries are mutable! However, you cannot use mutable objects like lists and yes dictionaries for the key. Dictionary values can be most anything. Study some more and experiment with this interesting container. If you get stuck, ask more questions!

bumsfeld 413 Nearly a Posting Virtuoso

Rather than putting your selected line into Label, put it into Entry. Now you can edit it. Bind the Entry to double mouse click to load it back into Listbox at the index sel[0] you have.

bumsfeld 413 Nearly a Posting Virtuoso

I think it depends on the version of Windows XP. I can repeat vegaseat's observation on my folks old desktop computer, but import uses the updated pyc file right away on a friend's brandnew laptop with the latest version of Windows XP.

Does anyone now how to display the version of Windows XP?

Note: Also found out that the module name and the file name have to absolutely match (case sensitive).

bumsfeld 413 Nearly a Posting Virtuoso

For German characters I have found it simpler to replace them with acceptable equivalents. Here is an example:

# -*- coding: iso-8859-15 -*-

str1 = 'Activest-Aktien-Großbritannien'
print str1  # test
str1 = str1.replace('ß', 'ss')
print str1  # test

str2 = 'Überländliche Fracht'
print str2
str2 = str2.replace('Ü', 'Ue')
str2 = str2.replace('ä', 'ae')
print str2
bumsfeld 413 Nearly a Posting Virtuoso

My advice, use the little utility at:
http://www.daniweb.com/code/snippet499.html

Since this is GUI program you need to change 'console' to 'window' and give your filename .pyw extension.

bumsfeld 413 Nearly a Posting Virtuoso

You might have to destroy the dialog after it has been used:

###  uncomment the following 2 lines of code and
        ###  the popup menu will not appear on fc5    
        
        if dlg.ShowModal() == wx.ID_OK:
            # do something
            thisresult = "a file was selected"
        
        dlg.Destroy()
        
        ###  ######################
bumsfeld 413 Nearly a Posting Virtuoso

Here are simple programs. The console version:

# console sales tax program

while True:
    price = float(raw_input("Enter purchase price: "))
    # prevent division by zero error
    if price != 0:
        break
    else:
        print "price can not be zero!"
        
tax = float(raw_input("Enter sales tax paid: "))

percent = 100 * tax / price
print "You paid %0.3f%s sales tax" % (percent, '%')

Now the Tkinter GUI version:

# Tkinter sales tax program

from Tkinter import *
import tkSimpleDialog

# the basic window
root = Tk()
# create label for result
label1 = Label(root)
# position the label in window
label1.grid(row=0, column=0)
# ask for needed data with dialog window
# the askfloat dialog window makes certain you entered floating point value
# and also prevents you from entering zero which would give divide by zero error
price = tkSimpleDialog.askfloat("Price", "Enter purchase price:", parent=root, minvalue=0.01)
tax = tkSimpleDialog.askfloat("Tax", "Enter sales tax paid:", parent=root)
percent = 100 * tax / price
result = "You paid %0.3f%s sales tax" % (percent, '%')
# display result string in label1
label1.config(text=result)
# event loop needed by GUI, checks for mouse and key events
root.mainloop()
bumsfeld 413 Nearly a Posting Virtuoso

Accidental endless loops are the once you have to watch out for. The 'while loop' is more prone to this either through faulty escape logic or accidental use of the control variable:

# accidental endless loop

# this is okay in Python
for k in range(10):
    k = 2
    print k
    
# but not in C ...
"""
// accidental endless loop in C

#include <stdio.h>

int main()
{
  int k;
  
  for(k = 0; k < 10; k++)
  {
    k = 2;
    printf("%d", k);        
  }    
    
  return 0;
}
"""

# the C 'for loop' behaves more like this
# now you have accidental endless loop
k = 0
while k < 10:
    k = 2
    print k
bumsfeld 413 Nearly a Posting Virtuoso

For your information, a few nice folks are working on a 'Python Tkinter GUI Builder' (ptkgb), that allows you to drag and drop Tkinter widgets on one form similar to the Delphi RAD or MS Visual stuff. Take a look at:
http://sourceforge.net/projects/ptkgb/

bumsfeld 413 Nearly a Posting Virtuoso
bumsfeld 413 Nearly a Posting Virtuoso

Expanding on mawe's formula builder, this is my contribution to the equation solver:

# evaluate equation like 3x^2+2(3x-2) = 0

import re

# look for digit before alpha and '('
pattern = re.compile("(\d)([A-Za-z(])")

formula_raw = "3x^2+2(3x-2)"
# insert '*' between digit and alpha or '('
formula = re.sub(pattern, r"\1*\2", formula_raw)

print formula  # '3*x^2+2*(3*x-2)'

# take care of power symbol ^
if '^' in formula:
    formula = formula.replace('^', '**')

print
print "formula =", formula  # '3*x**2+2*(3*x-2)'

# test it with for loop ...
for x in range(-5, 5):
    if 'x' in formula:
        formula2 = formula.replace('x', str(x))
    #print formula2  # test
    print "x = %s  --> %s" % (str(x), eval(formula2))

print

# narrow x value down ...
for x in range(0, 100):
    x = x/100.0
    if 'x' in formula:
        formula2 = formula.replace('x', str(x))
    result = eval(formula2)
    # when result crosses zero line stop
    if result > 0.0:
        print "x = %s  --> %s" % (str(x), result)
        break
Mouche commented: very helpful +1
bumsfeld 413 Nearly a Posting Virtuoso

MSVCR71.dll is the Microsoft runtime C++ library. I don't think Py2Exe is going to mess with that! You can distribute that file, but you cannot change it or get the wrath of big MS!

Jython compiles Python source code down to Java bytecodes which can run directly on a JVM. You have to use the Java utility corresponding to Py2Exe! Py2Exe only handles Python byte code.

bumsfeld 413 Nearly a Posting Virtuoso

I am studying C++ right now in school (not my choice), and being used to Python the endless type declarations, memory allocations, and pointer this, and pointer that, to achieve very simple stuff, is cumbersome at best. Function arguments are handled with such elegance in Python!

bumsfeld 413 Nearly a Posting Virtuoso

Rightclick the IDLE icon and check Properties. You may notice that it still wants to run under Python23. Create a shortcut of Idle.pyw in the Python25/Lib/idellib/ directory and drag it onto your display panel. Use this new icon to run IDLE.

bumsfeld 413 Nearly a Posting Virtuoso

Chris, this approach would avoid the repetition of the room description and make the code shorter. Here is a test code:

gold = 0
gotGold_reading = 0

def reading_room():
    global gold
    print "    Current Gold = ",gold
    print "    You are in a large reading room ..."
    rea_desc()
    #prompt_rea()

def rea_desc():
    print '''    The room is stuffed with novels and poetry books on every
    every shelf. There is a large table in the middle of the room.
    It has a reading lamp, and a cluster of books scattered about
    on top. The exits are (N)orth and (E)ast.  
    Type 'help' for a full list of commands.'''
    print
    prompt_rea()

def prompt_rea():
    global gold
    global gotGold_reading
    prompt_r = raw_input("Type a command: ").lower()
    # etc etc ...

reading_room()
bumsfeld 413 Nearly a Posting Virtuoso

I have used Python and I am learning C++. Programs that are just a few lines of code in Python are nightmares in C++, like splitting sentence into words and loading them into array of strings dynamically.

bumsfeld 413 Nearly a Posting Virtuoso

I have used pygtk one little and have found these good resources:

Recommended reading for Python+GTK users
PyGTK 2.0 Tutorial by John Finlay
download from: http://www.pygtk.org/dist/pygtk2-tut.pdf

also:
PyGTK FAQ Index
at: http://www.async.com.br/faq/pygtk/index.py?req=index

bumsfeld 413 Nearly a Posting Virtuoso

Looks like you have somewhat incomplete code:

#include<stdio.h>

float x[4] = {1.2,2.4,3.6,4.8};
float f[4] = {0.1,0.2,0.3,0.4};
float xave = 0.0;
float ftotal = 0.0;

int main()
{
  int i;
  float weights[4] = {0};
  char buf[80];
  for(i = 0; i < 4; ++i)
  {
    printf("Enter weight #%d", i+1);
    fgets(buf,sizeof(buf),stdin);
    weights[i] = atof(buf);
  }
  
  //???????????? missing something here!!!
  {
    int i;
    for (i=0; 1<4;i++) ftotal + = f[i];
    if(ftotal!=1.0)
    {
      printf("error\n");
      exit();
    }
    for(i=0;1<4;i++) xave+=f *x;
    printf("\nThe weights are %f"&f);
    printf("\nThe average is %f\n",xave);



  // blahblah...
  return 0;
}

There are quite a number of obvious errors too!

bumsfeld 413 Nearly a Posting Virtuoso

Got to hurry! The waitress at the internet bistro wants to serve my meal.
Here is some more code, hope that satisfies your needs:

# this would be rawfile.txt
str1 = """
NAME:XXXXXXXXXXXX
SURNAME:XXXXXXXXXXXX
DATE:23.09.2006
A B C D E F G H (column names)
40 250 300 01.01.2006 13:43:21 250 12345678 KENTBANK
31 123 455 02.02.2006 11:22:43 450 CAPITALBANK
.
.
.
.
PAGE 1

40 150 240 01.11.2006 17:41:21 50 12346678 XBANK
31 123 455 02.02.2006 11:22:43 654474151 YBANK
.
.
PAGE 2

40 250 240 01.11.2006 17:41:21 50 12346678
.
PAGE 3

.
.
PAGE 4

.
.
NOTES:XXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXX
"""

# convert to ...
"""
A B C D E F G H
40 250 300 01.01.2005 13:43:21 250 12345678 KENTBANK
31 123 455 02.02.2005 11:22:43 450 tab CAPITALBANK
40 150 240 01.11.2005 17:41:21 50 12346678 CITYBANK
31 123 455 02.02.2005 11:22:43 tab 654474151 CITYBANK
"""
# save as resultfile.txt

# create raw_file.txt from str1 for testing
fout = open("raw_file.txt", "w")
fout.write(str1)
fout.close()

# read in raw_file.txt as list of lines/strings
fin = open("raw_file.txt", "r")
line_list1 = fin.readlines()
fin.close()

#print line_list1  # test

def sub_missing(line):
    """take string line and sub for certain missing items"""
    # convert string to list
    list1 = line.split()
    # if list1[1] (column A1) starts with 2 prefix with 555
    if list1[1].startswith('2'):
        list1[1] = "555" + list1[1]
    # dito for column A2
    if list1[2].startswith('2'):
        list1[2] = "555" + list1[2]
    # if list1[1] (column A1) starts with 4 prefix with 666 …
bumsfeld 413 Nearly a Posting Virtuoso

Simply replace this part of present code:

# process the list of lines
# give the new list proper header
#line_list2 = ["A B C D E F G H\n"]
str3 = "ID A1 A2 Date Time Sec.SID Bank\n"
str3.replace(" ", "\t")
#print str3  # test
line_list2 = [str3] 
for line in line_list1:
    lead_char = line[0]
    # use only line starting with a number
    if lead_char.isdigit():
        # replace space with tab
        line.replace(" ", "\t")
        #print line  # test
        line_list2.append(line)

The thing with xxx, yyy, zzz and default values you have to explain better. For instance, is xxx contained in rawfile.txt and you want it replaced with 111111? You could do that with additional line.replace(what, with) statements.

bumsfeld 413 Nearly a Posting Virtuoso

Aha, now I see it! All you need to do is reference daclick1() properly! Forget the inherited solution.

#!/usr/bin/python


import wx
import time


class MakePanel1(wx.Panel):
    def __init__(self, Parent, *args, **kwargs):
        wx.Panel.__init__(self, Parent, *args, **kwargs)
        
        self.dalabel = wx.StaticText(self, -1, "   panel 1 label   ")
        self.dabutton1 = wx.Button(self, label="button 1") 
        self.dabutton1.Bind(wx.EVT_BUTTON, self.daclick1 )
        self.bs1 = wx.BoxSizer(wx.HORIZONTAL)
        self.bs1.Add(self.dabutton1,0)
        self.bs1.Add(self.dalabel,0)
        self.SetSizer(self.bs1)
        
    def daclick1(self, event):
        self.dalabel.SetLabel(str(time.time()))


class MakePanel2(wx.Panel):
    """Note that MakePanel2 inherits MakePanel1"""
    def __init__(self, Parent, *args, **kwargs):
        wx.Panel.__init__(self, Parent, *args, **kwargs)

        self.dabutton2 = wx.Button(self, label="button 2") 
        self.dabutton2.Bind(wx.EVT_BUTTON, self.daclick2 )
        self.bs2 = wx.BoxSizer(wx.HORIZONTAL)
        self.bs2.Add(self.dabutton2,0,wx.ALL,20)
        self.SetSizer(self.bs2)

    def daclick2(self, event):
        # reference daclick1() properly!!!!!!! 
        daframe.Panel1.daclick1(self)

class DisFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.Panel1 = MakePanel1(self)
        self.Panel2 = MakePanel2(self)

        bs = wx.BoxSizer(wx.VERTICAL)
        bs.Add(self.Panel1,1,wx.EXPAND);
        bs.Add(self.Panel2,1,wx.EXPAND);

        self.SetSizer(bs)
        self.Fit()


if __name__ == '__main__':
    app = wx.App()
    daframe = DisFrame(None)
    daframe.Show()
    app.MainLoop()

Sorry, was sitting in my favorite internet bistro and got distracted by friends!

bumsfeld 413 Nearly a Posting Virtuoso

Make sure you test this out thoroughly! There are few things that might need to be changed.

bumsfeld 413 Nearly a Posting Virtuoso

If the lines you want start with number, other than header, here is easy solution:

# this would be rawfile.txt
str1 = """
NAME:XXXXXXXXXXXX
SURNAME:XXXXXXXXXXXX
DATE:23.09.2006
A B C D E F G H (column names)
40 250 300 01.01.2006 13:43:21 250 12345678 KENTBANK
31 123 455 02.02.2006 11:22:43 450 CAPITALBANK
.
.
.
.
PAGE 1

40 150 240 01.11.2006 17:41:21 50 12346678 XBANK
31 123 455 02.02.2006 11:22:43 654474151 YBANK
.
.
.
.
PAGE 2

.
.
PAGE 3

.
.
PAGE 4

.
.
NOTES:XXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXX
"""

# convert to something like this ...
"""
A B C D E F G H
40 250 300 01.01.2005 13:43:21 250 12345678 KENTBANK
31 123 455 02.02.2005 11:22:43 450 tab CAPITALBANK
40 150 240 01.11.2005 17:41:21 50 12346678 CITYBANK
31 123 455 02.02.2005 11:22:43 tab 654474151 CITYBANK
"""
# save as resultfile.txt

# create raw_file.txt from str1 for testing
fout = open("raw_file.txt", "w")
fout.write(str1)
fout.close()

# read in raw_file.txt as list of lines/strings
fin = open("raw_file.txt", "r")
line_list1 = fin.readlines()
fin.close()

#print line_list1  # test

# process the list of lines
# give the new list proper header
line_list2 = ["A B C D E F G H\n"]
for line in line_list1:
    lead_char = line[0]
    # use only line starting with a number
    if lead_char.isdigit():
        print line  # test
        line_list2.append(line)

#print line_list2  # test

# convert processed list to string
str2 = ''.join(line_list2)

print str2  # test

# write the string to file
fout = open("result_file.txt", "w")
fout.write(str2)
fout.close()
bumsfeld 413 Nearly a Posting Virtuoso

One solution to fix problem is to have MakePanel2 inherit MakePanel1, then you only need to create instance of MakePanel1 in MakePanel2. For some odd reason wx.BoxSizer() gets confused with the label location. Look the code over.

#!/usr/bin/python


import wx
import time


class MakePanel1(wx.Panel):
    def __init__(self, Parent, *args, **kwargs):
        wx.Panel.__init__(self, Parent, *args, **kwargs)
        
        self.dalabel = wx.StaticText(self, -1, "   panel 1 label   ")
        self.dabutton1 = wx.Button(self, label="button 1") 
        self.dabutton1.Bind(wx.EVT_BUTTON, self.daclick1 )
        self.bs1 = wx.BoxSizer(wx.HORIZONTAL)
        self.bs1.Add(self.dabutton1,0)
        self.bs1.Add(self.dalabel,0)
        self.SetSizer(self.bs1)
        
    def daclick1(self, event):
        self.dalabel.SetLabel(str(time.time()))


class MakePanel2(MakePanel1):
    """Note that MakePanel2 inherits MakePanel1"""
    def __init__(self, Parent, *args, **kwargs):
        wx.Panel.__init__(self, Parent, *args, **kwargs)

        self.dabutton2 = wx.Button(self, label="button 2") 
        self.dabutton2.Bind(wx.EVT_BUTTON, self.daclick2 )
        self.bs2 = wx.BoxSizer(wx.HORIZONTAL)
        self.bs2.Add(self.dabutton2,0,wx.ALL,20)
        self.SetSizer(self.bs2)

    def daclick2(self, event):
        #MakePanel1.daclick1()  # gives error, need to make instance first
        self.Panel1 = MakePanel1(self)
        self.Panel1.daclick1(self)

class DisFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.Panel1 = MakePanel1(self)
        self.Panel2 = MakePanel2(self)

        bs = wx.BoxSizer(wx.VERTICAL)
        bs.Add(self.Panel1,1,wx.EXPAND);
        bs.Add(self.Panel2,1,wx.EXPAND);

        self.SetSizer(bs)
        self.Fit()


if __name__ == '__main__':
    app = wx.App()
    daframe = DisFrame(None)
    daframe.Show()
    app.MainLoop()
bumsfeld 413 Nearly a Posting Virtuoso

I would split user and computer creation of random numbers up like this:

import random

def computer_random():
    """let computer create a list of 6 unique random integers from 1 to 50"""
    ci = random.sample(range(1,50), 6)
    return ci
    
def user_random():
    """let user create a list of 6 unique random integers from 1 to 50"""
    print "Enter 6 random integers from 1 to 50:"
    ui = []
    while len(ui) < 6:
        print len(ui) + 1,
        i = input("--> ")
        # check if i is unique and has a value from 1 to 50
        # otherwise don't append, could also assure that i is an integer
        if (i not in ui) and (1 <= i <= 50):
            ui.append(i)
    return ui

comp_list = computer_random()  # assign the returned list to variable comp_list
print comp_list  # test it

user_list = user_random()
print user_list  # test it

Function comp_random() will be called numerous times, each time you need to compare comp_list with user_list. Now you have to work on list compare function to find the matches, then count how many times 3 to 6matches have occured.

bumsfeld 413 Nearly a Posting Virtuoso

Just for learning purposes:

# one alternative to random.sample(range(0,50), 6)

import random

print "show 6 random unique integers from 1 to 50:"
numbers=[]
while len(numbers) < 6:
    ri = random.randint(1,50)
    if ri not in numbers:
        numbers.append(ri)

print numbers