Re: user modules

2006-10-05 Thread Tuomas
Cameron Walsh wrote:
> Hi,
> 
> I'm writing a python program to analyse and export volumetric data.  To 
> make development and extension easier, and to make it more useful to the 
> public when it is released (LGPL), I would like to enable users to place 
> their own python files in a "user_extensions" directory.  These files 
> would implement a common interface in order for the main program to be 
> able to read them and execute the necessary code.
> 
> My question is what is the best way of implementing this?
> 
> I have investigated importing them as modules, but unless the user 
> modifies the main program I cannot see how the main program can learn of 
> the existence of specific modules.
> 
> For example:
> 
> from user_modules import *
> # directory 'user_modules' contains __init__.py allowing this
> # From here I would need a list of the imported modules, in order to
> # execute a common command on each of them, such as
> 
> for module in imported_modules:
> module.initialise()
> module.get_tab_window()
> 
> 
> How do I get from the first bit to the second bit, or is there a better 
> way of obtaining the functionality I need?
> 
> 
> --Cameron.

import os

files=os.listdir('user_modules')
tabs=[]
for fle in files:
 if fle.endswith('.py'):
 module=__import__(fle[0:-3], 'user_modules', None,
['initialise', 'get_tab_window'])
 module.initialise()
 tabs.append(module.get_tab_window())

*not tested*

print __import__.__doc__
__import__(name, globals, locals, fromlist) -> module

Import a module.  The globals are only used to determine the context;
they are not modified.  The locals are currently unused.  The fromlist
should be a list of names to emulate ``from name import ...'', or an
empty list to emulate ``import name''.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty.

Tuomas

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Alphabetical sorts

2006-10-16 Thread Tuomas

My application needs to handle different language sorts. Do you know a 
way to apply strxfrm dynamically i.e. without setting the locale?

Tuomas

Neil Cerutti wrote:
> On 2006-10-16, Ron Adam <[EMAIL PROTECTED]> wrote:
> 
>>I have several applications where I want to sort lists in
>>alphabetical order. Most examples of sorting usually sort on
>>the ord() order of the character set as an approximation.  But
>>that is not always what you want.
> 
> 
> Check out strxfrm in the locale module.
> 
> 
>>>>a = ["Neil", "Cerutti", "neil", "cerutti"]
>>>>a.sort()
>>>>a
> 
> ['Cerutti', 'Neil', 'cerutti', 'neil']
> 
>>>>import locale
>>>>locale.setlocale(locale.LC_ALL, '')
> 
> 'English_United States.1252'
> 
>>>>a.sort(key=locale.strxfrm)
>>>>a
> 
> ['cerutti', 'Cerutti', 'neil', 'Neil']
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cross-linked version of the python documentation

2006-10-20 Thread Tuomas
tom arnall wrote:
> Is there a cross-linked version of the python documentation available? Is
> anyone interested in starting a project for such?
> 
> tom arnall
> north spit, ca
> usa
> 

pydoc serves as such a cross-linked version of the python *online* 
documentation

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint: What's wrong with the builtin map()

2006-10-22 Thread Tuomas
Georg Brandl wrote:
> Some people think that all occurences of map() must be replaced
> by list comprehensions. The designer of pylint seems to be
> one of those.

So it seems, but why? Formally spoken we ase "using variable 'x' before 
assigment" in the comprehension too.

#!/usr/bin/python
"""test pydev_0.9.3/../pylint"""
__revision__ = "test_mod 0.2 by TV 06/10/22"

lst = ['aaa', ' bbb', '\tccc\n']
# lst = (lambda x: x.strip(), lst) # revision 0.1
lst = [x.strip() for x in lst]

result = """revision 0.1:
No config file found, using default configuration
* Module test_mod
W:  6: Used builtin function 'map'
E:  6: Using variable 'x' before assigment
...

revision 0.2:
...
Your code has been rated at 10.00/10 (previous run: -10.00/10)
"""
-- 
http://mail.python.org/mailman/listinfo/python-list


pylint: What's wrong with the builtin map()

2006-10-22 Thread Tuomas
#!/usr/bin/python
"""test pydev_0.9.3/../pylint"""
__revision__ = "test_mod 0.1 by TV 06/10/22"

lst = ['aaa', ' bbb', '\tccc\n']
lst = map(lambda x: x.strip(), lst)

result = """
No config file found, using default configuration
* Module test_mod
W:  6: Used builtin function 'map'
E:  6: Using variable 'x' before assigment
...
"""
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __div__ not recognized automatically

2006-11-02 Thread Tuomas

Try
a=(b+c)/NumX(2)

TV

Anton81 wrote:
> Hello!
> 
> I wrote a class
> 
> class NumX:
>   ...
>   def __add__(self,other):
> ...
>   def __div__(self,other):
> if not isinstance(other,NumX): other=NumX(other)
> ...
> 
> Somewhere else I use
> 
> a=(b+c)/2
> 
> where all variables are of NumX Type. When I execute the program it
> complains that it can't find an operator "/" for "instance" and "integer".
> However if I use pdb the same command works when started on the prompt. Also
> the manual execution
> 
> a=(b+c).__div__(2)
> 
> works. Any suggestions what goes wrong?
> 
> Anton
-- 
http://mail.python.org/mailman/listinfo/python-list


forwarding *arg parameter

2006-11-05 Thread Tuomas
 >>> def g(*arg):
... return arg
...
 >>> g('foo', 'bar')
('foo', 'bar')
 >>> # seems reasonable
...
 >>> g(g('foo', 'bar'))
(('foo', 'bar'),)
 >>> # not so good, what g should return to get rid of the outer tuple

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forwarding *arg parameter

2006-11-05 Thread Tuomas
Diez B. Roggisch wrote:
> Tuomas schrieb:
> 
>>  >>> def g(*arg):
>> ... return arg
>> ...
>>  >>> g('foo', 'bar')
>> ('foo', 'bar')
>>  >>> # seems reasonable
>> ...
>>  >>> g(g('foo', 'bar'))
>> (('foo', 'bar'),)
>>  >>> # not so good, what g should return to get rid of the outer tuple
> 
> 
> g(*g('foo', 'bar'))
> 
> 
> * and **  are the symetric - they capture ellipsis arguments, and they 
> make iterables/dicts passed as positional/named arguments.
> 
> Diez

Thanks Diez

And what about this case if I want the result ('foo', 'bar')

 >>> def f(*arg):
... return g(arg)
...
 >>> f('foo', 'bar')
(('foo', 'bar'),)

 >>> def h(*arg):
... return arg[0]
...
 >>> g=h
 >>> f('foo', 'bar')
('foo', 'bar')

Where can g know it should use arg[0] when arg is forwarded?

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forwarding *arg parameter

