Gribouillis 1,391 Programming Explorer Team Colleague

Hm ''.join(the_list).split()

Gribouillis 1,391 Programming Explorer Team Colleague

Here is how you can find which variables are None

missing_list = [ i for (i, z) in enumerate((v, u, a, t)) if z is None ]

This returns a sublist of [0, 1, 2, 3] with the indexes of the variables equal to None.

Gribouillis 1,391 Programming Explorer Team Colleague

I don't think BeautifulSoup will work as it loads the whole parse tree. I'm not sure it can be avoided.

Gribouillis 1,391 Programming Explorer Team Colleague

Also notice that you could perhaps obtain better performance for the previous code by reading larger chunks of data at a time (say 100 KB or 1 MB), because the previous code reads line by line. Here are the necessary changes

from adaptstrings import adapt_as_opener

CHUNK = 2 ** 17 # 128 KB

@adapt_as_opener
def source(filename, mode='r'):
    yield PREFIX
    with open(filename, mode) as ifh:
        while True:
            s = ifh.read(CHUNK)
            if s:
                yield s
            else:
                break
    yield SUFFIX

p.ParseFile(source("dups.xml"))
Gribouillis 1,391 Programming Explorer Team Colleague

As your data file looks like xml, I obtained some results very easily using module xml.parsers.expat. Here is the code. It uses this code snippet adaptstrings http://www.daniweb.com/software-development/python/code/389929 (this could be optimized later).

from itertools import chain
from adaptstrings import adapt_as_file
import xml.parsers.expat

PREFIX = "<document>\n"
SUFFIX = "</document>\n"

def byte_index(p):
    return p.CurrentByteIndex - len(PREFIX)

class glo:
    IN_ID = False

# 3 handler functions
def start_element(name, attrs):
    if name in ('tag', 'id'):
        print '<%s>' % name, attrs,"at byte", byte_index(p)
    if name == 'id':
        glo.IN_ID = True
def end_element(name):
    if name in ('tag', 'id'):
        print '</%s>' % name, "at byte", byte_index(p)
    if name == 'id':
        glo.IN_ID = False
def char_data(data):
    if glo.IN_ID:
        print 'Data:', repr(data)

p = xml.parsers.expat.ParserCreate()

p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data

p.ParseFile(adapt_as_file(chain((PREFIX,), open("dups.xml"), (SUFFIX,))))

""" my output -->

<tag> {} at byte 0
<id> {} at byte 121
Data: u'32444'
</id> at byte 130
</tag> at byte 165
<tag> {} at byte 172
<id> {} at byte 289
Data: u'32344'
</id> at byte 298
</tag> at byte 340
<tag> {} at byte 347
<id> {} at byte 493
Data: u'32444'
</id> at byte 502
</tag> at byte 537
"""

The file "dups.xml" contained the exact data that you wrote above. As you can see, the parser gives the byte position in the file where the relevant tags are found. It can also give the line and column numbers. This code is only a first draft, but it could be a reasonable starting point.

Gribouillis 1,391 Programming Explorer Team Colleague

I'll fiddle some more tomorrow. but this looks like a good, "proper" way to pass and parse arguments. Thanks again

Don't miss this page if you are going to use optparse http://www.alexonlinux.com/pythons-optparse-for-human-beings .

Gribouillis 1,391 Programming Explorer Team Colleague

An improvement would be to use the argparse module to handle the command line. It would be especially useful to learn if you need to write a lot of scripts.

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

Indent the last 2 lines to put them in the while's body.

Gribouillis 1,391 Programming Explorer Team Colleague

I think there are a lot of misconceptions about classes in your approach.

First, a more accurate name for class Person would be MinimalDataThatThisProgramNeedsToStoreAboutAPerson. It means that the purpose of a class Person is not to mimic a person from the real world but to provide some space in memory to handle some data relative this person. For example this program stores the person's name but not the person's parents names or date of birth because it does not need it. The argument that 'it is more natural' to do such or such way should not be pushed too far. The important question is 'what does this program need'.

Second, classes are a way of factorizing data, because all the instances can access the class members. It means that data common to all people are good candidates to be stored in the class object.

