woooee 814 Nearly a Posting Maven

I wondered why this has been asked many many times in the last few days both here and on python-forum. At least you are honest enough to admit that it is homework. You should be able to find this asked and answered many times already. If you do want help, you'll have to make an effort and post some code to be critiqued.

woooee 814 Nearly a Posting Maven

Try writing and testing your programs on piece at a time. I've commented everything after the __init__ function for Player1 below. Run it that way first and see if that helps. Then add the functions one by one and test them. The problem is not that Player1 doesn't have an attribute named direction, the problem is that you don't have any idea where and what is wrong. Next, you might want to figure out or ask how to use one Player class for any number of players.

#"""Player 1"""
class Player1(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.STANDING = 0
        self.RUNNING = 1

        self.loadImages()
        self.image = self.imageStand
        self.rect = self.image.get_rect()
        self.rect.x = 20
        self.rect.y = 150
        self.frame = 0
        self.delay = 3
        self.pause = 0
        self.state = self.STANDING
        direction = ""

    """--------------------  COMMENTED for testing-----------------------------------------------
    def checkKeys(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            direction = "RIGHT"
            self.rect.x -= 5
            self.state = self.RUNNING
            print self.state, self.rect.x
        elif keys[pygame.K_d]:
            direction = "LEFT"
            self.rect.x += 5
            self.state = self.RUNNING
            print self.state, self.rect.x
            
            
    def update(self):

        self.checkKeys()
        if self.state ==  self.STANDING:
            self.image = self.imageStand

        elif self.state == self.RUNNING:
            self.pause += 1
            if self.pause >= self.delay:
                self.pause = 0
                self.frame += 1
                if self.frame >= len(self.runImages):
                    self.frame = 0
                    self.state = self.STANDING
                    self.image = self.imageStand
                else:
                    self.image = self.runImages[self.frame]
    
    def loadImages(self):
        if self.direction == "RIGHT":
            
            self.imageStand = pygame.image.load("SPRITES/WALKING_RHS/000.gif")
            self.imageStand = self.imageStand.convert()
            transColor = self.imageStand.get_at((1, 1))
            self.imageStand.set_colorkey(transColor)

            self.runImages = []
            for i in range(5):
                imgName = "SPRITES/WALKING_RHS/00%d.gif" % i
                tmpImage = pygame.image.load(imgName)
                tmpImage = tmpImage.convert()
                transColor = tmpImage.get_at((1, 1))
                tmpImage.set_colorkey(transColor) …
woooee 814 Nearly a Posting Maven

With Python you would use a list of lists for each group of records. Hopefully there is a similiar method in scipy. (If you were very, very lucky, each group would have the same number of records, you can use a counter to split them)

data_list=[
"#BEGIN 1",
"1 .1 .2",
"2 .8 .3",
"3 .9 .5",
"#END",
"",
"#BEGIN 2",
"1 .1 .3",
"2 .8 .4",
"3 .9 .6",
"#END",
"",
"#BEGIN 3",
"1 .1 .4",
"2 .8 .5",
"3 .9 .7",
"#END"]

group_list=[]
junk_list=[]
for rec in data_list:
   if rec.strip().startswith("#BEGIN") and (len(junk_list)):
      group_list.append(junk_list)
      junk_list=[]

   else:
      if (len(rec)) and (not rec.startswith("#")):
         junk_list.append(rec)
if len(junk_list):     ##   final group
   group_list.append(junk_list)
for group in group_list:
   print group
woooee 814 Nearly a Posting Maven

The latest one is, 'My wife was killed in a car accident a year ago and I have terminal cancer and will die in X months. Since we have no children, i would like to donate my estate of some-tremendous-amount to an orphanage but don't know of any. If you help me find a suitable one I will give you a-smaller-amount-but-still-a-lot-of-money.' Can we call them "human" beings. Although, the only reason the scams work is because of greed on the part of the responder. If the total amount offered in all of these scams were added together it would equal many times the known wealth of the world. Report these to spam@uce.gov. Spam would soon clog the iternet if it wasn't filtered out.

woooee 814 Nearly a Posting Maven

In pseudo-code it would be something like this assuming a class format (ignoring case for now)

def __init__(self):
          self.orig_list=[ "Original", "words", "you", "want", "to", "test"]
          self.new_list = orig_list[:]  ## first pass - to be used by test_list

     def compare_when_text_changed():
          test_list=self.new_list[:]
          self.new_list=[]
          for word in test_list:
             if word.startswith(self.entered_in_qt_edit_box):
                  self.new_list.append(word)

          ## self.new_list now contains the words that match so far
          ## update list box from self.new_list

     ## not necessary to return anything since self. is used.

I thought that someone would have posted code to do this, but coding this could become so funky that no one wants to put it out there on the internet I guess.

woooee 814 Nearly a Posting Maven

list = file.readlines()

List is a reserved word in python and should not be used as a variable's name. Use something like data_list = file.readlines()

woooee 814 Nearly a Posting Maven

Note the else: "print 'sorry, the synopsis is too long.". That is what I was going on, but the OP will have to decide.

woooee 814 Nearly a Posting Maven

A Google codesearch came up with only the do it yourself, the gist of which used textChanged. This snippet was in one of the hits

searchLabel = QtGui.QLabel(" Search", self)
        hLayout.addWidget(searchLabel)
        self.searchText = QtGui.QLineEdit()
        searchLabel.setBuddy(self.searchText)
        hLayout.addWidget(self.searchText)

        self.treeWidget = self.createTreeWidget()
        vLayout.addWidget(self.treeWidget)

        self.connect(self.searchText,
                     QtCore.SIGNAL('textChanged(QString)'),
                     self.treeWidget.searchItemName)
woooee 814 Nearly a Posting Maven

Also it appears that this part of your code should be "<", not ">"

if story <= 25:
   print wrap_story
else:
   print 'sorry, the synopsis is too long.'
woooee 814 Nearly a Posting Maven

Take a look at the textwrap docs here http://docs.python.org/lib/module-textwrap.html You should be able to use initial_indent and subsequent_indent for the left side spaces. For spaces on the right side, reducing width by 2 should get that, but I have never used textwrap. Also, it is not meant to be a total solution so you may have to write your own.

woooee 814 Nearly a Posting Maven

readline reads until it hits a line termination, (\n=decimal 10 in ascii, or \r\n=decimal 13 & 10, depending on the OS). Decimal 26 is generally used in ascii for end of file, which would terminate a file read also. So a byte is read and if it is not a termination character it is stored in a string and another byte is read, etc. We could do this ourselves but it's nice to have these internals handled for us.

woooee 814 Nearly a Posting Maven

The numbers come from the file as strings, not integers. Strings sort left to right so
100 --> 1 & (00) is less than
95 --> 9 & (5)
Hopefully this bit of code will help

test_int_list = [
80,
0,
60,
25,
50,
70,
75,
100,
90,
95 ]

test_str_list = [str(num) for num in test_int_list]
test_str_list.sort()
print "As strings", test_str_list
test_int_list.sort()
print "As integers", test_int_list
woooee 814 Nearly a Posting Maven

python.org also has a tutorial. Try them all. Some parts of one will make more sense, and in another part, one of the other tutorials will be better. http://docs.python.org/tut/tut.html

woooee 814 Nearly a Posting Maven

I will only give you a hint since the answer is obvious. The variable is named self.tab_1.

woooee 814 Nearly a Posting Maven

And os.path.isfile(name) will work for a file. Note that name is the full name, so include the full path.

woooee 814 Nearly a Posting Maven

It looks like your problem is here
'+idpracownika+','+a+'kawaler'+a+',0,false)'
You have +idpracownika
+','
+a
+'kawaler'
+a
+',0,false) ## you have to have at least one more (or one less) single quote here
If you create a string and use that, you can then print the string to see if it is accurate
key_str = 'idpracownika,%skawaler%s,0,false' % (a, a) (not sure if this is how you want it though)

woooee 814 Nearly a Posting Maven

I'm still using qt3, but it should be somewhere in the vicinity of this

self.tab_1 = QWidget()
        self.tab_1.setObjectName("Create Tab")
        self.tabs.addTab(self.tab_1, "")
        self.layout.addWidget(self.tabs)
woooee 814 Nearly a Posting Maven

To read the stdout, use communicate(). Take a look at Doug Hellmann's examples here.
http://blog.doughellmann.com/2007/07/pymotw-subprocess.html Also, you can pipe the output to a file (on Linux anyway).

woooee 814 Nearly a Posting Maven

There is not enough code here or enough of the error message to help you. If you are not using a class,

the "self." will yield errors. This is an example using QVBoxLayout that hopefully will help.

#****************************************************************************
#** $Id: lineedits.py,v 1.1 2002/06/19 07:56:07 phil Exp $
#**
#** Copyright (C) 1992-1998 Troll Tech AS.  All rights reserved.
#**
#** This file is part of an example program for PyQt.  This example
#** program may be used, distributed and modified without limitation.
#**
#*****************************************************************************/

import sys
from qt import *

class LineEdits(QGroupBox):
    def __init__(self, parent = None, name = None):
        QGroupBox.__init__(self, 0, Qt.Horizontal, "Line Edits", parent, name)

        self.setMargin(10)
        
        vbox = QVBoxLayout(self.layout())
        
        row1 = QHBoxLayout(vbox)
        row1.setMargin(5)

        label = QLabel("Echo Mode: ", self)
        row1.addWidget(label)

        combo1 = QComboBox(False, self) 
        row1.addWidget(combo1)
        combo1.insertItem("Normal", -1) 
        combo1.insertItem("Password", -1) 
        combo1.insertItem("No Echo", -1)

        self.connect(combo1, SIGNAL("activated(int)"), self.slotEchoChanged)
        self.lined1 = QLineEdit(self)
        vbox.addWidget(self.lined1)

        row2 = QHBoxLayout(vbox)
        row2.setMargin(5)

        label = QLabel("Validator: ", self)
        row2.addWidget(label)

        combo2 = QComboBox(False, self)
        row2.addWidget(combo2)
        combo2.insertItem("No Validator", -1)
        combo2.insertItem("Integer Validator", -1)
        combo2.insertItem("Double Validator", -1)
        
        self.connect(combo2, SIGNAL("activated(int)"), self.slotValidatorChanged)

        self.lined2 = QLineEdit(self)
        vbox.addWidget(self.lined2)

        row3 = QHBoxLayout(vbox)
        row3.setMargin(5)

        label = QLabel("Alignment: ", self)
        row3.addWidget(label)

        combo3 = QComboBox(False, self)
        row3.addWidget(combo3)
        combo3.insertItem("Left", -1)
        combo3.insertItem("Centered", -1)
        combo3.insertItem("Right", -1)

        self.connect(combo3, SIGNAL("activated(int)"), self.slotAlignmentChanged)
        self.lined3 = QLineEdit(self)
        vbox.addWidget(self.lined3)

        row4 = QHBox(self)
        vbox.addWidget(row4)
        row4.setMargin(5)

        QLabel("Read-Only: ", row4)

        combo4 = QComboBox(True, row4)
        combo4.insertItem("False", -1)
        combo4.insertItem("True", -1)

        self.connect(combo4, SIGNAL("activated(int)"), self.slotReadOnlyChanged)

        self.lined4 = QLineEdit(self)
        vbox.addWidget(self.lined4)

        self.lined1.setFocus()

    def slotEchoChanged(self, i):
        if i == 0:
            self.lined1.setEchoMode(QLineEdit.Normal)
        elif i == 1:
            self.lined1.setEchoMode(QLineEdit.Password)
        elif i == 2:
            self.lined1.setEchoMode(QLineEdit.NoEcho)

        self.lined1.setFocus()

    def slotValidatorChanged(self, i):
        if i == …
woooee 814 Nearly a Posting Maven

There are times when pyprocessing is a better choice. Using the queue and jointhread may be another solution, but the specifics are only known by yourself.
http://pyprocessing.berlios.de/

woooee 814 Nearly a Posting Maven

There are various tutorials on the web as well as on python.org . Try one of the tutorials so you can present some code that we can help you with.
http://www.faqts.com/knowledge_base/view.phtml/aid/23158/fid/552

woooee 814 Nearly a Posting Maven

Include a small code snippet that demonstrates what you want (it doesn't have to work, just use descriptive variable names). I think you are talking about passing variables from/to functions, classes, and separate program files, which is done in practically every program written, but a descriptive piece of code would help to clarify.

woooee 814 Nearly a Posting Maven

I think the gadfly maintainer stopped supporting gadfly several years ago. A big criteria for choosing is forums and/or documentation support, which gadfly did not have AFAIK. There are very, very few experts so you will be using them. In any case you want to use SQLite or metakit which is faster.

woooee 814 Nearly a Posting Maven

Use rec.split("*") and then convert the strings to an int and divide by float(100). Remember to round if converting back to a string as floats are not exact. Or you can use slice[:-2] to get everything except the last 2 digits and [-2:] to get only the last 2, and then add the decimal point but that would be the long way around.

woooee 814 Nearly a Posting Maven

Use a for loop to read the first 20 recs into a list, we'll call it move_list, and then remove the first item each time you read a new rec. With only 20 values you don't have to be too concerned about memory use or processing time, something like this (untested)

move_list = []
data=""
for j in range(0, 20):
   data = fp.readline()
   split_fields = data.split()
   move_list.append(split_fields[appropriate_one])
while data:
   ## sum and average the values of the list before changing
   sum_ave = 0
   for value in move_list:
      sum_ave += float(value)
   print "the moving average is", sum_ave/float(20), move_list

   del move_list[0]
   data=fp.readline()
   split_fields = data.split()
   move_list.append(split_fields[appropriate_one])
woooee 814 Nearly a Posting Maven

I get no returned rows. I use the following SQL code to query:
SELECT * FROM fdi.fdiresults;

fdi.fdiresults seems odd for a table name. Try "SELECT tablename FROM pg_tables where tablename not like 'pg_%'" and see what it gives you for a table name. (Note that semicolons are not used in Python.) I am not familiar with PostGIS, but generally a select statement is more like 'cur.execute( "SELECT * FROM tablename")'.

PoovenM commented: Thank you for the tip :) +2
woooee 814 Nearly a Posting Maven

Pypy is the faster Python. I have never tried it though. http://codespeak.net/pypy/dist/pypy/doc/home.html

woooee 814 Nearly a Posting Maven

Something like the following is a simple example and usually works. If not, then you will have to Google for your specific sendmail app.

fromaddr = "<me@localhost>"                                            
toaddrs  = "<you@localhost>"
msg = "Test of Python's sendmail\n"
                                                                                
# The actual mail send part                                
server = smtplib.SMTP('localhost')                                       
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
print server.verify( toaddrs )
server.quit()
woooee 814 Nearly a Posting Maven

Putting a quote around the field name works with SQLite. I don't know about MS Access. This is the well known example that has been changed to use a field name with a space in it (always a bad idea).

import sqlite3 as sqlite

##----------------------------------------------------------------------
def add_rec(cur, con):
   cur.execute("INSERT INTO test ('name last', age) values ('Putin',   50)")
   cur.execute("INSERT INTO test ('name last', age) values ('Putin',   50)")
   cur.execute("INSERT INTO test ('name last', age) values ('Putin',   50)")
   cur.execute("INSERT INTO test ('name last', age) values ('Yeltsin',   72)")
   cur.execute("INSERT INTO test ('name last', age) values ('Baby',   1)")

   con.commit()

#==========================================================================
if __name__ == "__main__":
   con = sqlite.connect("test_db" )
   cur = con.cursor()

##--- Note: 'name last'
   cur.execute("CREATE TABLE test ('name last' VARCHAR(20), age INT)")

   add_rec(cur, con)           ## add some recs

   cur.execute('SELECT * FROM test')
   for row in cur:
      print "name =", row[0], " age =", row[1]
   
   print "select test"
   cur.execute('SELECT age FROM test where "name last"="Yeltsin"')
   for row in cur:
       print row
woooee 814 Nearly a Posting Maven

The reason SchoolMember's __init__ is called to define self.name=name and self.age=age. You could also do this in the Teacher and Student classes. It doesn't matter where it happens as SchoolMember is inherited. I have changed the Student class to illustrate.

#!/usr/bin/python
# Filename: inherit.py

class SchoolMember:
	'''Represents any school member.'''
	def __init__(self, name, age):
		self.name = name
		self.age = age
		print '(Initialized SchoolMember: %s)' % self.name
	
	def tell(self):
		'''Tell my details.'''
		print 'Name:"%s" Age:"%s"' % (self.name, self.age),

class Teacher(SchoolMember):
	'''Represents a teacher.'''
	def __init__(self, name, age, salary):
		SchoolMember.__init__(self, name, age)
		self.salary = salary
		print '(Initialized Teacher: %s)' % self.name

	def tell(self):
		SchoolMember.tell(self)
		print 'Salary: "%d"' % self.salary

class Student(SchoolMember):
	'''Represents a student.'''
	def __init__(self, name, age, marks):
                  ##SchoolMember.__init__(self, name, age)
                  self.name = name
                  self.age = age
                  self.marks = marks
                  print '(Initialized Student: %s)' % self.name
	
	def tell(self):
		SchoolMember.tell(self)
		print 'Marks: "%d"' % self.marks

t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)

print # prints a blank line

members = [t, s]
for member in members:
	member.tell() # works for both Teachers and Students
woooee 814 Nearly a Posting Maven

This might be easier to understand (not tested). This is not as efficient as storing the value as you perform one additional split() per record instead of storing it, but it may be more straight forward.

import math

data = open(filename, "r").readlines()   ##  reads entire file into list
stop=len(data)
daily_list=[]
for ctr in range(1, stop):     ## start with the second record
    current_list = data[ctr].split()
    prev_list =data[ctr-1].split()
    daily_returns = log(current_list[1] - prev_list[1])
    daily_list.append(daily_returns)
print daily_list
woooee 814 Nearly a Posting Maven

It is a good idea to insure that there is no white space in any of the records, so you should include
rec = rec.strip()
then you can use

substrs=rec.split()
substrs[0] = substrs[0].upper()
if (substrs[0].startswith("MM")) or (substrs[0].startswith("HS"):
woooee 814 Nearly a Posting Maven

You can also convert a1 and a3 to a set and use set intersection and difference.

woooee 814 Nearly a Posting Maven

Which GUI toolkit are you using?

woooee 814 Nearly a Posting Maven

You can print the variables named operation, difficulty, etc. You will have to declare them first before the if statements, otherwise they only exist within the if statement's code block.
print "\t\t\tWelcome to my Mathematics Game"
operation=""
difficulty=""

Also instead of
if difficulty == "Easy" or difficulty == "easy" or difficulty == "E" or difficulty == "e":
you can use
difficulty = difficulty.lower()
if difficulty.startswith("e"):
As long as there are no other words for difficulty that start with "e".

woooee 814 Nearly a Posting Maven

Python also has smtplib if you are referring to e-mail messages.

woooee 814 Nearly a Posting Maven

The list has to be in order, so sort it as the first statement in the function

def binarySearch(list1,faces):
    list1.sort()
    first = 0
    last = len(list1) - 1
    while first <= last:
        mid = (first + last) / 2
        if faces == list1[mid]:
            return mid
        elif faces < list1[mid]:
            last = mid - 1
        else:
            first = mid + 1
    return -1
woooee 814 Nearly a Posting Maven

Try running everything after "if name[-4:] == ".tif":" in a separate function. The memory should be garbage collected when the function exits.

woooee 814 Nearly a Posting Maven

If you are using raw_input or the variable is already a string, then try isdigit(). This of course assumes that you aren't using floating point numbers. If you are then you will have to use a try/except converting the string to a float.

get_num=raw_input("Enter a number ")
print get_num,
if get_num.isdigit():
   if int(get_num) > 0:
      print "is integer and is positive"
   else:
      print "is integer and is NOT positive"
## this will never execute since a minus sign, "-", is not a digit
else:
   print "is NOT a number"
woooee 814 Nearly a Posting Maven

Also, take a look at pyprocessing which will run each in a separate process. http://developer.berlios.de/projects/pyprocessing

woooee 814 Nearly a Posting Maven

Yes, m is a pointer to the class so could not be passed. Perhaps an explaination of what you are trying to do would help. There may be other solutions.

woooee 814 Nearly a Posting Maven

Sorry, I misunderstood. The only way I know of is to pass it as an arg to the script being executed. Something like:
subprocess.call( 'program_name m', shell=True)
The program being executed would have to examine sys.argv to find it.

woooee 814 Nearly a Posting Maven

Pass m to the second script as a function parameter or to the __init__() function of the class. If that doesn't do what you want, post back.

m = Mine(2,3)
m.PrintMe()
m.ChangeMe(10,11)
m.PrintMe()

#Call to script SecondaryScript here.... 
SecondaryScript.foo(m)
SecondaryScript.ClassFoo(m)
woooee 814 Nearly a Posting Maven

the list being [23, 764, 12, 54, 83, 2, 543, 890, 1235, 453, 98]

The easiest to understand is to use three new lists. In some kind of loop, append the first number to list1, the second to list2 and the third to list3. Rinse and repeat until the end. Then print the lists on separate lines.

woooee 814 Nearly a Posting Maven

You can use a while loop if you prefer

list2 = [23, 764, 12, 54, 83, 2, 543, 890, 1235, 453, 98] 
 
stop = len(list2)
ctr = 0
while ctr < stop:
   print "%-5d " % (list2[ctr]),
   ctr += 1
   if 0 == ctr % 3:   ## new line
      print 
print
woooee 814 Nearly a Posting Maven

Here is a link on how to import modules from the Dive Into Python online book http://www.diveintopython.org/object_oriented_framework/importing_modules.html An online tutorial or book is a good way to start learning. When you just copy something and screw it up, you have no idea what to do, so the place to begin is with a step by step instruction that you understand.

woooee 814 Nearly a Posting Maven

First
while list2[k] != -1:
will never exit because -1 is not in list2 so you will always exceed the limits of the loop. Generally, this is done with a for loop.

list2 = [23, 764, 12, 54, 83, 2, 543, 890, 1235, 453, 98] 
 
stop = len(list2)
for k in range(0, stop, 3):   ## step=3
   for m in range(0,3):        ##  print 3 per line
      this_el = m+k            ##  k + 0-->2 = this element in list2
      if this_el < stop:
##                minus 5d=left justified
         print "%-5d " % (list2[this_el]),   ## note the comma at the end
   print                                          ## new line
woooee 814 Nearly a Posting Maven

First, you have a function to check the pin, but never ask for one. Also, you have to have some amount of money on file for known pins, so there has to be a dictionary or whatever that keeps track of the pin and the balance for that pin so you can print statements.

woooee 814 Nearly a Posting Maven

You can also use rfind to find the rightmost "-", which returns the location of the character. A slice using this location+1 will give you the string after the final "-", and you can use isdigit to tell if there are alpha characters.

def numbers_only(str_in):
   new_str=""
   if False == str_in.isdigit():
      for chr in str_in:
         if not chr.isdigit():
            return new_str    ## exit on first alpha character
         new_str += chr
   else:
      new_str = str_in
   return new_str

data='115Z2113-3-777-55789ABC7777'
x = data.rfind("-")
end_str = data[x+1:]

new_str = numbers_only(end_str)
print "new_str =", new_str
woooee 814 Nearly a Posting Maven

Try one of the online books or tutorials. This is a link to the "Dive Into Python" chapter on string formatting http://diveintopython.org/native_data_types/formatting_strings.html