Gribouillis 1,391 Programming Explorer Team Colleague

It's very simple, when you write a 2nd order equation as a first order system, the technique is to introduce the vector (u, v) = (u, u') and to compute its derivative. You have (u, v)' = (u', v') = (v, u"). Now you replace u" by (1/m)(F(t) - f(u') - s(u)). Now, f(u') = f(v) because u'=v, and finally you get (u, v)' = (v, (1/m)(F(t) - f(v) - s(u))).
When you program this, you replace the vector (u,v) by a list u = [u[0], u[1]], and the right hand side is the list [u[1], (1/m)*(F(t) - f(u[1]) - s(u[0])]. Note that this expression of the second order equation as a first order system comes before any numerical scheme is applied. It's pure theory. The hard part is the Runge Kutta method which you have to implement on the system !

Gribouillis 1,391 Programming Explorer Team Colleague

I don't think it's possible. The normal way to do this is to create your own subclass of str like this

class mystr(str):
  def __new__(cls, *args):
    return str.__new__(cls, *args)
  def findAll(self, other):
    print("Couldn't find '%s' in '%s'!" % (other, self))

if __name__ == "__main__":
  s = mystr("Hello world")
  s.findAll("Hi")

It's a good solution because your class will behave much like the str class and can be used in functions which use a str. For example, you can pass a mystr to open, etc...

shadwickman commented: Great idea to create my own str class! +2
Gribouillis 1,391 Programming Explorer Team Colleague

It looks like a tuple which first element is a dict. Try Results[0]["Free"]

Gribouillis 1,391 Programming Explorer Team Colleague

What is the output of print(Results) ?

Gribouillis 1,391 Programming Explorer Team Colleague
from urllib2 import urlopen
data = urlopen("http://internetaddress.com/file.txt").read()
Gribouillis 1,391 Programming Explorer Team Colleague

I don't know Jython, but looking at this org.python.proxies.main$ballCollisionListener$0.<init>(Unknown Source) , it seems that java tries to execute the python call __main__.ballCollisionListener.__init__() . Are you sure that you imported the name ballCollisionListener the right way ?

Gribouillis 1,391 Programming Explorer Team Colleague

It means that one of the modules which you're using, directly or indirectly, tries to import a module name 'main' and can't find it. Do you have a more complete exception traceback ?

Gribouillis 1,391 Programming Explorer Team Colleague

For a french version of the game, this site http://www.pallier.org/ressources/dicofr/dicofr.html gives a text file of 336531 french words :)

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a random word generator for this dictionary file

from os.path import getsize
from random import randint

dic_path ="DictionaryE.txt"
file_size =getsize (dic_path )
file_in =open (dic_path ,"rb")

def random_word ():
  while True :
    offset =randint (0 ,file_size )
    file_in .seek (offset )
    L =file_in .read (25 ).split ("\r\n")
    if len (L )>2 :
      return L [1 ]

if __name__ =="__main__":
  n =100
  print "%d randomly generated words"%n
  for i in xrange (n ):
    print random_word (),
  print
  file_in .close ()

Note that the file is opened but not read in memory. Only 25 characters are read at a time when a random word is requested.

Gribouillis 1,391 Programming Explorer Team Colleague

Sorry, there is a syntax error in the code above. You should replace

@staticmethod readCtrl(ctrl):

by

@staticmethod
    def readCtrl(ctrl):

However, since the code is untested, it's most likely broken, but I think in principle it should store your tree control on the disk and back after you kill a few bugs :)

Gribouillis 1,391 Programming Explorer Team Colleague

I would suggest something like this, with the pickle module (completely untested)

import pickle

class Tree(object):
  # a tree class, with a single root (a Node object)
  def __init__(self):
    self.root = None
  def fillCtrl(self, ctrl):
    # fills an empty wx.TreeCtrl (ctrl) with the content of the tree structure
    if self.root is None:
      return
    root_item = ctrl.AddRoot(self.root.text)
    self.root.fillCtrl(ctrl, root_item)
  def dump(self, file):
    # writes the tree structure to a file using the pickle protocol
    pickle.dump(file, self)
  @staticmethod
  def load(file):
    # creates a new Tree which content is read in a file
    return pickle.load(file)
  @staticmethod readCtrl(ctrl):
    # creates a new Tree from the content of a wx.TreeCtrl
    self = Tree()
    item = ctrl.GetRootItem()
    self.root = Node()
    self.root.text = ctrl.GetItemText(item)
    self.root.readCtrl(ctrl, item)
    return self
    
class Node(list):
  # A class for nodes of Tree objects. Each node is a list which elements are
  # the subnodes
  def __init__(self):
    list.__init__(self)
    self.text = ""
  def fillCtrl(self, ctrl, parent_item):
    # fills a wx.TreeCtrl with items corresponding to the descent of this node
    for child in self:
      item = ctrl.AppendItem(parent_item, child.text)
      child.fillCtrl(ctrl, item)
  def readCtrl(self, ctrl, item):
    # creates the descent of this node from the content of a wx.TreeCtrl item
    child_item = ctrl.GetFirstChild(item)
    if child_item[0]:
      child_item = child_item[0]
    else:
      return
    while True:
      self.append(Node())
      self[-1].text = ctrl.GetItemText(child_item)
      self[-1].readCtrl(ctrl, child_item)
      child_item = ctrl.GetNextSibling(child_item)
      if not child_item:
        break


def dumpCtrl(ctrl, file):
  # Dumps the content of a wx.TreeCtrl to a opened file
  tree = Tree.readCtrl(ctrl)
  tree.dump(file)
  
def loadCtrl(ctrl, file):
  # loads a file containing the content of a wx.TreeCtrl …
Gribouillis 1,391 Programming Explorer Team Colleague

I suggest a generator

def find_text(element):
    if element.text is None:
        for subelement in element:
            for txt in find_text(subelement):
                yield txt
    else:
        yield element.text

for txt in find_text(root):
    print txt
Gribouillis 1,391 Programming Explorer Team Colleague

this way

mylist = ["whatever"] * 100
Gribouillis 1,391 Programming Explorer Team Colleague

I cleaned up your code a while. Here is a code that runs. Compare the details with your version to understand how it works.

#!/usr/bin/env python

import random

class monster(object):
    def __init__(self, attack, health, defense, name):
        self.attack = attack
        self.health = health
        self.defense = defense
        self.name = name

    def GetAttributesInfo(self):
        attributes = ['Name: %s' % self.name,
        'Health: %d' % self.health,
        'Attack: %d' % self.attack,
        'Defense: %d' % self.defense]
        return ', '.join(attributes)

class orc(monster):
    def __init__(self):
        monster.__init__(self, 3, 10, 3, 'Orc')

    def GetAttributesInfo(self):
        return monster.GetAttributesInfo(self)

class troll(monster):
    def __init__(self):
        monster.__init__(self, 5, 20, 5, 'Troll')

    def GetAttributesInfo(self):
        return monster.GetAttributesInfo(self)

class weapon(object):
    def __init__(self, attack, name):
        self.attack = attack
        self.name = name
        
    def GetAttributesInfo(self):
        attributes2 = ['Attack: %d' %  self.attack,
        'Name: %s' % self.name]
        return ', '.join(attributes2)

class sword(weapon):
    def __init__(self):
        weapon.__init__(self, random.randrange(1,5), 'Sword')

    def GetAttributesInfo(self):
        return weapon.GetAttributesInfo(self)

class axe(weapon):
    def __init__(self):
        weapon.__init__(self, random.randrange(1,7), 'Axe')

    def GetAttributesInfo(self):
        return weapon.GetAttributesInfo(self)

class player():
    def __init__(self):
        self.alive = True
        self.health = 30
        self.damage = 5
        choice = random.randrange(1,2)
        if choice == 1:
            self.weapon = sword()
        else:
            self.weapon = axe()
        print self.weapon.GetAttributesInfo()
    
    def attack(self, monster):
        #if not self.attacking == 1: ?
        #    self.attacking = 1 ?
        if self.weapon.attack > monster.defense:
            print 'You hit him for %d damage!' % self.damage
        if self.weapon.attack < monster.defense:
            print 'You did\'nt do any damage...'

def main():
    new_monster = random.randrange(1,2)
    if new_monster == 1:
        new_monster = orc()
    elif new_monster == 2:
        new_monster == troll()
    P = player()
    P.attack(new_monster)

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

Also, your methods getAttribute info in troll and orc return None instead of what they should return. You shoud write

def getAttributeInfo(self):
        return monster.getAttributeInfo(self)
Gribouillis 1,391 Programming Explorer Team Colleague

You must not call sword.getAttributeInfo2() because sword is a class and getAttributeInfo2 is an instance method. It applies to an instance (an object). Here, your sword object is self.weapon, so you should write print self.weapon.getAttributeInfo2()

Gribouillis 1,391 Programming Explorer Team Colleague

If you want to test code, I gave an example of how you could do this with doctest, here http://www.daniweb.com/forums/thread146672.html
Programming with tests is a very efficient method.

Gribouillis 1,391 Programming Explorer Team Colleague

An alternative to changing the method's name is this

class Troll(Monster):
    def getAttributesInfo(self):
        Monster.getAttributesInfo(self)

It's a standard way of overloading a method in python: the method in the derived class calls the method with the same name in the parent's class. This allows you to define troll-specific behaviour in the derived class method.

Gribouillis 1,391 Programming Explorer Team Colleague

I installed the program pdftk (on my linux distribution, it was a package). I think you can be interested in this little script

import os
from os.path import join as pjoin, expanduser
import subprocess
from pprint import pprint

directory = expanduser("~/MyPdfs")

for name in os.listdir(directory):
  if name[-4:] == ".pdf":
    p = pjoin(directory, name)
    child = subprocess.Popen("pdftk %s dump_data output" % p, shell=True,
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    sout, serr = child.communicate()
    if serr:
      print p
      print(serr)
    else:
      D = dict((t[0].strip(), t[1].strip()) for t in
                     (t.split(":") for t in sout.split("\n")[:-1]))
      pprint(D)
Gribouillis 1,391 Programming Explorer Team Colleague

Try this

for line ...
    if other_date ...
        ...
        more_logs = open(..., "w")
        try:
            new_log_data ...
            for line_data ...
                ...
                more_logs.write(new_data)
        finally:
            more_log.close()
Gribouillis 1,391 Programming Explorer Team Colleague

A nice way is to use an exception. An exception allows you to exit the game at any moment, for example you could write this

class RestartException(Exception):
    pass

class QuitException(Exception):
    pass

def askUser():
    # somewhere deep inside the game
    s = raw_input("do you want to restart ?")
    if s == "yes":
        raise RestartException
    elif s == "quit":
        raise QuitException

def main():
    do_play = True
    while do_play:
        do_play = False
        try:
            game = Game() # initializes the game
            game.run()
        except RestartException:
            do_play = True
        except QuitException:
            print "Thank you for playing!"

main()
Gribouillis 1,391 Programming Explorer Team Colleague

this one just swaps the list elements

import random

let = list("abcdefg")

n = len(let)
for j in xrange(3):
    n -= 1
    i = random.randint(0, n)
    print let[i],
    let[i], let[n] = let[n], let[i]
print
Gribouillis 1,391 Programming Explorer Team Colleague

there is also random.choice(let) which would choose a random element of your list instead of choosing a random index. After that, use del let[pos].

Gribouillis 1,391 Programming Explorer Team Colleague

Did you try to insert explicitely the path to your directory instead of calling os.path.abspath ? Also, could you print sys.path and put this in a post, together with the path to your programs ?

Gribouillis 1,391 Programming Explorer Team Colleague

If you read a PDF document in a viewer, and you want to know the number of pages (assuming the browser doesn't tell you), a good way is to go directly read the page number on the last page. You could try to read only the end of the file, using the method seek of file objects.

Gribouillis 1,391 Programming Explorer Team Colleague

yes, sys.executable .

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest this

from glob import glob as __g
import re
pattern = re.compile(r"/Count\s+(\d+)")

def count(vPath):
    """
    Takes one argument: the path where you want to search the files.
    Returns a dictionary with the file name and number of pages for each file.
    """
    vPDFfiles = __g( vPath + "\\" + '*.pdf' )
    vMsg = {}
    for vPDFfile in vPDFfiles:
        vPages = 0
        content = open( vPDFfile, 'rb', 1 ).read()
        for match in pattern.finditer(content):
            vPages = int(match.group(1))
        vMsg[vPDFfile] = vPages
    return vMsg

The main difference is that I compile the pattern once for all, and I dont read the files line by line. Tell me if it works, and how faster it is !

Prahaai commented: :) +4
Gribouillis 1,391 Programming Explorer Team Colleague

You should try to print sys.path to check that it contains the folder of your python library .../lib/python2.5 (and not another python library if you have different pythons). Also directories are searched in the order where they appear in sys.path. So if you want to be sure that a directory is reached first, you can use sys.path.insert(0, "directory") instead of sys.path.append

Gribouillis 1,391 Programming Explorer Team Colleague

You can try to set the environment variable PYTHONPATH to the directory which contains mytest.py. Otherwise, attach your files to a post, and also try to import just the module 'site' to see if this works.

Gribouillis 1,391 Programming Explorer Team Colleague

On my system the python library are here

/usr/lib/python2.5/config/libpython2.5.a
/usr/lib/python2.5/config/libpython2.5.so

check that there is a 'config' directory in your .../lib/python2.5 and link with the library that it contains. Also I suppose that you have different versions of python, so without the Py_SetProgramName, it loads the wrong version of python. Also the documentation says that if there is an environment variable PYTHONHOME, it overrides the call to Py_SetProgramName, so you should remove this variable in that casse. Finally, you say it fails, but is there an error message ? (never say it fails without describing how it fails) :)

Gribouillis 1,391 Programming Explorer Team Colleague

No the program name in the Py_SetProgramName must be the path of the 'python' executable ! I mean something like /usr/local/bin/python , or wherever your python 2.5 command is.

Gribouillis 1,391 Programming Explorer Team Colleague

It's strange that the "import site failed" reappeared. Did you remove the Py_SetProgramName ?

Gribouillis 1,391 Programming Explorer Team Colleague

It means that python fails to compute test.transform . There must be an error in your python file.
Try to add this

PyRun_SimpleString ("print test.__file__");

before the other print, to check from which file your module test was imported. I think there is a predefined module test, so you should probably rename your program "mytest.py" for example.

Gribouillis 1,391 Programming Explorer Team Colleague

You said the error is now 'module' object has no attribute ..., but what's the attribute ?

Gribouillis 1,391 Programming Explorer Team Colleague

Here is the documentation of the site module if you want to understand it's role. However, it's not really important as long as python doesn't complain anymore http://www.python.org/doc/2.5.2/lib/module-site.html.

Gribouillis 1,391 Programming Explorer Team Colleague

Note that the code in the body of the function transform should be indented. Also, I think it's quite a challenge to begin with python from it's C API. You should experiment with pure python code too :)

Gribouillis 1,391 Programming Explorer Team Colleague

From the documentation of Py_Initialize(), I think it would be a good idea to try

Py_SetProgramName("path to the python executable");

before the call to Py_Initialize. Also check that your python 2.5.2 library contains a file site.py.

Gribouillis 1,391 Programming Explorer Team Colleague

There are many ways to avoid all the global declarations in your program, for example you could put this at the top of your program

class var(object):
    shoes = 0
    underwear = 0
    bottoms = 0
    tops = 0
    bags = 0
    # etc

Then in the rest of the code, you could use var.shoes = 2 for example. This would drop all the global declarations from your program.

Gribouillis 1,391 Programming Explorer Team Colleague

Don't use item after the selection=... . in this expression, item varies from the first element to the last element of the list. You can use selection , which is a list of all the tuples in tuplelist which first element is word. You could obtain a list of indexes instead, like this

indexlist = [ i for i in xrange(len(tuplelist)) if tuplelist[i][0] == word]
Gribouillis 1,391 Programming Explorer Team Colleague

You could use this, if you want to access the tuples

# select the tuples which first element is word
selection = [item for item in tuplelist if item[0] == word]
if selection:
    print word, "was found!"
    print selection
else:
   print word, "was not found"

However, a more efficient way to do this would be to use dictionaries.

Gribouillis 1,391 Programming Explorer Team Colleague

Similarly, calls to LoadAccounts should be replaced by cursor.state = "UserDeleteAccess"

Gribouillis 1,391 Programming Explorer Team Colleague

You must not import SystemMenu in the other files (if A import B, then B should not attempt to import A), so you can't directly call MainMenu from the other files. What you should do is replace calls to MainMenu by a change of state

def ExitToMenu(cursor):
    cursor.state = "SystemMenu"
Gribouillis 1,391 Programming Explorer Team Colleague

In this menu program, you're programming an automaton in fact. This automaton has nodes which represent states where your system can be, these states are "SystemMenu", "UserAccess", "UserDeleteAccess", "Exit". When you're in one of these states, a callback function is called to show a menu and then move to a new state (technically, this is called a transition). These functions are "MainMenu", "NewAccount", "Menu", "LoadAccounts", and a function should be added for the "Exit" state.

You should avoid using mutliples execfiles. The good way to access multiple python programs in an application is to use the import statement. You should also avoid calling recursively your callback functions, which obfuscates the program.

A better desing would be to have a cursor which remembers the state where your system is and calls the appropriate callback function. This function in turn can change the cursor state and return. A loop will be the engine for the automaton. Here is how you could write this

#  file SystemMenu.py
import UserAccess
import UserDeleteAccess

def MainMenu(cursor):
    ...
    if Choice == '1':
        cursor.state = "UserAccess"
    elif Choice == '2':
        cursor.state = "UserDeleteAccess"
    elif Choice == '3':
        cursor.state = "Exit"
    else:
        print ...
        cursor.state = "SystemMenu"

def ExitCallback(cursor):
    sys.exit(0)

class Cursor(object):

    callbacks = {
        "SystemMenu" : MainMenu,
        "UserAccess": UserAccess.NewAccount,
        "UserDeleteAccess": UserDeleteAccess.LoadAccounts,
        "Exit": ExitCallback,
    }
    def __init__(self):
        self.state = "SystemMenu"

    def mainloop(self):
        # the 'engine' loop
        while True:
            # call the function corresponding tu the cursor's state
            self.callbacks[self.state](self)

cursor = Cursor()
cursor.mainloop()

In the other files, …

Gribouillis 1,391 Programming Explorer Team Colleague

A shorter code using module bisect

from bisect import bisect_left

costs =  [0.0, 2.10, 3.20, 4.70, 4.80]
weights = [0, 2, 6, 10]

def shipping_charges(package_weight):
    return costs[bisect_left(weights, package_weight)]

print 'Welcome to Shipping Company Rate Calculator'

while True:
    shipweight=raw_input ('Please Enter the Weight of the Item You Wish To Ship: ')
    if shipweight == "quit":
        break
    try:
        weight_package = float(shipweight)
        charges = shipping_charges(weight_package)
        print "Your total shipping charges: %.2lf" % charges
    except:
        print "You can only enter a number (or 'quit')"
vegaseat commented: great suggestion +10
Gribouillis 1,391 Programming Explorer Team Colleague

What the re module gives you is 1) A language, the regular expression language which can express patterns like "the word foo followed by any sequence of characters followed by the word bar", and more complex patterns, 2) A compiler which understands such a pattern and produces optmized code for searching the pattern in a string. This code is contained in the regular expression objects, 3) Methods to use this code for searching the occurrences of the given pattern in any string, and also to modify the string according to arbitrary rules that you would define when the pattern is found, etc