Third, storing instances in a container is common, but it is very different from storing the number of instances. The reason is that stored instances don't disappear unless there are removed from the container or the container is destroyed. Instances often have a short life. For example an instance may be created as a local variable in a function and it disappears when the function returns. Such temporary instances should not be stored. If your program only needs the number of instances created, don't store instances because you think that 'it is more natural'.

For your first question you can check the …

HiHe commented: very helpful +5
Gribouillis 1,391 Programming Explorer Team Colleague

To understand more about closures, study this code which shows that python creates an object called a 'cell' for each closure, this cell contains the variable's value, but 2 functions created in the same scope share the same cells.

def f():
    date = "Monday"
    def g():
        return date
    print "g:", g.__closure__
    date = "Tuesday"
    def h():
        return date
    print "g:", g.__closure__
    print "h:", h.__closure__
    return g, h
        
print "first call"
g, h = f()
print "second call"
g, h = f()

print g.__code__.co_freevars

""" my output -->
first call
g: (<cell at 0x7fe6970616a8: str object at 0x7fe697062e40>,)
g: (<cell at 0x7fe6970616a8: str object at 0x7fe697062e70>,)
h: (<cell at 0x7fe6970616a8: str object at 0x7fe697062e70>,)
second call
g: (<cell at 0x7fe6970617f8: str object at 0x7fe697062e40>,)
g: (<cell at 0x7fe6970617f8: str object at 0x7fe697062e70>,)
h: (<cell at 0x7fe6970617f8: str object at 0x7fe697062e70>,)
('date',)
"""
Gribouillis 1,391 Programming Explorer Team Colleague

This is Cython code. It seems to be a version of Prahaai's pure python code here http://www.daniweb.com/software-development/python/threads/152831. See if the pure python version works.

Also notice that a pyPdf module exists here http://pybrary.net/pyPdf/ . Here is an example code to count the pages in a pdf file with python 2 and pyPdf (a python 3 compatible version seems to exist as well).

from pyPdf import PdfFileReader

reader = PdfFileReader(open("ginac_tutorial.pdf"))
print reader.getNumPages()

""" my output -->
124
"""
Gribouillis 1,391 Programming Explorer Team Colleague

Hm, try this

outstr = "\n".join("\t".join(str(i*j) for j in range(1, 13)) for i in range(1, 13))
print outstr
vegaseat commented: wow +15
Gribouillis 1,391 Programming Explorer Team Colleague

As a follow up, can anyone point me to a resource that explains why Tkinter/Python behaves like this?

The reason is that when you write

action = lambda x = date: createEvent(x)

the value of the variable 'date' is stored in the anonymous function 'action' and reused when this function is called. On the other hand, when you write

f = lambda: createEvent(date)
...
g = lambda: createEvent(date)

then f and g both use the same variable date. More precisely, they use something that is called the closure of the variable. It means the variable in a given execution frame (which is the same here for f and g).

The best solution is to use curryfication

from functools import partial
action = partial(createEvent, date)

Here again, the value of the variable date is stored in the partial object for later use. This is faster than a lambda form, and python does not need to byte-compile a new function.

Gribouillis 1,391 Programming Explorer Team Colleague

It means

exec mycode in mydictionary
Gribouillis 1,391 Programming Explorer Team Colleague

Replace line 18 with lpre.append(subject.name) . You can also replace line 19 with return ", ".join(lpre) .

Gribouillis 1,391 Programming Explorer Team Colleague

I think you must specify a length for the strings, otherwise the length defaults to zero.

import numpy

timefile_dtype=numpy.dtype([
         ('filename', file),
         ('year', int),
         ('month', str, 25),
         ('day', int),
         ('time', str, 25),
         ('int_time', int),
         ('unit', str, 25),
         ('avg', int),
         ('boxcar', int),
            ])

a = numpy.zeros((1,), dtype=timefile_dtype)
x = a[0]

x['filename'] = "hello.txt"
x['month'] = 'August'

print x.dtype
print x

""" my output -->
[('filename', '|O8'), ('year', '<i8'), ('month', '|S25'), ('day', '<i8'), ('time', '|S25'), ('int_time', '<i8'), ('unit', '|S25'), ('avg', '<i8'), ('boxcar', '<i8')]
('hello.txt', 0, 'August', 0, '', 0, '', 0, 0)
"""
Gribouillis 1,391 Programming Explorer Team Colleague