2006-11-05 Thread Tuomas
Steven D'Aprano wrote:

> You could write something like this:
> 
> def g(*arg):
> # Detect the special case of a single tuple argument
> if len(arg) == 1 and type(arg[0]) == tuple:
> return arg[0]
> else:
> return arg
> 
> but now tuple arguments are treated differently to all other data. Why do
> you think you need that?

I am looking a shorter way to do the above in the case:

def g(*arg):
 return arg

def f(*arg):
 return g(arg)

How can g know if it is called directly with (('foo', 'bar'),) or via f 
with ('foo', 'bar'). I coud write in f: return g(arg[0], arg[1]) if I 
know the number of arguments, but what if I don't know that in design time?

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forwarding *arg parameter

2006-11-05 Thread Tuomas
Tuomas wrote:
> def g(*arg):
> return arg
> 
> def f(*arg):
> return g(arg)
> 
> How can g know if it is called directly with (('foo', 'bar'),) or via f 
> with ('foo', 'bar'). I coud write in f: return g(arg[0], arg[1]) if I 
> know the number of arguments, but what if I don't know that in design time?

So it seems that I would like to have an unpack operator:

def f(*arg):
 return(!*arg)

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forwarding *arg parameter

2006-11-05 Thread Tuomas
Stargaming wrote:
> Either you take one of the snippets here:
> http://aspn.activestate.com/ASPN/search?query=flatten§ion=PYTHONCKBK&type=Subsection
>  
> 
> or just use arg[0] clever (as mentioned a few times in this thread).

Thanks. My solution became:

 >>> def flattern(arg):
... result = []
... for item in arg:
... if isinstance(item, (list, tuple)):
... result.extend(flattern(item))
... else:
... result.append(item)
... return tuple(result)
...
 >>> def g(*arg):
... arg = flattern(arg)
... return arg
...
 >>> def f(*arg):
... return g(arg)
...
 >>> f('foo', 'bar')
('foo', 'bar')

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forwarding *arg parameter

2006-11-05 Thread Tuomas
Dennis Lee Bieber wrote:
> On Sun, 05 Nov 2006 17:42:30 GMT, Tuomas <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> 
> 
>>I am looking a shorter way to do the above in the case:
>>
>>def g(*arg):
>> return arg
>>
>>def f(*arg):
>> return g(arg)
>>
>>How can g know if it is called directly with (('foo', 'bar'),) or via f 
> 
> 
>   Typically, the responsibility should be on the CALLER, not the
> CALLED..
> 
> 
>>>>def g(*arg):
> 
> ...   return arg
> ... 
> 
>>>>def f(*arg):
> 
> ...   return g(*arg)  #<<<<<<<< unpack tuple on call
> ... 
> 
>>>>f("a", 1, 2)
> 
> ('a', 1, 2)
> 
> 
>   Note how f() is calling g() using an * -- Since f() "knows" that its
> arguments were "packed" it calls g() with an unpack marker. Then g()
> gets the arguments via whatever scheme it was coded to use.
> 
> 
>>>>def f(*arg):
> 
> ...   return g(arg)   #<<<<<<<<<< no tuple unpack
> ... 
> 
>>>>f("a", 1, 2)
> 
> (('a', 1, 2),)
> 
>  
I fylly agree with tis: "Typically, the responsibility should be on the 
CALLER, not the CALLED..". I just don't know how to unpack *arg for 
calling g. I can get the len(arg), but how to formulate an unpacked call 
g(arg[0], arg[1], ..). Building a string for eval("g(arg[0], arg[1], 
..)") seems glumsy to me.

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forwarding *arg parameter

2006-11-06 Thread Tuomas
Dennis Lee Bieber wrote:
> On Sun, 05 Nov 2006 22:51:00 GMT, Tuomas <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> 
>>> 
>>
>>I fylly agree with tis: "Typically, the responsibility should be on the 
>>CALLER, not the CALLED..". I just don't know how to unpack *arg for 
>>calling g. I can get the len(arg), but how to formulate an unpacked call 
>>g(arg[0], arg[1], ..). Building a string for eval("g(arg[0], arg[1], 
>>..)") seems glumsy to me.
>>
> 
>   Did you miss the example I gave? Using "*args" on the "def"
> essentially says "pack remaining arguments into one tuple". Using
> "*args" on a CALL says "UNPACK tuple into positional arguments"
> 
> def f(*args): <<<< pack arguments into tuple

Thats it:

>   x = g(*args)>>>> unpack args tuple when calling

Yesterday I tested something like this and got a syntax error. So I got 
misunderstanding that "g(*args)" is'nt a proper syntax. Obviously my 
test sentence had some other syntax error. Sorry.

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forwarding *arg parameter

2006-11-06 Thread Tuomas
Steven D'Aprano wrote:
> On Sun, 05 Nov 2006 19:35:58 +, Tuomas wrote:
> 
> 
>>Thanks. My solution became:
>>
>> >>> def flattern(arg):
>>... result = []
>>... for item in arg:
>>... if isinstance(item, (list, tuple)):
>>... result.extend(flattern(item))
>>... else:
>>... result.append(item)
>>... return tuple(result)
>>...
>> >>> def g(*arg):
>>... arg = flattern(arg)
>>... return arg
>>...
>> >>> def f(*arg):
>>... return g(arg)
>>...
>> >>> f('foo', 'bar')
>>('foo', 'bar')
> 
> 
> 
> That's the most complicated do-nothing function I've ever seen. Here is a
> shorter version:
> 
> def shortf(*args):
> return args
> 
> 
> 
>>>>f('foo', 'bar')
> 
> ('foo', 'bar')
> 
>>>>shortf('foo', 'bar')
> 
> ('foo', 'bar')
> 
> 
>>>>f(1,2,3,4)
> 
> (1, 2, 3, 4)
> 
>>>>shortf(1,2,3,4)
> 
> (1, 2, 3, 4)
> 
> 
>>>>f({}, None, 1, -1.2, "hello world")
> 
> ({}, None, 1, -1.2, 'hello world')
> 
>>>>shortf({}, None, 1, -1.2, "hello world")
> 
> ({}, None, 1, -1.2, 'hello world')
> 
> Actually, they aren't *quite* identical: your function rips lists apart,
> which is probably not a good idea.
> 
> 
>>>>f("foo", [1,2,3], None) # three arguments turns into five
> 
> ('foo', 1, 2, 3, None)
> 
>>>>shortf("foo", [1,2,3], None) # three arguments stays three
> 
> ('foo', [1, 2, 3], None)
> 
> 
> 
> I still don't understand why you are doing this. Can we have an example of
> why you think you need to do this?

If i redefine the function g the difference comes visible:

  >>> def g(*arg):
... if with_flattern: arg=flattern(arg)
... return arg

 >>> with_flattern=False
 >>> f('foo', 'bar')