Gribouillis 1,391 Programming Explorer Team Colleague

This is so because of the history of the python language. In the early versions of python, classes were defined using class A: . Then the implementation of python objects changed, mainly so that users could define subclasses of the builtin types like int, str, dict, list, etc.The 'new style' classes appeared and were defined using class A(object) . The first kind of definition was kept so that old python code could still run. You should always use new style classes in your code (some properties of the old style objects differ from the others)

Gribouillis 1,391 Programming Explorer Team Colleague

I'm surprised that nobody suggests to use the re module, like this

import re

sentence = raw_input("Please type a sentence: ")
first = raw_input("Please type the first word to find: ")
last = raw_input("Please type the last word to find: ")

pattern = re.compile(
    "%s(.*)%s" % (re.escape(first), re.escape(last)),
    re.DOTALL
    )

match = pattern.search(sentence)
if match is None:
    print "The sentence does not contain '%s...%s'" %(first, last)
else:
    print "found: %s" % match.group(1)

The re module is a very powerful tool for searching and modifying strings.

Gribouillis 1,391 Programming Explorer Team Colleague

A good way to do this is to have a folder for your python modules and to set the environment variable PYTHONPATH to contain this folder. If you're on windows, search for environment variables in windows help and set the correct value. In this folder, you can create files like myModule.py and then use import myModule in all your python programs. You can also define subfolders like anotherModule which must contain a (possibly empty) file __init__.py and other python files like myProgram.py . You can then use import statements like import anotherModule.myProgram . Also, start reading this http://www.python.org/doc/2.5.2/tut/node8.html in the python tutorial.

Gribouillis 1,391 Programming Explorer Team Colleague

if D is a dictionary a code like

for x in D:
    print x

will print only the keys of the dictionary. If you wnat the keys and values, you should write

for k, v in D.iteritems():
    print k, v
Gribouillis 1,391 Programming Explorer Team Colleague

The problem is that the argument to eval must be an expression, while "print 'I hate Hippies'\n" is a statement. You can exec statements :)