Here is an example

class Student(object):
    def __init__(self, name):
        self.name = name
        self.report = dict()
        
    def __repr__(self):
        return "Student({0})".format(repr(self.name))

    def add_subject(self, subject):
        self.report[subject] = list()
        
    def add_mark(self, subject, mark):
        self.report[subject].append(mark)
        
    def subjects(self):
        return self.report.keys()
        
    def s_subjects(self):
        return ", ".join(subject.name for subject in self.subjects())

    def average(self, subject):
        L = self.report[subject]
        return float(sum(L))/len(L)

class Subject(object):
    def __init__(self, name, teacher = "unknown"):
        self.name = name
        self.teacher = teacher
        

if __name__ == "__main__":
    janko = Student('Janko Moor')
    janka = Student ('Janka Vaskova')
    
    fyz = Subject('fyzic')
    eng = Subject('english')
    mat = Subject('matematic')
    hist= Subject('history')
    bio = Subject('biology')

    janko.add_subject(fyz)
    janko.add_subject(eng)
    janko.add_subject(mat)

    janka.add_subject(hist)
    janka.add_subject(bio)
    janka.add_subject(eng)
    janka.add_subject(fyz)

    janko.add_mark(fyz, mark=4)
    janko.add_mark(fyz, mark=1)
    janko.add_mark(fyz, mark=1)

    janka.add_mark(hist,mark=1)
    janka.add_mark(hist,mark=2)
    janka.add_mark(hist,mark=3)
    janka.add_mark(fyz,mark=1)
    
    print janko
    print janko.s_subjects()
    print janko.average(fyz)

    print janka
    print janka.s_subjects()
    print janka.average(hist)

""" my output -->
Student('Janko Moor')
fyzic, english, matematic
2.0
Student('Janka Vaskova')
biology, fyzic, history, english
2.0
"""
Gribouillis 1,391 Programming Explorer Team Colleague

It's a design issue. Here is my son's school report

FRANCAIS        Mrs xxx     17,0 , 13,0 , 16,0 , 19,0 , 10,5 , 18,0
LATIN           Mrs xxx     5,0
ANGLAIS LV1     Miss xxx    12,5 , 18,0
ESPAGNOL LV1    Mrs xxx     12,5 , 8,0 , 12,0
HIST/GEO/ED.CIV Miss xxx    15,0 , 13,5
MATHEMATIQUES   Mrs xxx     16,0 , 17,5 , 20,0 , 17,5
PHYSIQUE        Miss xxx    10,0 , 13,5
SC VIE ET TERRE Mrs xxx     18,5 , 15,0

As you can see there is a list of subjects and for each subject, a list of marks. These lists of marks belong to both my son and the subject. So I suggest the following class design:

class Student:
    # members
    name
    report

class Subject:
    # members
    name
    teacher_name

"report" can be a list of pairs (subject, list of marks), or a dictionary subject --> list of marks.

Gribouillis 1,391 Programming Explorer Team Colleague

array.array() accepts an iterable, it would be much more efficient not to create the list

M = array.array('B', (0 for x in xrange(sizeA)))

Actually what I said is not true, the list version is faster than the iterator version. I tried with itertools.repeat(0, sizeA) also, but the list version is still faster. Sorry.

Gribouillis 1,391 Programming Explorer Team Colleague

M = array.array('B',[0]*sizeA)

array.array() accepts an iterable, it would be much more efficient not to create the list

M = array.array('B', (0 for x in xrange(sizeA)))
Gribouillis 1,391 Programming Explorer Team Colleague

There is also a bitarray type in pypi http://pypi.python.org/pypi/bitarray

Gribouillis 1,391 Programming Explorer Team Colleague

Use the builtin function bytearray()

>>> L = bytearray(10)
>>> L
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> L[3] = 'a'
>>> L
bytearray(b'\x00\x00\x00a\x00\x00\x00\x00\x00\x00')

edit: sorry, that was not exacly your question, but perhaps you can use a block of 8 consecutive bytes for your purpose.

Gribouillis 1,391 Programming Explorer Team Colleague