(('foo', 'bar'),)
 >>> with_flattern=True
 >>> f('foo', 'bar')

If you read the whole chain you find out what we were talking of.

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forwarding *arg parameter

2006-11-06 Thread Tuomas
Steve Holden wrote:
> Suppose you did actually want to do this you have chosen about the worst 
> possible way: the use of global variables to condition function 
> execution is a sure way to get into trouble. Consider if somebody else 
> want to use your function: they also have to set a global in their 
> program to avoid your function raising an exception.

Do you think all discussion examples are included a producton application.

> Fortunately Python has just the thing to make such horrors unnecessary: 
> the default argument value. Try something like this (untested):
> 
> def g(flattening=True, *arg):
> if flattening:
> arg = flatten(arg)
> return arg
> 
> Obviously you could use either True or False for the default value. In 
> the case above the function flattens by default. You could also, if you 
> wished, have f() take the flattening argument, and always pass it to g().
> 
> Nothing very sophisticated here, just something to help you flex your 
> growing Python and programming muscles.

Thanks for your good purposes.

TV

> regards
>  Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forwarding *arg parameter

2006-11-07 Thread Tuomas
Steven D'Aprano wrote:
> On Mon, 06 Nov 2006 13:03:55 +, Tuomas wrote:
> 
> 
>>If you read the whole chain you find out what we were talking of.
> 
> 
> I had already read the whole thread, and I've read it again in case I
> missed something the first time, and I still have no idea why you think
> you need to do this. You explain *what* you want to do, but not *why* you
> want to do it.

Redirecting a funtion parameter to an other function is a quite common 
situation in programming. Here the question was forwarding *args 
parameter. Have you ever tried this and found the difference in cases:

def f(*args):
 x = g(args)  # how g sees arguments in this case
 x = g(*args) # and how it sees them in this case

I am happy with what Dennis Lee Bieber wrote in the second latest node 
in this chain. So luckily my "flattern" is not needed because the 
problem I had can be solved in the calling function.

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Catching toplevel move and resize

2006-09-16 Thread Tuomas
 From a PyGTK component I would like to react moving and resizing the 
toplevel window. I try to connect the toplevel 'frame-event' to my 
callback, but the toplevel do not fire on moving or resizing. Any 
suggestions?

Tuomas
(Linux, Python 2.3, GTK 2.6.7)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Catching toplevel move and resize

2006-09-16 Thread Tuomas
Pontus Ekberg wrote:
> You are probably looking for "configure_event".

That's it! Works fine, thanks.

Tuomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Message dialog on 'focus-out-event'

2006-09-18 Thread Tuomas
import pygtk, gtk, gobject, ...

class MyEntry(gtk.Entry):
 def __init__(self, is_OK):
 gtk.Entry.__init__(self)
 self.is_OK=is_OK
 self.add_events(gtk.gdk.FOCUS_CHANGE)
 self.focus_out_id=self.connect('focus-out-event',
self.on_focus_out)

 def on_focus_out(self, sender, event):
 if self.is_OK(self.get_text()): return False
 else:
 # don't want another focus-out-event because of show_message
 self.disconnect(self.focus_out_id)
 # self.grab_focus()
 show_message("Wrong value for entry")
 self.focus_out_id=self.connect('focus-out-event',
self.on_focus_out)
 return False

 # Leaving focus in not_OK case results:

 # GtkWarning: GtkEntry - did not receive focus-out-event.
 # If you connect a handler to this signal, it must return
 # FALSE so the entry gets the event as well

 # The required False is given, but may be the messagebox
 # times it out.

 # My second trial was to include self.grab_focus() before
 # show_message, but it gives focus to the toplevel
 # gtk.gdk.Window and I lose access to the entry.

 # Any suggestions?
 # Tuomas Vesterinen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "list index out of range" error

2006-09-20 Thread Tuomas
sam wrote:

I gues: no_lines=len(list_initial)

> for j in range(0, no_lines):

   range returns 0, 1, 2, ..., no_lines-1

> 
> k = 0
> while k < no_lines:
> sorted_check = 0
> if list_initial[k] < list_initial[k+1]:

When j gets its last value (no_lines-1) k has the same value and k+1 
owerflows the list index range.

Try

   for j in range(1, no_lines):
   ...
   if list_initial[k-1] < list_initial[k]:
   ...

Tuomas

> temp_str = list_initial[k]
> elif list_initial[k] == list_initial[k+1]:
> temp_str = list_initial[k]
> elif list_initial[k] > list_initial[k+1]:
> temp_str = list_initial[k+1]
> sorted_check = 1
> k += 1
> 
> list_initial.remove(temp_str)
> list_final.append(temp_str)
> no_lines -= 1
> 
> if sorted_check == 0:
> break
...
-- 
http://mail.python.org/mailman/listinfo/python-list


gtk.Entry Colors

2006-09-24 Thread Tuomas
I would like to manipulate PyGTK Entry widget's background and 
foreground colors. Is it possible? How?

Tuomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gtk.Entry Colors

2006-09-24 Thread Tuomas
MonkeeSage wrote:
> Tuomas wrote:
> 
>>I would like to manipulate PyGTK Entry widget's background and
>>foreground colors. Is it possible? How?
> 
> 
> Yes, it is possible:
> 
> # widget color
> entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#FF"))
> # frame color
> entry.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#FF"))
> # text color
> entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#00FF00"))


Thanks a lot.

> See:
> http://www.pygtk.org/pygtk2reference/class-gtkwidget.html
> http://www.pygtk.org/pygtk2reference/class-gdkcolor.html

Yes, I read the reference before posting here. I tried something like:

attr_list=pango.AttrList()
attr=pango.AttrForeground(0, 0, 65000, start_index=0, end_index=-1)
attr_list.insert(attr)
entry.get_layout().set_attributes(attr_list)

or

entry.window.set_background(gtk.gdk.color_parse("#FF"))

but they did not work for this purpose.

Tuomas

> Regards,
> Jordan
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gtk.Entry Colors

2006-09-25 Thread Tuomas
MonkeeSage wrote:
> Tuomas wrote:
> 
>>Yes, I read the reference before posting here. I tried something like:
> 
> 
> Hi Tuomas,
> 
> I didn't mean to say that you hadn't read the docs (I had a hard time
> finding the right methods in the docs too, even though I know the
> methods); I just wanted to give you the references so you could see the
> method signatures and the other gdk.Color options. :)


I didn't meant to blame you of blaming me either. I had worked with this 
problem a couple of days and your advice helped me to solve it in ten 
minutes. So I am very grateful.

Nice thing this Python :)

Tuomas

> Regards,
> Jordan
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Resuming a program's execution after correcting error