The problem is that you're passing a string 'fyzika' to add_mark() instead of a Cpredmet object. I think it would be easier if self.predmety was a dictionary name --> Cpredmet instance with that name . For example you would write

def add_subject(self, predmet):
        '''

        @param predmet: objekt typu predmet
        '''
        self.predmety[predmet.nazov] = predmet

and then

if 'fyzika' in self.predmety:

would work.

Gribouillis 1,391 Programming Explorer Team Colleague

There is also re.search(r'\b3\b', '13 12 333 453 2 3 433') but it will match -3 too.

Gribouillis 1,391 Programming Explorer Team Colleague

Use f = file.read() and f = f.split() .

mr_noname commented: Very Helpful! Thanks. +0
Gribouillis 1,391 Programming Explorer Team Colleague

It looks easy, replace all the v1, v2, v3 .. variables with arrays v[0], v[1], v[2], something like

import tkinter as tk
from functools import partial

def klik(n):
    button[n].config(image=s[n])

root = tk.Tk()
 
frame1 = tk.Frame(root)
frame1.pack(side=tk.TOP, fill=tk.X)

karirano = tk.PhotoImage(file="kari.GIF")
s = list(tk.PhotoImage(file="%d.GIF" % (i+1)) for i in range(4))
button = list()
for i in range(4):
    button.append(tk.Button(frame1, image=karirano, command=partial(klik, i)))
    button[-1].grid(row=0,column=i)

root.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

I would say that the time complexity of the first function is O((j-i) Log(j-i)). The rough argument is this: it is obvious that the number of 'print' only depends on j-i. Call f(z) the number of items printed when prel(x, i, j) is called with an interval length z = j-i. There are z explicit prints in the function, and the function is recursively called 3 times with an interval of length about z/3. It means that f(z) = z + 3 f(z/3) approximately. The mathematical function which satisfies exactly this relation is f(z) = z log(z)/log(3). So this must be roughly the number of prints.

Gribouillis 1,391 Programming Explorer Team Colleague

Try

return "".join((seqA, '\n', a, '\n', seqB, '\n', 'Score: %d' % sum(c)))

edit: don't use tabs to indent python code, use 4 spaces.

Gribouillis 1,391 Programming Explorer Team Colleague

No it's not possible to have assignments in if conditions. The reason is that assignment is a statement and cannot be part of an expression (the same applies to += -=, etc), while the 'if' statement expects an expression. The potential problem with your code above is that it evaluates stmt1 several times. You could write it this way

c = expr1
if c or expr2:
    if c:
        k = 7
    if k == 7:
        # etc
    else:
        # etc

Notice that '== True' is usually not needed. I know it looks restricting if you're used to C code, but it is one of the features that make python code clear.

Gribouillis 1,391 Programming Explorer Team Colleague

There are python modules to parse vcards. I pip-installed a module called vobject and it works:

#!/usr/bin/env python
# -*-coding: utf8-*-

import vobject

cards = ["""BEGIN:VCARD
VERSION:2.1
REV:20110913T095232Z
UID:aac119d5fe3bc9dc-00e17913379d6cc8-3
N;X-EPOCCNTMODELLABEL1=First name:;Maj;;;
TEL;VOICE:09120000000
X-CLASS:private
END:VCARD""",

"""BEGIN:VCARD
VERSION:2.1
REV:20110228T083215Z
UID:aac119d5fe3bc9dc-00e17b0693898c98-4
N;X-EPOCCNTMODELLABEL1=First name:;Ali jahan;;;
TEL;VOICE:09120000001
X-CLASS:private
END:VCARD""",

"""BEGIN:VCARD
VERSION:2.1
REV:20110228T083510Z
UID:aac119d5fe3bc9dc-00e17b069df653a0-5
N;X-EPOCCNTMODELLABEL0=Last name;X-EPOCCNTMODELLABEL1=First name:Eqlimi;Mostafa;;;
TEL;CELL;1:+989120000002
TEL;VOICE:09180000003
X-CLASS:private
TEL;CELL;2:09390000004
X-CLASS:private
END:VCARD"""
]

if __name__ == "__main__":
    result = dict()
    for c in cards:
        v = vobject.readOne( c )
        # v.prettyPrint()
        result[str(v.n.value).strip()] = v.tel.value
    print result