2006-09-28 Thread Tuomas
Sheldon wrote:
> Does anyone know if one can resume a python script at the error point
> after the error is corrected?
> I have a large program that take forever if I have to restart from
> scratch everytime. The error was the data writing a file so it seemed
> such a waste if all the data was lost and must be recalculated again.

May be you could put some parameter to your main loop:

start_point=begin
if start_point==begin: output=open('outputfile', 'w')
else : output=open('outputfile', 'a')

while start_point <= case <= end_point:

 try:
 do_complex_computation(case)
 except Exception:
 print case
 break

If you get an error you repair the program and set

start_point=case

and go on with the program.

Tuomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: interleaving dictionary values

2006-11-22 Thread Tuomas
[EMAIL PROTECTED] wrote:
> Hello,
> 
> I was trying to create a flattened list of dictionary values where each
> value is a list, and I was hoping to do this in some neat functionally
> style, in some brief, throwaway line so that it would assume the
> insignificance that it deserves in the grand scheme of my program.
> 
> I had in mind something like this:
> 
> 
interleave([1, 2, 3], [4,5], [7, 8, 9])
> 
> [1, 4, 7, 2, 5, 8, 3, 9]
> 
> I played for a while with zip(), [some newfangled python keyword, that
> I was truly shocked to find has been hiding at the bottom of the list
> built in functions since version 2.0], before giving up and going back
> to trusty old map(), long celebrated for making code hard to read:
> 
> 
map(None, [1, 2, 3], [4,5], [7, 8, 9])
> 
> [(1, 4, 7), (2, 5, 8), (3, None, 9)]
> 
> This is basically it.  It then becomes:
> 
> 
filter(None, flatten(map(None, [1, 2, 3], [4,5], [7, 8, 9])))
> 
> [1, 4, 7, 2, 5, 8, 3, 9]
> 
> filter(None, - my brain parses that automatically now.  This is not so
> bad.  Flatten is snitched from ASPN/Cookbook/Python/Recipe/363051,
> thank you Jordan Callicoat, Mike C. Fletcher:
> 
> def flatten(l, ltypes=(list, tuple)):
> i = 0
> while (i < len(l)):
>while (isinstance(l[i], ltypes)):
>l[i:i+1] = list(l[i])
>i += 1
> return l
> 
> Trouble is then getting map() to play with the result of dict.values().
>  I only worked this out while writing this post, of course.
> 
> Given a dictionary like d = { "a" : [1, 2, 3], "b" : [4, 5], "c" : [7,
> 8, 9]} - I was hoping to do this:
> 
>   map(None, d.values())
> 
> But instead I (finally worked out I could) do this:
> 
>   apply(map, tuple([None] + d.values()))
> 
> So... my bit of code becomes:
> 
>   filter(None, flatten(map(None, apply(map, tuple([None] +
> d.values())
> 
> It fits on one line, but it feels far more evil than I set out to be.
> The brackets at the end are bad for my epilepsy.
> 
> Surely there is there some nice builtin function I have missed?
> 
> --
> | John J. Lehmann, j1o1h1n(@)gmail.com
> + [lost-in-translation] "People using public transport look stern, and
> handbag
> + snatchers increase the ill feeling."  A  Japanese woman, Junko, told
> the paper:
> + "For us, Paris is the dream city. The  French are all beautiful and
> elegant
> + And then, when we arrive..."
> 

What about:
 >>> d = { "a" : [1, 2, 3], "b" : [4, 5], "c" : [7, 8, 9]}
 >>> L=[]
 >>> for x in d.values(): L.extend(x)
...
 >>> L
[1, 2, 3, 7, 8, 9, 4, 5]

or a little curious:
 >>> L=[]
 >>> map(L.extend, d.values())
[None, None, None]
 >>> L
[1, 2, 3, 7, 8, 9, 4, 5]

TV

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find script's directory

2007-08-19 Thread Tuomas
#!/usr/bin/python
# module show_my_path
# ...
import os
print 'os.path.abspath(__file__):', os.path.abspath(__file__)
# ...
# end of module

[EMAIL PROTECTED] class]$ python
 >>> import show_my_path
os.path.abspath(__file__): /misc/proc/py/test/class/show_my_path.py
 >>>
[EMAIL PROTECTED] class]$ python show_my_path.py
os.path.abspath(__file__): /misc/proc/py/test/class/show_my_path.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sorting a list of lists

2007-08-27 Thread Tuomas
 >>> records = [['dog',1,2], ['chair',2,1], ['cat',1,3], ['horse',3,4],
... ['table',3,2], ['window',3,5]]
 >>> sorted(records, key = lambda x: (x[1], x[2]))
[['dog', 1, 2], ['cat', 1, 3], ['chair', 2, 1], ['table', 3, 2], 
['horse', 3, 4], ['window', 3, 5]]


[EMAIL PROTECTED] wrote:
> Hi,
> 
> i would like to sort a list of lists. The list is first sorted on the
> second item in the sub-lists (which I can do), then on the third item
> (which I can't).
> 
> eg. records = [['dog',1,2], ['chair',2,1], ['cat',1,3], ['horse',3,4],
> ['table',3,2], ['window',3,5]]
> 
> I want sorted to [['dog',1,2], ['cat',1,3], ['chair',2,1], ['table',
> 3,2], ['horse',3,4], ['window',3,5]]
> 
> To sort on the second item in the sub-lists I do the following
> 
> pass1 = itemgetter(1)
> sorted(records, key=pass1)
> 
> How can I then sort on the third item in the sub-lists whilst keeping
> the order on the second item?
> 
> Nick
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Undeterministic strxfrm?

2007-09-04 Thread Tuomas
Python 2.4.3 (#3, Jun  4 2006, 09:19:30)
[GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import locale
 >>> def key(s):
... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8')
... return locale.strxfrm(s.encode('utf8'))
...
 >>> first=key(u'maupassant guy')
 >>> first==key(u'maupassant guy')
False
 >>> first
'\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 
$\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79'
 >>> key(u'maupassant guy')
'\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 
$\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5'
 >>>

May be this is enough for a sort order but I need to be able to catch 
equals too. Any hints/explanations?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: REGULAR EXPRESSION

2007-09-04 Thread Tuomas
AniNair wrote:
> hi.. I am trying to match '+ %&/-' etc using regular expression  in
> expressions like 879+34343. I tried \W+   but it matches only in the
> beginning of the string Plz help Thanking you in advance...
> 

Is this what you are seeking for?

 >>> re.compile('(\+{0,1})?([0-9]+)').findall('879+34343')
[('', '879'), ('+', '34343')]

Tuomas Vesterinen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Undeterministic strxfrm?

2007-09-04 Thread Tuomas
Gabriel Genellina wrote:
> En Tue, 04 Sep 2007 07:34:54 -0300, Tuomas 
> <[EMAIL PROTECTED]>  escribi�:
> 
>> Python 2.4.3 (#3, Jun  4 2006, 09:19:30)
>> [GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>>  >>> import locale
>>  >>> def key(s):
>> ... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8')
>> ... return locale.strxfrm(s.encode('utf8'))
>> ...
>>  >>> first=key(u'maupassant guy')
>>  >>> first==key(u'maupassant guy')
>> False
>>  >>> first
>> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12
>> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79'
>>  
>>
>>  >>> key(u'maupassant guy')
>> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12
>> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5'
>>  
>>
>>  >>>
>>
>> May be this is enough for a sort order but I need to be able to catch
>> equals too. Any hints/explanations?
> 
> 
> I can't use your same locale, but with my own locale settings, I get  
> consistent results:
> 
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit  
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> py> import locale
> py> locale.setlocale(locale.LC_COLLATE, 'Spanish_Argentina')
> 'Spanish_Argentina.1252'
> py> def key(s):
> ...   return locale.strxfrm(s.encode('utf8'))
> ...

Because I am writing a multi language application I need to plase the 
locale setting inside the key function. Actually I am implementing 
binary search in a locally sorted list of strings and should be able to 
count on stable results of strxfrm despite possibly visiting another 
locale at meantime. Could repeated calls to setlocale cause some problems?

> py> first=key(u'maupassant guy')
> py> print repr(first)
> '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02
>  
> 
> \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01'
> py> print repr(key(u'maupassant guy'))
> '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02
>  
> 
> \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01'
> py> print first==key(u'maupassant guy')
> True
> 
> Same thing with Python 2.4.4
> 

I get the same unstability with my locale 'fi_FI.utf8' too, so I am 
wondering if the source of the problem is the clib or the Python wrapper 
around it. Differences in strxfrm results for identical source are 
allways in the few latest bytes of the results.



-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Undeterministic strxfrm?

2007-09-04 Thread Tuomas
Peter Otten wrote:
> Python seems to be the culprit as there is a relatively recent
> strxfrm-related bugfix, see

Thanks Peter. Can't find it, do you have the issue number?

> http://svn.python.org/view/python/trunk/Modules/_localemodule.c?rev=54669
> 
> If I understand it correctly the error makes it likely that the resulting
> string has trailing garbage characters.

Reading the rev 54669 it seems to me, that the bug is not fixed. Man says:

STRXFRM(3): ... size_t strxfrm(char *dest, const char *src, size_t n);
... The first n characters of  the  transformed  string
are  placed in dest.  The transformation is based on the program’s 
current locale for category LC_COLLATE.
... The strxfrm() function returns the number of bytes required to 
store  the transformed  string  in dest excluding the terminating ‘\0’ 
character.  If the value returned is n or more, the contents of dest are 
*indeterminate*.

Accordin the man pages Python should know the size of the result it 
expects and don't trust the size strxfrm returns. I don't completely 
understand the collate algorithm, but it should offer different levels 
of collate. So Python too, should offer those levels as a second 
parameter. Hovever strxfrm don't offer more parameters either except 
there is another function strcasecmp. So Python should be able to 
calculate the expected size before calling strxfrm or strcasecmp. I 
don't how it is possible. May be strcoll knows better and I should kick 
strxfrm off and take strcoll instead. It costs converting the seach key 
in every step of the search.

Tuomas

> Peter
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Undeterministic strxfrm?

2007-09-05 Thread Tuomas
Gabriel Genellina wrote:
> I think it's not in the issue tracker - see  
> http://xforce.iss.net/xforce/xfdb/34060
> The fix is already in 2.5.1  
> http://www.python.org/download/releases/2.5.1/NEWS.txt

Thanks Gabriel, I'll try Python 2.5.1.

>> Reading the rev 54669 it seems to me, that the bug is not fixed. Man  
>> says:
>>
>> STRXFRM(3): ... size_t strxfrm(char *dest, const char *src, size_t n);
>> ... The first n characters of  the  transformed  string
>> are  placed in dest.  The transformation is based on the program’s
>> current locale for category LC_COLLATE.
>> ... The strxfrm() function returns the number of bytes required to
>> store  the transformed  string  in dest excluding the terminating ‘\0’
>> character.  If the value returned is n or more, the contents of dest are
>> *indeterminate*.
>>
>> Accordin the man pages Python should know the size of the result it
>> expects and don't trust the size strxfrm returns. I don't completely
>> understand the collate algorithm, but it should offer different levels
>> of collate. So Python too, should offer those levels as a second
>> parameter. Hovever strxfrm don't offer more parameters either except
>> there is another function strcasecmp. So Python should be able to
>> calculate the expected size before calling strxfrm or strcasecmp. I
>> don't how it is possible. May be strcoll knows better and I should kick
>> strxfrm off and take strcoll instead. It costs converting the seach key
>> in every step of the search.
> 
> 
> No. That's why strxfrm is called twice: the first one returns the 
> required  buffer size, the buffer is resized, and strxfrm is called 
> again. That's a  rather common sequence when buffer sizes are not known 
> in advance.
> [Note that `dest` is indeterminate, NOT the function return value which  
> always returns the required buffer size]
> 

OK, I made too quick conclusions of the man text without knowing the 
details.

Tuomas
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: interesting puzzle......try this you will be rewarded...

2007-09-07 Thread Tuomas

To save your time:

http://ilikeit.desiblogz.com/363/ojofuffo,+ojofuffo,+ojofuffo+-+Solutions+to+the+Hacking+puzzle++by+freestuffhotdeals.com.html

Renu wrote:
> Hi,
> 
> Just click on this link n use ur common sence to navigate.
> 
> It has 23 pages one after the other, starting from this first
> 
> Page.
> The trick is to find a way to go to the next page.
> 
> If u can really go to the 23rd page ur a genius in ur own respect :)
> 
> So best of luck n keep clicking, tik tik
> 
> http://iamhere.50webs.com
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Tuomas
Mark Summerfield wrote:
> I feel that Python lacks one useful data structure: an ordered
> dictionary.

Why it should be a dict. With it you can only maintain the order 
x1http://mail.python.org/mailman/listinfo/python-list


Exceptions and unicode messages

2007-03-21 Thread Tuomas
This works:
 >>> raise StandardError(u'Wrong type')
Traceback (most recent call last):
   File "", line 1, in ?
StandardError: Wrong type

but don't in Finnish:
 >>> raise StandardError(u'Väärä tyyppi')
Traceback (most recent call last):
   File "", line 1, in ?
StandardError>>>
 >>>

Any solution in Python?

TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exceptions and unicode messages

2007-03-21 Thread Tuomas

This seems to work:

 >>> import sys, traceback
 >>> def excepthook(exctype, value, tb):
... if tb:
... lines = traceback.format_tb(tb)
... for i, line in zip(range(len(lines)), lines):
... lines[i] = lines[i].decode('utf8')
... lines.insert(0, u'Traceback (most recent call last):\n')
... else:
... lines = []
... msg = str(exctype).split('.')[-1] + u': ' + unicode(value)
... lines.append(msg)
... print u''.join(lines)
...
 >>> sys.excepthook = excepthook
 >>> class UserError(StandardError):
... def __str__(self):
... return self.args[0]
...
 >>> raise UserError(u'Väärä tyyppi')
Traceback (most recent call last):
   File "", line 1, in ?
UserError: Väärä tyyppi
 >>>

Tuomas

Tuomas wrote:
> This works:
>  >>> raise StandardError(u'Wrong type')
> Traceback (most recent call last):
>   File "", line 1, in ?
> StandardError: Wrong type
> 
> but don't in Finnish:
>  >>> raise StandardError(u'Väärä tyyppi')
> Traceback (most recent call last):
>   File "", line 1, in ?
> StandardError>>>
>  >>>
> 
> Any solution in Python?
> 
> TV
-- 
http://mail.python.org/mailman/listinfo/python-list


Problems with datetime.datetime.strptime

2009-05-09 Thread Tuomas Vesterinen
I hoped that I could get rid of my special module _strptime2 when 
porting to Python 3.0. But testing is a disappointment.


Python 3.0.1 (r301:69556, Apr 14 2009, 14:30:31)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale, datetime
>>> def test1(locale_str, val):
... print(locale.setlocale(locale.LC_ALL, locale_str), ':')
... test_cases = [
... locale.nl_langinfo(locale.D_T_FMT), # test default formats
... locale.nl_langinfo(locale.D_FMT),
... locale.nl_langinfo(locale.T_FMT)
... ]
... for form in test_cases:
... string = val.strftime(form)
... print("  strftime(%s)=%s" % (repr(form), repr(string)))
... print("  strptime(%s,%s)=" % (repr(string), repr(form)), 
end=' ')

... try:
... val2 = datetime.datetime.strptime(string, form)
... except ValueError as e:
... print('\n   ', str(e))
... else:
... print('\n   ', str(val2))
...
>>> now = datetime.datetime.now()
>>> for loc in ('C', 'en_US.UTF-8', 'fi_FI.UTF-8'):
... test1(loc, now)
...
C :
  strftime('%a %b %e %H:%M:%S %Y')='Sat May  9 11:26:12 2009'
  strptime('Sat May  9 11:26:12 2009','%a %b %e %H:%M:%S %Y')=
'e' is a bad directive in format '%a %b %e %H:%M:%S %Y'
  strftime('%m/%d/%y')='05/09/09'
  strptime('05/09/09','%m/%d/%y')=
2009-05-09 00:00:00
  strftime('%H:%M:%S')='11:26:12'
  strptime('11:26:12','%H:%M:%S')=
1900-01-01 11:26:12
en_US.UTF-8 :
  strftime('%a %d %b %Y %r %Z')='Sat 09 May 2009 11:26:12 AM '
  strptime('Sat 09 May 2009 11:26:12 AM ','%a %d %b %Y %r %Z')=
'r' is a bad directive in format '%a %d %b %Y %r %Z'
  strftime('%m/%d/%Y')='05/09/2009'
  strptime('05/09/2009','%m/%d/%Y')=
2009-05-09 00:00:00
  strftime('%r')='11:26:12 AM'
  strptime('11:26:12 AM','%r')=
'r' is a bad directive in format '%r'
fi_FI.UTF-8 :
  strftime('%a %e. %Bta %Y %T')='la  9. toukokuuta 2009 11:26:12'
  strptime('la  9. toukokuuta 2009 11:26:12','%a %e. %Bta %Y %T')=
'e' is a bad directive in format '%a %e. %Bta %Y %T'
  strftime('%d.%m.%Y')='09.05.2009'
  strptime('09.05.2009','%d.%m.%Y')=
2009-05-09 00:00:00
  strftime('%T')='11:26:12'
  strptime('11:26:12','%T')=
'T' is a bad directive in format '%T'

What to do.
Tuomas Vesterinen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with datetime.datetime.strptime

2009-05-10 Thread Tuomas Vesterinen

Nick Craig-Wood wrote:

Tuomas Vesterinen  wrote:
 I hoped that I could get rid of my special module _strptime2 when 
 porting to Python 3.0. But testing is a disappointment.

[snip]

 C :
strftime('%a %b %e %H:%M:%S %Y')='Sat May  9 11:26:12 2009'
strptime('Sat May  9 11:26:12 2009','%a %b %e %H:%M:%S %Y')=
  'e' is a bad directive in format '%a %b %e %H:%M:%S %Y'

[snip]

 What to do.


I'd start by checking out the code for python 3 trunk and seeing if I
could fix it. If I could I'd update the unit tests and the
documentation then submit the patch to the python bugtracker.

If I couldn't fix it then I'd report it as a bug.



Thanks. I have a Python implementation here:

  http://kotisivu.dnainternet.net/tuovest1/booker/booker-0.1.2.tar.gz

See folder booker/csvcnt modules _strptime2.py and time_forms.py.

TV
--
http://mail.python.org/mailman/listinfo/python-list


Ambiguous locale.strxfrm

2009-05-22 Thread Tuomas Vesterinen
This was fixed once in Python 2.5, but in Python 3.0 the bug celebrates 
its comeback. The tail of the strxfrm result is ambiguous.


Python 3.0.1 (r301:69556, Apr 14 2009, 14:30:31)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> locale.setlocale(locale.LC_COLLATE, 'en_US.utf8')
'en_US.utf8'
>>> key1=locale.strxfrm('maupassant guy')
>>>> for i in range(10):
... print(locale.strxfrm('maupassant guy')==key1)
...
False
True
False
False
False
False
False
False
False
False

Tuomas Vesterinen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ambiguous locale.strxfrm

2009-05-23 Thread Tuomas Vesterinen


Thanks. Bug report done, issue 6093.

Tuomas Vesterinen

Gabriel Genellina wrote:
En Fri, 22 May 2009 06:32:40 -0300, Tuomas Vesterinen 
 escribió:


This was fixed once in Python 2.5, but in Python 3.0 the bug 
celebrates its comeback. The tail of the strxfrm result is ambiguous.


Python 3.0.1 (r301:69556, Apr 14 2009, 14:30:31)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import locale
 >>> locale.setlocale(locale.LC_COLLATE, 'en_US.utf8')
'en_US.utf8'
 >>> key1=locale.strxfrm('maupassant guy')
 >>>> for i in range(10):
... print(locale.strxfrm('maupassant guy')==key1)
...
False
True
False
False
False
False
False
False
False
False


I could not reproduce the issue on Windows (I don't have any locale 
using utf8) but you should file a bug report at http://bugs.python.org/




--
http://mail.python.org/mailman/listinfo/python-list


Connecting to the users preferred email client

2009-12-04 Thread Tuomas Vesterinen

If I want to open a html-page from Python code I can say:

>>> import webbrowser
>>> webbrowser.open('index.html')

Is there a standard way to init an email in users preferred email client 
like Thubderbird, Evolution etc.?


Tuomas Vesterinen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Connecting to the users preferred email client

2009-12-04 Thread Tuomas Vesterinen

Mike Driscoll wrote:

On Dec 4, 5:28 am, Tuomas Vesterinen  wrote:

If I want to open a html-page from Python code I can say:

 >>> import webbrowser
 >>> webbrowser.open('index.html')

Is there a standard way to init an email in users preferred email client
like Thubderbird, Evolution etc.?

Tuomas Vesterinen


Check this thread out:

http://www.megasolutions.net/python/invoke-users-standard-mail-client-64348.aspx

Basically, the idea is to pass the mailto url to webbrowser.



OK, that's where we are. Thanks.

Tuomas Vesterinen


---
Mike Driscoll

Blog:   http://blog.pythonlibrary.org

--
http://mail.python.org/mailman/listinfo/python-list


Using site-packages with alt-installed Python version

2010-05-16 Thread Tuomas Vesterinen
I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native 
Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.


Aplication GUI uses:
import pygtk
pygtk.require('2.0')
import gtk
import gobject

I go to:
$ cd /usr/local/lib/python2.4/site-packages

and say:
$ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py
$ sudo ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0

and try:
$ python2.4 gui_utils.py
Traceback (most recent call last):
  File "gui_utils.py", line 57, in ?
import gtk
  File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line 
30, in ?

import gobject as _gobject
  File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py", 
line 26, in ?
from glib import spawn_async, idle_add, timeout_add, 
timeout_add_seconds, \
  File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line 
22, in ?

from glib._glib import *
ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol: 
_PyObject_CallFunction_SizeT


What I should say more to get access to the GTK?

Tuomas Vesterinen
--
http://mail.python.org/mailman/listinfo/python-list


Re: joining files

2010-05-16 Thread Tuomas Vesterinen

On 05/16/2010 05:04 PM, Dave Angel wrote:

(You forgot to include the python-list in your response.  So it only
went to me. Normally, you just do reply-all to the message)

mannu jha wrote:

On Sun, 16 May 2010 13:52:31 +0530 wrote

mannu jha wrote:



Hi,




I have few files like this:
file1:
22 110.1 33 331.5 22.7 5 271.9 17.2 33.4
4 55.1



file1 has total 4 column but some of them are missing in few row.



file2:
5 H
22 0



file3:
4 T
5 B
22 C
121 S




in all these files first column is the main source of matching their
entries. So What I want in the output is only those entries which is
coming in all three files.



output required:



5 271.9 17.2 33.4 5 H 5 T
22 110.1 22 0 22 C


I am trying with this :

from collections import defaultdict

def merge(sources):
blanks = [blank for items, blank, keyfunc in sources]
d = defaultdict(lambda: blanks[:])
for index, (items, blank, keyfunc) in enumerate(sources):
for item in items:
d[keyfunc(item)][index] = item
for key in sorted(d):
yield d[key]

if __name__ == "__main__":
a = open("input1.txt")
c = open("input2.txt")

def key(line):
return line[:2]
def source(stream, blank="", key=key):
return (line.strip() for line in stream), blank, key
for m in merge([source(x) for x in [a,c]]):
print "|".join(c.ljust(10) for c in m)

but with input1.txt:
187 7.79 122.27 54.37 4.26 179.75
194 8.00 121.23 54.79 4.12 180.06
15 8.45 119.04 55.02 4.08 178.89
176 7.78 118.68 54.57 4.20 181.06
180 7.50 119.21 53.93 179.80
190 7.58 120.44 54.62 4.25 180.02
152 8.39 120.63 55.10 4.15 179.10
154 7.79 119.62 54.47 4.22 180.46
175 8.42 120.50 55.31 4.04 180.33
and input2.txt:
15 H 37 H 95 T
124 H 130 H 152 H 154 H 158 H 164 H
175 H 176 H 180 H
187 H 190 T
194 C
196 H 207 H 210 H 232 H it is giving output as:
|
|124 H
|130 H
154 7.79 119.62 54.47 4.22 180.46|158 H
|164 H
175 8.42 120.50 55.31 4.04 180.33|176 H
180 7.50 119.21 53.93 179.80|187 H
190 7.58 120.44 54.62 4.25 180.02|196 H
|207 H
|210 H
|232 H
|37 H
|95 T
so it not matching it properly, can anyone please suggest where I am
doing mistake.




I'm about to travel all day, so my response will be quite brief.

Not sure what you mean by the blank and key values that source() takes,
since they're just passed on to its return value.

I don't see any place where you compare the items from the various
files, so you aren't checking if an item is in multiple files.

DaveA


import os

def merge_sources(sources):
# sources is a list of tuples (source_name, source_data)
data = []
keysets = []
for nme, sce in sources:
lines = {}
for line in sce.split(os.linesep):
lst = line.split()
lines[lst[0]] = (nme, lst)
keysets.append(set(lines.keys()))
data.append(lines)
common_keys = keysets[0]
for keys in keysets[1:]:
common_keys = common_keys.intersection(keys)
result = {}
for key in common_keys:
result[key] = dict(d[key] for d in data if key in d)
return result

if __name__ == "__main__":
# Your test files here are replaced by local strings
print merge_sources([("file1", file1), ("file2", file2), ("file3", 
file3)])

print merge_sources([("input1", input1), ("input2", input2)])

Test_results = '''
{'22': {'file3': ['22', 'C'],
'file2': ['22', '0'],
'file1': ['22', '110.1', '33', '331.5', '22.7', '5', '271.9',
  '17.2', '33.4']}}

{'194': {'input2': ['194', 'C'],
 'input1': ['194', '8.00', '121.23', '54.79', '4.12',
'180.06']},
 '175': {'input2': ['175', 'H', '176', 'H', '180', 'H'],
 'input1': ['175', '8.42', '120.50', '55.31', '4.04',
'180.33']},
  '15': {'input2': ['15', 'H', '37', 'H', '95', 'T'],
 'input1': ['15', '8.45', '119.04', '55.02', '4.08',
'178.89']},
 '187': {'input2': ['187', 'H', '190', 'T'],
 'input1': ['187', '7.79', '122.27', '54.37', '4.26',
'179.75']}}
'''

--
http://mail.python.org/mailman/listinfo/python-list


Re: Using site-packages with alt-installed Python version

2010-05-16 Thread Tuomas Vesterinen

On 05/16/2010 02:38 PM, Alister wrote:

On Sun, 16 May 2010 12:07:08 +0300, Tuomas Vesterinen wrote:


I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native
Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.

Aplication GUI uses:
import pygtk
pygtk.require('2.0')
import gtk
import gobject

I go to:
$ cd /usr/local/lib/python2.4/site-packages

and say:
$ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py $ sudo
ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0

and try:
$ python2.4 gui_utils.py
Traceback (most recent call last):
File "gui_utils.py", line 57, in ?
  import gtk
File
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line
30, in ?
  import gobject as _gobject
File
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py",
line 26, in ?
  from glib import spawn_async, idle_add, timeout_add,
timeout_add_seconds, \
File
"/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line
22, in ?
  from glib._glib import *
ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol:
_PyObject_CallFunction_SizeT

What I should say more to get access to the GTK?

Tuomas Vesterinen


I am not a great expert on this But I think you need to use the Redhat
alternatives system to switch between versions rather than trying to
change things manually.

as i understand it the Alternatives system sets up and changes various
symlinks to ensure everything works correctly.



Yes, my first trial is not the solution because byte compiled .pyc files 
must be produced by the corresponding Python version.


PEP 3147 http://www.python.org/dev/peps/pep-3147 suggests a common 
solution, but only for Python 3.2 and perhaps 2.7. So I am still looking 
for hints. Have You some helpful links to those "Alternatives system"?


Tuomas Vesterinen
--
http://mail.python.org/mailman/listinfo/python-list


Python preprosessor

2009-06-07 Thread Tuomas Vesterinen
I am developing a Python application as a Python2.x and Python3.0 
version. A common code base would make the work easier. So I thought to 
try a preprosessor. GNU cpp handles this kind of code correct:



#ifdef python2
print u'foo', u'bar'
#endif
#ifdef python3
print('foo', 'bar')
#endif


results:
> cpp -E -Dpython2 test_cpp.py
...
print u'foo', u'bar'

Any other suggestions?

Tuomas Vesterinen

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python preprosessor

2009-06-07 Thread Tuomas Vesterinen

Peter Otten wrote:

Tuomas Vesterinen wrote:


I am developing a Python application as a Python2.x and Python3.0
version. A common code base would make the work easier. So I thought to
try a preprosessor. GNU cpp handles this kind of code correct:



Any other suggestions?


http://docs.python.org/dev/3.1/library/2to3.html




I am intensively using 2to3.py. So I have 2 codebase: one in py2 and the 
other in py3. When changing the code I have to do things to 2 separate 
codebase in the repository. There are no patch2to3 or patch3to2, So I 
thought that for ensuring the common functionality of both version it 
would be nice to bring both versions into a common codebase. So I can 
update only one code and automate builds and tests for both versions.


Tuomas Vesterinen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get the class name

2009-06-07 Thread Tuomas Vesterinen

Kless wrote:

Is there any way of to get the class name to avoid to have that write
it?

---
class Foo:
   super(Foo, self)
---


* Using Py 2.6.2


>>> class Foo(object):
... def cls(self):
... return self.__class__
...
>>> Foo().cls()

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python preprosessor

2009-06-08 Thread Tuomas Vesterinen

R. David Murray wrote:

Tuomas Vesterinen  wrote:
I am developing a Python application as a Python2.x and Python3.0 
version. A common code base would make the work easier. So I thought to 
try a preprosessor. GNU cpp handles this kind of code correct:



#ifdef python2
print u'foo', u'bar'
#endif
#ifdef python3
print('foo', 'bar')
#endif


results:
 > cpp -E -Dpython2 test_cpp.py
...
print u'foo', u'bar'

Any other suggestions?


There's a Google Summer of Code project to create a 3to2 processor.
That would let you maintain the code in 3.x, and have it automatically
translated on demand so that it will run under 2.x (where x goes back
to at least 5, I think, but I'm not sure).

Of course, it isn't finished yet, so it won't do you any good right at
the moment :(

--
R. David Murray http://www.bitdance.com
IT ConsultingSystem AdministrationPython Programming



I found also a ready made py3to2-tool (test/develop/integrate python 3.0 
code natively under robust, software-rich python 2.5 environment) at:

  http://code.activestate.com/recipes/574436/
It seems so complicated that I don't dare to try before some more 
experienced people has commented it.


TV
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python preprosessor

2009-06-08 Thread Tuomas Vesterinen

Roger Binns wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Tuomas Vesterinen wrote:

I am intensively using 2to3.py. So I have 2 codebase: one in py2 and the
other in py3.


The expectation would be that you only maintain the py2 code and
automatically generate the py3 code on demand using 2to3.

It is possible to have the same code run under both versions, but not
recommended.  As an example I do this for the APSW test suite, mostly
because the test code deliberately explores various corner cases that
2to3 could not convert (nor should it try!).  Here is how I do the whole
Unicode thing:

if py3: # defined earlier
  UPREFIX=""
else:
  UPREFIX="u"

def u(x): # use with raw strings
  return eval(UPREFIX+"'''"+x+"'''")

# Example of use
u(r"\N${BLACK STAR}\u234")

You can pull similar stunts for bytes (I use buffers in py2), long ints
(needing L suffix in some py2 versions), the next() builtin from py3,
exec syntax differences etc.  You can see more details in the first 120
lines of http://code.google.com/p/apsw/source/browse/apsw/trunk/tests.py

Roger
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkosTxEACgkQmOOfHg372QS4rQCgl1ymNME2kdHTBUoc7/f2e+W6
cbMAmwf7mArr7hVA8k/US53JE59ChnIt
=pQ92
-END PGP SIGNATURE-



You have interesting solutions.

TV
--
http://mail.python.org/mailman/listinfo/python-list


ANNOUNCEMENT: Tinybooker accounting released

2009-08-18 Thread Tuomas Vesterinen

Tinybooker 0.2.2 released at http://tinybooker.org/

Tinybooker is an accounting program offering the dual accounting
core functionality for moderate size accountings:

* Assisted establishing new accountings
* Localized scheme templates
* Easy entering and saving new entries
* Standard reports in plain text or HTML: Income Statement,
  Balance Sheet, Journal, Nominal Ledger, Final Statement
  and Scheme
* Assisted opening the next financial year
* Accounting example as a demo
* Open for auditing, all files human readable plain text
* All written in pure Python
* License GPL3

This early release is for Linux only. Later Tinybooker will be
ported to Windows.

Developers, more translations wanted, join the project contacting
me at https://sourceforge.net/sendmessage.php?touser=2524141.
--
http://mail.python.org/mailman/listinfo/python-list