""" my output -->
{'Ali jahan': u'09120000001', 'Maj': u'09120000000', 'Mostafa  Eqlimi': u'+989120000002'}
"""

Not sure it will work on your phone however

Gribouillis 1,391 Programming Explorer Team Colleague

Did you try

next(os.walk(directory))

In the doc, it seems that os.walk only works with strings (unicode), so that you shouldn't have encoding/decoding issues.

Gribouillis 1,391 Programming Explorer Team Colleague

whilst this thread is open, could you help me with another problem?

this time i am to determine whether its scalene or not, so i wrote;

def isScalene(x, y, z):
	if x <= 0 or y <=0 or z <=0:
		     return False
	elif x == y or x == z:
		  return False
	else:
		return True

but its not being accepted. whats wrong with this?

I understand that a trinagle is scalene if it is not isoceles, so this should work

def isScalene(x, y, z):
    return not isIsoceles(x, y, z)

You issue may come from the tab characters that you're using in your code. Configure your editor to indent python code with 4 spaces. Furthermore, pyTony's function doesn't work, one could have x == z when his function returns False. I suggest

def checkValidTriangle(x, y, z):
    if x < 0 or y < 0 or z < 0:
        raise ValueError("Negative side in triangle.")
    elif not (abs(x-y) <= z <= x + y):
        raise ValueError("Impossible triangle.")

def isIsoceles(x, y, z):
    checkValidTriangle(x, y, z)
    return (x == y) or (x == z) or (y == z)

# or

def isIsoceles(x, y, z):
    checkValidTriangle(x, y, z)
    return len(set((x, y, z))) <= 2
Gribouillis 1,391 Programming Explorer Team Colleague

I guess it could be something like this in C

#include <math.h>

double dot(int sz, double *u, double* v){
    int i;
    double res = 0.0;
    for(i = 0; i < sz; ++i)
        res += u[i] * v[i];
    return res;
}

void cumul(int sz, double *u, double* res){
    int i;
    for(i = 0; i < sz; ++i)
        res[i] += u[i];
}

double norm2(int sz, double *u){
    return sqrt(dot(sz, u, u));
}

void prod(int sz, double **A, double *v, double *res){
    int i;
    for(i = 0; i < sz; ++i)
        res[i] = dot(sz, A[i], v);
}

void zoom(int sz, double *y, double fact, double *res){
    int i;
    for(i = 0; i < sz; ++i){
        res[i] = y[i] * fact;
    }
}

void PowerMethod(int sz, double **A, double* y, double e, int *t, double *v){
    int stop = 0;
    while(1){
        zoom(sz, y, 1.0/norm2(sz, y), v);
        prod(sz, A, v, y);
        *t = dot(sz, v, y);
        if(stop)
            return;
        zoom(sz, v, -*t, v);
        cumul(sz, y, v);
        if(norm2(sz, v) <= e * abs(*t))
            stop = 1;
    }    
}

I don't have many opportunities to code C, so you can certainly improve it :)

Edit: you still need to write the main function and allocate and initialize a few arrays of double ...

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a way

def parse(annotation):
    return list((int(x), int(y)) for (x,y) in (item.strip(" ()").split('..') for item in annotation.split(',')))

print parse('(1834..2736), (348..7734)')

""" my output -->
[(1834, 2736), (348, 7734)]
"""

Edit: try and use the [code] button in the editor window at the bottom of this page!
Edit: it seems that pyTony gave you another nice solution last month http://www.daniweb.com/software-development/python/threads/400630/1715515#post1715515

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a version with timeit

# 619480
import time
from random import *
from timeit import Timer
timer = Timer("binarySearch(Spam.value, Spam.lst)", "from __main__ import Spam, binarySearch")
class Spam:
    pass

def main():
    lst = []
    result, length = 0, 500000
    while result <= 0.50 and length < 10**7:
        for i in range(length):
            lst.append(randint(1, length))
        value = randint(1, length)
        t0 = time.clock()
        linearSearch(value, lst)
        result = time.clock() - t0
        print("This LINEAR SEARCH took {0:4.2f}seconds with a length of".format(result), length)
        lst.sort()
        number = 1000
        Spam.value, Spam.lst = value, lst
        result = timer.timeit(number)
        #t0 = time.clock()
        #binarySearch(value, lst)
        #result = time.clock() - t0
        print("This BINARY SEARCH took {0:4.2e}seconds with a length of".format(result/number), length, "\n")
        lst = []
        length = length + 500000

def binarySearch(value, lst):
    low, high = 0, len(lst) - 1
    while low <= high:
        mid = (low + high) // 2
        item = lst[mid]
        if value == item:
            return mid
        elif value < item:
            high = mid - 1
        else:
            low = mid + 1
    return -1

def linearSearch(value, lst):
    for i in range(len(lst)):
        if value == lst[i]:
            return i
    return -1

main()

""" my output --->
('This LINEAR SEARCH took 0.03seconds with a length of', 500000)
('This BINARY SEARCH took 6.54e-06seconds with a length of', 500000, '\n')
('This LINEAR SEARCH took 0.07seconds with a length of', 1000000)
('This BINARY SEARCH took 5.83e-06seconds with a length of', 1000000, '\n')
('This LINEAR SEARCH took 0.24seconds with a length of', 1500000)
('This BINARY SEARCH took 7.55e-06seconds with a length of', 1500000, '\n') …
Gribouillis 1,391 Programming Explorer Team Colleague

The standard terminology is to call the three slice arguments start, stop and step

L[start:stop:step]

The elements in the returned list are

L[start], L[start + step], L[start + 2*step], L[start + 3*step], ...
  • step cannot be zero and defaults to 1
  • stop must not be understood as a last element, but as an unreachable bound. If start + k*step reaches the bound, the item with this index is not in the returned sequence.
  • If start (or stop) is < 0, python adds the length of the list to its value before doing anything.
  • Then if step < 0 but stop >= start, the returned list is empty
  • Similarly if step > 0 and stop <= start.
  • If stop is empty, it means 'no bound', like in L[2::1] .
  • If start is empty, it means start from the first or the last element depending on step > 0 or step < 0

For example

L[::-1]

starts from the last element with no bound and step -1, it reverses the list.

Gribouillis 1,391 Programming Explorer Team Colleague

You must not insert or remove items in a list while iterating on this list. In your case, you could simply use

for x in a:
    print x
a[:] = ()

If you want to delete only some items, use a pattern like

a = range(10)
print a

def keep_me(item):
   print item
   return item % 2

a[:] = (x for x in a if keep_me(x))
print a
Gribouillis 1,391 Programming Explorer Team Colleague

I think it is cheating, you can cheat even more

def MinMax(numbers):
    ''' This function finds the minimum and maximum values.
    Input  a list of real numbers.
    '''
    return min(numbers), max(numbers)

Try to write a function without sort(), min(), max(). You can use a loop and the comparison operators <, >, etc.

Gribouillis 1,391 Programming Explorer Team Colleague
Traceback (most recent call last):
  File "C:\Users\Chris\Documents\Python\Okami Zodiac.py", line 100, in ?
    from tracespect import Tracer
  File "C:\Users\Chris\Documents\Python\tracespect.py", line 17
    @simplegeneric
    ^
SyntaxError: invalid syntax

Yeah... it's not liking the function decorators. Are they necessary or can I comment them out?

Which version of python are you using ? These decorators are necessary, you don't have to change anything in tracepect.

Gribouillis 1,391 Programming Explorer Team Colleague

I've tried to download those, and the aspect folder is in the right directory but I can find nothing in them with Tracespect.py (and the only thing in your zip is a single file that is called "-" and won't do anything). Also did you typo in the code? Should it be aspect or inspect? I checked the aspect.py file and found no "getmro" anywhere.

Yes,reload the attachment, this time the file is called tracepect.py (or rename the file called -). The code is ok, there is no typo, inspect is the standard library module. You don't need to check any module.

Gribouillis 1,391 Programming Explorer Team Colleague

We are going to find where this window comes from:

1) download and install the 'aspects' module here http://www.cs.tut.fi/~ask/aspects/index.shtml
2) unpack and install the attached file tracepect.py in your site-packages folder.
3) change your main code to

from inspect import getmro
from tracepect import Tracer
tracer = Tracer()
tracer.wrap_classes(*getmro(Button))
root = Tk()
app = App(root)
root.mainloop()

4) run your code (avoid the image with your mouse otherwise there will be too much output), then close the window.
5) Look for the string Hello in the output, you should be able to find from which file and line the hello button was created.

Gribouillis 1,391 Programming Explorer Team Colleague

It works almost fine for me in a linux box, I only had to add this

else: # ADDED
           return 0, 0 # ADDED

to ToolTip.coords() (there are probably better values to return), and I used

t1 = ToolTip(b, text="The Rejuvenation Power", delay=500)
#or
        t1 = ToolTip(b, text="The Rejuvenation Power", follow_mouse=1, delay=500)
Gribouillis 1,391 Programming Explorer Team Colleague

you are right, it works after i use the 'w' option instead of 'wb'. any comment why notepad view differently? tq

See the doc of os.linesep for more information.

Also a[1]+' '+a[2]+' '+a[3]+' '+a[4]+' '+a[5]+' '+a[6] is best written ' '.join(a[1:7])

Gribouillis 1,391 Programming Explorer Team Colleague

I think this motto should not be understood too strictly. Here are a few hints

1) If there is only one (preferably obvious) way to do things, this reduces considerably the design part of writing software. Everybody agrees on the unique possible solution.

2) Obviously (and hopefully) this is not so in real life. There ARE several ways to do things, so the motto must be understood as an unreachable ideal.

3) Perhaps, this applies best to writers of APIs or UIs. Offering only one way to do things makes a much simpler interface. So perhaps when Tim Peters wrote the zen of python, he mainly targetted python developers and this was a guidance rule for python, to offer only the best way to do each thing.

4) As everybody knows, this was also a response to perl's TIMTOWTDI, which looks appealing to the beginning perl programmer, but rapidly leads to indecipherable code. At the time python and the zen of python were written, perl was a leader in scripting languages, and pythonistas had to give arguments as to why their language was better.

Gribouillis 1,391 Programming Explorer Team Colleague

great. the output is right. it's strange though when i open using output.txt using notepad, it shows:
17 BC_1 CLK input X 16 BC_1 OC_NEG input X 15 BC_1 D 1

but when i use other editor like wordpad it shows (which is what i want)
17 BC_1 CLK input X
16 BC_1 OC_NEG input X
15 BC_1 D 1

i also notice that in the code already inserted \n so it should write to a new line,not sure why notepad is showing differently.

anyway this certainly works. do you mind explaining the logic of your code, i'm trying to understand why there are 2 ifs. and the meaning of a=re.split("\W+", ?

thanks a lot

About the end of line issue, try to open the output file in mode "w" instead of "wb" to see if it changes something.

Gribouillis 1,391 Programming Explorer Team Colleague

thanks but output i get is:
<itertools.takewhile object at 0x0000000002B90808>

btw, what is itertools? didnt realize got this function. i'm using Python 2.6.6

The object x returned is an iterable. You can convert to a list with list(x), or iterate with a for loop: for line in x .

Itertools is a module in a standard library which contains useful functions to manipulate iterables.

Gribouillis 1,391 Programming Explorer Team Colleague

Something like

from itertools import dropwhile, takewhile

def not_advanced(line):
    return not line.startswith("-- Advanced")

def not_num(line):
    return not line.startswith("-- num")

with open("sample.txt") as lines:
    lines = takewhile(not_advanced, dropwhile(not_num, lines))
    for line in lines:
        print line
Gribouillis 1,391 Programming Explorer Team Colleague

I can't tell you about synapse, because I don't use it (I'm on mandriva most of the time), but you could try this: write an executable file named "myidle" which you store in a place where you store executable files (for example in /usr/local/bin), containing the following

#!/usr/bin/env bash
python /usr/lib/python2.7/idlelib/idle.py "$@"&

Then use synapse to start myidle instead of idle. It should work.

Gribouillis 1,391 Programming Explorer Team Colleague

sorry, my mistake
it returned as follows;

wolf@p:~$ /usr/lib/python2.7/idlelib/idle.py
bash: /usr/lib/python2.7/idlelib/idle.py: Permission denied
wolf@p:~$

It's

wolf@p:~$ python /usr/lib/python2.7/idlelib/idle.py