Referring to Interpreter (Jython)

2006-07-23 Thread wojciech
Hi everyone,

I apologize if this is a bit off-topic. I am currently working on a
Java-based application that is used Jython as a scripting language
within the actual program. However, for one of my GUI elements, I need
to pass the actual PythonInterpeter to the constructor.

I know that in Java there is the "this" keyword which allows an object
to refer to itself. Does anyone know if there is a way to use a similar
type of keyword to have the PythonInterpreter refer to itself?

Thanks,
Wojciech

P.S.

If there is a more appropriate newsgroup to which I should post this,
please let me know.

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


Re: Referring to Interpreter (Jython)

2006-07-23 Thread wojciech
Hi everyone,

Ah, after some more searching and programming, I got it:

PythonInterpreter py = new PythonInterpreter();
py.set("interpreter", py);

Thanks,
Wojciech

[EMAIL PROTECTED] wrote:
> Hi everyone,
>
> I apologize if this is a bit off-topic. I am currently working on a
> Java-based application that is used Jython as a scripting language
> within the actual program. However, for one of my GUI elements, I need
> to pass the actual PythonInterpeter to the constructor.
>
> I know that in Java there is the "this" keyword which allows an object
> to refer to itself. Does anyone know if there is a way to use a similar
> type of keyword to have the PythonInterpreter refer to itself?
>
> Thanks,
> Wojciech
>
> P.S.
>
> If there is a more appropriate newsgroup to which I should post this,
> please let me know.

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


Re: Lots of pdf files

2005-07-20 Thread Wojciech Mula
Greg Lindstrom wrote:
> There does not appear to be a simple way to merge many pdf's into one.  

Program pdftk can merge pdf's, but I have never tried it.
You may also use pdflatex --- there is a package called pdfpages
provides powerful command \includepdf.

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


Re: Suggestions for optimizing my code

2005-08-05 Thread Wojciech Mula
drife wrote:
> [...]
> for row in range(len(Y)):
> for col in range(0,row):

In this case you should use 'xrange' instead 'range'.

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


Re: is there a better way to check an array?

2005-09-01 Thread Wojciech Mula
jdonnell wrote:
> I want to check if a value is in an array. I'm currently doing it as
> follows, but I just don't like this way of doing it. It seems
> unpythonic.
> 
> fieldIsRequired = true
> try:
> notRequiredAry.index(k)
> fieldIsRequired = false
> except ValueError:
> pass
> 
> # throw expception if field is required and is empty
> if(product[k] == '' and fieldIsRequired):
> raise GMError(k + ' is required')

if product[k] == '' and k in notRequiredAry:
raise GMError(k + ' is required')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SSH/Telnet program to Router/switch

2014-02-19 Thread Wojciech Łysiak
On 19.02.2014 09:14, Sujith S wrote:
> Hi,
> 
> I am new to programming and python. I am looking for a python script to do 
> ssh/telnet to a network equipment ? I know tcl/perl does this using 
> expect/send. 
> 
> Do we have expect available in python as well or need to use some other 
> method ?

Hello,
 If you are looking for a way to connect to your netdevices and then
execute some shell commands (with output) via ssh then google for
paramiko module for python.

It works on windows and linux.

-- 
BR,
Wojtek
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Confused with Functions and decorators

2014-07-19 Thread Wojciech Giel


On 19/07/14 11:52, Jerry lu wrote:

Ok so i am trying to learn this and i do not understand some of it. I also 
tried to searched the web but i couldnt find any answers.

1. I dont understand when i will need to use a function that returns another 
function.
eg
def outer():
  def inner():
x = 5
   return inner
 
  why not just use inner and forget about the whole outer function?
function compositing is one possible use. Functions are first class 
objects so they can be passed as arguments to other functions. in math 
you can define function composition  f(x)  * g(x) by saying that (f * g 
)(x) = f(g(x)).
so composition of two functions gives you a new function with behaviour 
the same as applying fist function to the output of the second.


ex.
you are give two functions f and g to construct their composition:

>>> def outer(f, g):
... def inner(x):
... return f(g(x))
... return inner
...
>>> def f(x):
... print("f ({}) called".format(x))
... return x
...
>>> def g(x):
... print("g ({}) called".format(x))
... return x
...
>>> h = outer(f, g)
>>> h("test")
g (test) called
f (test) called
'test'

2. This is more yes or no question when you pass in a func into another func as 
a parameter do you need to specify the parameter that the func is being passed 
into as func?
eg
   def passinto(func)
 pass
 
def param():

  x = 5

 p = passinto(param)


also is this above statement correct?
  


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


Re: Confused with Functions and decorators

2014-07-19 Thread Wojciech Giel


On 19/07/14 11:52, Jerry lu wrote:

Ok so i am trying to learn this and i do not understand some of it. I also 
tried to searched the web but i couldnt find any answers.

1. I dont understand when i will need to use a function that returns another 
function.
eg
def outer():
  def inner():
x = 5
   return inner
 
  why not just use inner and forget about the whole outer function?
function compositing is one possible use. Functions are first class 
objects so they can be passed as arguments to other functions. in math 
you can define function composition  f(x)  * g(x) by saying that (f * g 
)(x) = f(g(x)).
so composition of two functions gives you a new function with behaviour 
the same as applying fist function to the output of the second.


ex.
you are give two functions f and g to construct their composition:

>>> def outer(f, g):
... def inner(x):
... return f(g(x))
... return inner
...
>>> def f(x):
... print("f ({}) called".format(x))
... return x
...
>>> def g(x):
... print("g ({}) called".format(x))
... return x
...
>>> h = outer(f, g)
>>> h("test")
g (test) called
f (test) called
'test'

cheers
Wojciech
--
https://mail.python.org/mailman/listinfo/python-list


Re: Confused with Functions and decorators

2014-07-19 Thread Wojciech Giel

On 19/07/14 12:40, Jerry lu wrote:

oh yeah i forgot about the decorators. Um say that you wanted to decorate a 
function with the outer() func you would just put @outer on top of it? And this 
is the same as passing another func into the outer func?

yes.
syntax was added because with very long function definitions it was 
dificult  to track reassignment to the name when it followed definition 
of the function. decorators is just abbreviation.


>>> def outer(f):
... def inner(*args, **kwargs):
... print("inner function")
... return f(*args, **kwargs)
... return inner
...
>>> @outer
... def myfunc(x):
... print("Myfunc", x)
...
>>> myfunc("test")
inner function
Myfunc test

it is exactly equivalent to:

>>> def outer(f):
... def inner(*args, **kwargs):
... print("inner function")
... return f(*args, **kwargs)
... return inner
...
>>> def myfunc(x):
...  print("Myfunc", x)
...
>>> myfunc = outer(myfunc)
>>> myfunc("test")
inner function
Myfunc test

cheers
Wojciech


and also with the first example you say x is in the scope when is was created 
can you define x in the outer func and refer to it in the inner func?

check nonlocal.

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


Re: What's the proper style for a library string function?

2014-07-19 Thread Wojciech Giel

On 19/07/14 18:38, C.D. Reimer wrote:

Greetings,

I typically write a Python 2.7 string function in my library like this:

def getCompletedTime(start, end): return "Time completed:", 
str(end - start)


And called it like this:

print getCompletedTime(start, end)

Since every Python script I write is executed from the command line, I 
rewrote the string function like this:


def getCompletedTime(start, end): print "Time completed:", str(end 
- start)


And call it like this:

getCompletedTime(start, end)

The first version is what I'm familiar with having reluctantly learned 
Java at community college, which couldn't afford a Microsoft site 
license for Visual C++ and taught every class in Java. (The Linux 
instructor rebelled against this policy by teaching basic C/C++ and 
shell scripting in his classes.) I recently read an article that 
Python is replacing Java as a teaching language.


The second version is more straight forward but seems less readable 
(i.e., "print getCompletedTime(start, end)" vs. 
"getCompletedTime(start, end)") from the calling script.


Alternatively, I thought about rewriting the string function to accept 
an extra parameter to do either and default to the print statement.


def getCompletedTime(start, end, type = 'p'):
string = "Time completed: " + str(end - start)
if type == 'p':
print string
else:
return string

I'm curious as to what the proper Python style would be for this.
You might look into PEP8 "Style Guide for Python Code" it will give you 
recommendation how to write a code. among other gives most sensible answer:
 "Consistency within a project is more important. Consistency within 
one module or function is most important.. When in doubt, use your 
best judgment. Look at other examples and decide what looks best."


http://legacy.python.org/dev/peps/pep-0008/#function-names

for me if you will be reusing this function I would just use:
 def getCompletedTime(start, end): return "Time completed:", str(end - 
start)


if you need to print just add print, if you want result from this 
function somewhere else you got it. adding additional arguments 
necessary adds complexity. do you really need it. Keep it simple stupid 
expression can be applied everywhere.

cheers
Wojciech
--
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to iterate through multidimensional space?

2014-08-06 Thread Wojciech Giel
You might check numpy it is really powerful tool for working with multi 
dimensional arrays:


ex.
>>> a = arange(81).reshape(3,3,3,3)
>>> a

array( 0,  1,  2],
 [ 3,  4,  5],
 [ 6,  7,  8]],

[[ 9, 10, 11],
 [12, 13, 14],
 [15, 16, 17]],

[[18, 19, 20],
 [21, 22, 23],
 [24, 25, 26]]],


   [[[27, 28, 29],
 [30, 31, 32],
 [33, 34, 35]],

[[36, 37, 38],
 [39, 40, 41],
 [42, 43, 44]],

[[45, 46, 47],
 [48, 49, 50],
 [51, 52, 53]]],


   [[[54, 55, 56],
 [57, 58, 59],
 [60, 61, 62]],

[[63, 64, 65],
 [66, 67, 68],
 [69, 70, 71]],

[[72, 73, 74],
 [75, 76, 77],
 [78, 79, 80)

>>> f = a.flat
>>> for i in f:
...print(i)
0
1
2
..
98
99

cheers
Wojciech



On 05/08/14 21:06, Frank Miles wrote:

I need to evaluate a complicated function over a multidimensional space
as part of an optimization problem.  This is a somewhat general problem
in which the number of dimensions and the function being evaluated can
vary from problem to problem.

I've got a working version (with loads of conditionals, and it only works
to #dimensions <= 10), but I'd like something simpler and clearer and
less hard-coded.

I've web-searched for some plausible method, but haven't found anything
"nice".  Any recommendations where I should look, or what technique should
be used?

TIA!


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


Re: double underscore attributes?

2005-12-10 Thread Wojciech Mula
[EMAIL PROTECTED] wrote:
> Now I went to Python Library Reference and searched for "__add__" but
> got zero hits.

http://python.org/doc/2.4.2/ref/specialnames.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Data Explorer

2006-07-16 Thread Wojciech Morański
Does anybody know some GUI (preferably QT) application  which can be
use to explore pickled python objects? Similar functionality has a
PyDev Debugger in Eclipse, but I would like to have a standalone
application. I know that it is not hard to write it, but I don't want
to again invent a wheel ;o)
Thanks for any help

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


Re: create global variables?

2006-10-30 Thread Wojciech Muła
Alistair King wrote:
> is there a simple way of creating global variables within a function?

def foo(name):
globals()[name] = "xxx"
globals()[name + 'aa'] = "yyy"
globals()[name + 'ab'] = "zzz"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatter for tuple

2006-11-02 Thread Wojciech Muła
Tim Chase wrote:
>   print "a = %s" % repr(a)

or
print "a = %r" % (a,)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to choose the right GUI toolkit ?

2006-11-09 Thread Wojciech Muła
Nick Craig-Wood wrote:
>>  It's very mature, full-featured, and portable, and fairly easy to
>>  learn as well.
>
> ...with native look and feel on each platform unlike GTK / TK

AFAIK Tk 8 uses platform's native widgets.

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


Re: Tkinter: Strange behavior using place() and changing cursors

2006-11-14 Thread Wojciech Muła
Mudcat wrote:
> [...]

You have to set cursor once, Tk change it automatically:

>   def buildFrame(self):
>   self.f = Frame(self.master, height=32, width=32, relief=RIDGE,
> borderwidth=2)
>   self.f.place(relx=.5,rely=.5)
#self.f.bind( '', self.enterFrame )
#self.f.bind( '', self.leaveFrame )
self.f.configure(cursor = 'sb_h_double_arrow')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: Strange behavior using place() and changing cursors

2006-11-14 Thread Wojciech Muła
Mudcat wrote:
> I have also determined that this is not a problem if the button is not
> packed inside the frame.  So somehow the interaction of the internal
> button is causing this problem.

Problem is really strange, and seems to be a Tk issue, not Tkinter.
I've observed that if method configure is called and **any** parameter
of frame is changed, then frame "forgets" all its children, gets natural
size and then pack children again!  This just(?) causes flickering, and
do not depend on geometry manager --- all place, pack and grid work in
this way.  But only place causes the problem --- I guess it do not block
events, or generate some events.

Workaround:

class Widget:
def __init__(self, master):
self.master = master
self.buildFrame()
self.buildWidget()
self.x = 0
self.y = 0

# [snip]

def enterFrame(self, event):
if self.x != event.x or self.y != event.y:
self.f.configure(cursor = 'sb_h_double_arrow')
self.x, self.y = event.x, event.y

def leaveFrame(self, event):
if self.x != event.x or self.y != event.y:
self.f.configure(cursor = '')
self.x, self.y = event.x, event.y

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


Re: math.pow(x,y)

2006-06-11 Thread Wojciech Muła
fl1p-fl0p wrote:
> import math
> math.pow(34564323, 456356)
>
> will give math range error.
>
> how can i force python to process huge integers without math range
> error? Any modules i can use possibly?

You have to use operator **, i.e. 34564323**456356
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Negative hex to int

2006-06-14 Thread Wojciech Muła
[EMAIL PROTECTED] wrote:
> The problem is negative values. If the unit returns the hex value 'e7',
> it means -25, but python says it's 231:
> ---
 int('e7', 16)
> 231
> ---
>
> Does anyone have a clue a to what I need to do?

def u2(x):
if x & 0x80: # MSB set -> neg.
return -((~x & 0xff) + 1)
else:
return x

>>> u2(int('e7', 16))
-25
>>> u2(int('12', 16))
18
>>>

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


Re: length of multidimensional table

2006-12-17 Thread Wojciech Muła
vertigo wrote:
> i have:
> x = zeros([3,4],Float)
>
> how can i check how many rows and columns x have ?
> (what is the X and Y size of that table) ?

Data member x.shape (tuple) contains
dimensions of array.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fuzzy string comparison

2006-12-26 Thread Wojciech Muła
Steve Bergman wrote:
> I'm looking for a module to do fuzzy comparison of strings. [...]

Check module difflib, it returns difference between two sequences.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Change coords of a canvas.line item

2007-01-05 Thread Wojciech Muła
Fredrik Lundh wrote:
> Matthias Vodel wrote:
>
>> I want to change the beginning/end-coordinates of a canvas.line item.
>>
>> Something like:
>>
>> self.myCanvas.itemconfigure(item_id, coords=(x1_new, y1_new, x2_new, y2_new))
>
> self.myCanvas.coords(item_id, x1_new, y1_new, x2_new, y2_new)

You can also use insert and dchars methods to add and delete
vertices (useful for polylines/polygons).

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


Re: More Efficient fnmatch.fnmatch for multiple patterns?

2007-01-08 Thread Wojciech Muła
abcd wrote:
> I am using fnmatch.fnmatch to find some files.  The only problem I have
> is that it only takes one pattern...so if I want to search using
> multiple patterns I have to do something like
>
> patterns = ['abc*.txt', 'foo*']
> 
> for p in patterns:
> if fnmatch.fnmatch(some_file_name, p):
> return True
>
> ...is there a built-in function that will match using multiple patterns?

import re
pats = re.compile('|'.join(fnmatch.translate(p) for p in patterns))

if pats.match(some_file_name):
return True

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


restricted mode (2.4.2)

2006-02-17 Thread Wojciech Pawlikowski
Hey,
I work on some project where main part (core) is coded in C
(for speed) and the rest is in Python. Python API is used
to launch python modules without using any exec() system()
calls (thread safe). During debugging I found that
many of Python modules fails to work because restricted mode:

Traceback (most recent call last):
   File "../modules/scan/dns_forward.py", line 167, in scan_element
 d = DNSForward(domainname)
   File "../modules/scan/dns_forward.py", line 20, in __init__
 self.__r = dns.resolver.Resolver()
   File "/usr/lib/python2.4/site-packages/dns/resolver.py", line 270, in 
__init__
 self.read_resolv_conf(filename)
   File "/usr/lib/python2.4/site-packages/dns/resolver.py", line 295, in 
read_resolv_conf
 f = open(f, 'r')
IOError: file() constructor not accessible in restricted mode

Is there any way to avoid this mode ?

-- 
___
* Wojciech Pawlikowski  ::  ::  GG: 4155781 *
* http://www.knockdownhc.com   ||  http://www.kingofthehillhc.com *
*  "Loved by a few, Hated by many, But respected by ALL"  *
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter toggle a Label Widget based on checkbutton value

2007-07-04 Thread Wojciech Muła
O.R.Senthil Kumaran wrote:
> Any suggestions on  how can i make this checkbutton effect.
> 1) Press Enable IP, the Label IP should be shown.
> 2) Toggle Enable IP (So that its unset). the Label IP should not be shown.
>
> #!/usr/bin/python
> from Tkinter import *
> root = Tk()
> root.title('something')
> x = StringVar()

ip = Label(root,text="IP:")
> def display():
  global ip
> if x.get():
> #ip = Label(root,text="IP:")
> ip.grid(row=3,column=0)
   else:
  ip.grid_forget()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: atexit, sys.exit, sys.exitfunc, reaching end of source code

2007-07-11 Thread Wojciech Muła
[EMAIL PROTECTED] wrote:
> I am playing with the atexit module but I don't find a way to see the
> difference
> between a script calling sys.exit() and the interpreting
> arriving at the end
> of the source code file. This has a semantic difference for my
> applications.
> Is there a way to determine in an exithandler (that is registered
> using atexit.register)
> how I exited?

Actually sys.exit raises exception SystemExit, but if interpreter
reaches end of script exception is not raised.  Try something
like this:

if __name__ == '__main__':
exit_code_for_exithandler = None
try:
#...
sys.exit(5)
pass
#...
except SystemExit, e:
exit_code_for_exithandler = e.code
print "sys.exit called"
else:
print "end of script"

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


Re: Itertools question: how to call a function n times?

2007-07-19 Thread Wojciech Muła
Matthew Wilson wrote:
> I want to write a function that each time it gets called, it returns a
> random choice of 1 to 5 words from a list of words.
>
> I can write this easily using for loops and random.choice(wordlist) and
> random.randint(1, 5).
>
> But I want to know how to do this using itertools, since I don't like
> manually doing stuff like:
>
> phrase = list()
> for i in random.randint(1, 5):
>
> phrase.append(random.choice(wordlist))

Use list comprehension:

phrase = [random.choice(wordlist) for i in xrange(random.randint(1, 5))]

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


Re: regular expression for parsing an html element

2007-04-20 Thread Wojciech Muła
abcd wrote:
> My regex so far is:  src=\"(.*)\" however the group in this case
> would end up being, image/blah/a.jpg" id="d">blah blah blah a>.
> 
> how can I tell the regex group (.*) to end when it gets to the first
> " ?

Use non-greedy matching, i.e. src=\"(.*?)\" (question mark after *.)
See: http://docs.python.org/lib/re-syntax.html

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


Re: tkinter paint program

2007-04-24 Thread Wojciech Muła
Gigs_ wrote:
> I'm working on tkinter paint program, mostly to learn tkinter canvas.
> I have method which create buttons for oval, rectangle, line, polygon etc.
> How to make oval button to be sunken when i click it and to remain 
> sunken until i click on another button (like rectangle and than is 
> another button sunken)?

You can use radiobuttons.  If attribute indicatoron is 0, then 
radiobuttons are drawn as regular buttons.  With attribute
selectcolor you can set background color of selected button.

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


Re: custom plugin architecture: how to see parent namespace?

2007-07-22 Thread Wojciech Muła
escalation746 wrote:
> def ViewValuable():
  
[...]
> code = """
> Hello()
> Plus()
> Valuable()
  
> """

These names don't match.  I replaced Valuable() with proper name,
and everything work fine.

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


Re: split a string of space separated substrings - elegant solution?

2007-07-31 Thread Wojciech Muła
Helmut Jarausch wrote:
> Hi,
>
> I'm looking for an elegant solution to the following (quite common)
> problem:
>
> Given a string of substrings separated by white space,
> split this into tuple/list of elements.
> The problem are quoted substrings like
>
> abc "xy z"  "1 2 3"  "a \" x"
>
> should be split into  ('abc','xy z','1 2 3','a " x')

import csv

s = 'abc "xy z"  "1 2 3"  "a \\" x"'
r = iter(csv.reader([s], delimiter=" ", escapechar="\\"))
print r.next()

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


Re: Memory Leak with Tkinter Canvas (Python 2.5 Win32)

2007-08-02 Thread Wojciech Muła
frikk wrote:
> [...]
> As you can see- I am doing nothing other than drawing a lot of
> rectangles on the canvas.

You aren't drawing, but **creating** rectangle objects, as
a meth. name suggests.  You find more info at tkinter.effbot.org.

> [...]
>
> def clear_grid():

  canv.delete(ALL)
 
> for i in range(0,HEIGHT/10):
> for j in range(0, HEIGHT/10):
> canv.create_rectangle(i*10,j*10, \
>   i*10+10, j*10+10, \
>   fill = "white")

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


Re: interpreting glyph outlines from ttfquery?

2007-03-22 Thread Wojciech Muła
swiftset wrote:
> I'm try to convert a glyph into a format I can easily numerically
> manipulate. So far I've figured out how to use ttfquery to get a list
> that represents the outline of a contour in a glyph:
> 
> from ttfquery import describe, glyphquery, glyph
> f = describe.openFont("/usr/share/fonts/truetype/freefont/
> FreeSans.ttf")
> n = glyphquery.glyphName(f, 'D')
> g = glyph.Glyph(n)
> c = g.calculateContours(f)
> o = glyph.decomposeOutline(c[1])
> 
> o looks like:
> 
> [array([182,  82],'s'),
> (354, 82),
> (420.29, 90.014),
> (474.91, 114.0), ...,
> array([182,  82],'s'),
> array([182,  82],'s')]
> 
> Is this a polyline?

decomposeOutline docstring confirms -- it's a polyline.  I think 
elements marked with 's' starts new subpath.

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


Re: call to function by text variable

2007-03-25 Thread Wojciech Muła
ianaré wrote:
> like this:
> 
> 
> list = ["Replace", "ChangeCase", "Move"]
> textVariable = list[n]
> self.operations.insert(pos, operations.[textVariable].Panel(self,
> main))
> 
> Is something sort of like that possible?

Yes:

self.operations.insert(
pos,
getattr(operations, textVariable).Panel(self.main)
)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XML minidom Parsing and ToPrettyXML

2007-03-25 Thread Wojciech Muła
Paul Kozik wrote:
> However, if I use xml.minidom.parse to parse the xml document, change
> a few attributes with setAttribute, then write back with toprettyxml,
> my XML file gets loaded up with spaces between many of the elements.

Use 'toxml' method, that writes XML document without any modification.

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


Re: pattern search

2007-03-27 Thread Wojciech Muła
Fabian Braennstroem wrote:
> Now, I would like to improve it by searching for different 'real'
> patterns just like using 'ls' in bash. E.g. the entry
> 'car*.pdf' should select all pdf files with a beginning 'car'.
> Does anyone have an idea, how to do it?

Use module glob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cascading ifs

2007-04-02 Thread Wojciech Muła
Ernesto García García wrote:
> Hi experts,
> 
> How would you do this without the more and more indenting cascade of ifs?:
> 
> match = my_regex.search(line)
> if match:
>   doSomething(line)
> else:
>   match = my_regex2.search(line)
>   if match:
> doSomething2(line)
>   else:
> match = my_regex3.search(line)
> if match:
>   doSomething3(line)
> 
> etc.

tbl = [(my_regex, doSomething), (my_regex2, doSomething2), (my_regex3, 
doSomething3)]
for regex, fun in tbl:
 match = regexp.match(line)
 if match:
fun(line)
break

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


Re: 08 and 09 in sequence create "invalid token" error?!

2007-04-06 Thread Wojciech Muła
IamIan wrote:
> I am confused as to why including 08 or 09 in a sequence (list or
> tuple) causes this error. All other numbers with a leading zero work.

All literals that start with "0" digit are considered as
octal numbers, i.e. only digits "0".."7" are allowed.

See octinteger lexical definition:
http://docs.python.org/ref/integers.html

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


Re: Saving output of Turtle Graphics?

2007-04-07 Thread Wojciech Muła
Dick Moores wrote:
> I accidentally stumbled across the Turtle Graphics module (turtle.py) 
> the other day and have been having some fun with it.
> 
> Now I'm wondering if there is a way to build into a script the saving of 
> each window just before it is cleared. For example, here are a couple 
> that I've saved by screen capture:
> 
> 

Turtle module uses Tk canvas element to draw graphics ('_canvas'
attribute). I've written module, that exports canvas graphics to SVG
file: http://wmula.republika.pl/proj/canvas2svg/ -- it may be useful
for you.

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


Re: Checking whether list element exists

2007-04-07 Thread Wojciech Muła
Rehceb Rotkiv wrote:
> I want to check whether, for example, the element myList[-3] exists. So 
> far I did it like this:
> 
> index = -3
> if len(myList) >= abs(index):
>   print myList[index]

IMHO it is good way.

> Another idea I had was to (ab-?)use the try...except structure:
> 
> index = -3
> try:
>   print myList[index]
> except:
>   print "Does not exist!"

In general case it won't work, because lists accept negative indexes:
http://docs.python.org/lib/typesseq.html, 3rd note.

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


Re: Saving output of Turtle Graphics?

2007-04-07 Thread Wojciech Muła
Dick Moores wrote:
>> Turtle module uses Tk canvas element to draw graphics ('_canvas'
>> attribute). I've written module, that exports canvas graphics to SVG
>> file: http://wmula.republika.pl/proj/canvas2svg/ -- it may be useful
>> for you.
> 
> I afraid I'm totally unfamiliar with SVG. Would it be possible for you
> or someone else on the list to show how to use your module to export the 
> simple product of this simple script to an SVG file?
> 
> ===
> import turtle as T
import canvasvg
> from random import randint
> T.setup(width=1000, height=700, startx=0, starty=0)
> T.color(1, .5, .5)
> T.begin_fill()
> # 2 connected lines will fill as a triangle
> for x in range(2):
> coord = (randint(-500,500), randint(-350,350))
> T.goto(coord)
> T.end_fill()

canvasvg.saveall("image.svg", T._canvas)

> T.done()
> 

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


Re: Saving output of Turtle Graphics?

2007-04-07 Thread Wojciech Muła
Dick Moores wrote:
> What do I do to see this?

For example Opera 9 and Firefox 1.5+ are able to view SVG files;
there is a free plugin for IrfanView.

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


Re: list comparison help?

2007-04-14 Thread Wojciech Muła
Dropkick Punt wrote:
 prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", 
 "u"]
> 
> And I have a string, that I split() into a list.
> 
 sentence = "what the blazes is this"
 sentence = sentence.split()
> 
> Now I want to strip the sentence of all words in the prefix list. 
> 
> I tried this method:
> 
 for x in prefixes:
> ... if sentence.index(x):
> ... del sentence[sentence.index(x)]
> 
> 
> This raises, the error: 
> 
> Traceback (most recent call last):
>   File "", line 3, in ?
> ValueError: list.index(x): x not in list
> 
> This puzzles me, because if x isn't in the list, the subroutine shouldn't 
> attempt to delete it
> from the list, so I'm not sure why it's complaining.

list.index raised ValueError, see error message.

> Can anybody explain this to me, &/or show me a better way to do it?

prefixes = set(prefixes)
sentence = [word for word in sentence.split() if word not in prefixes]

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


Python "implements " equivalent?

2007-10-04 Thread Wojciech Gryc
Hi,

I recently started using Python and am extremely happy with how
productive it's made me, even as a new user. I'm hoping to continue
using the language for my research, and have come across a bit of a
stumbling block.

I'm a seasoned Java programmer and quite a big fan of interfaces...
i.e. The idea that if I make a number of distinct classes that
implement interface X, I can pass them all as parameters to functions
or whatnot that require an X object.

Is there something similar in Python?

What I'd like to do is create a feature detection system for my work
-- specifically, a general class / interface called "Feature" and then
subclasses that implement functions like isFeaturePresent() in all of
their different and unique ways. I'd love to hear how I can do this in
Python.

Thanks,
Wojciech

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


Re: Python "implements " equivalent?

2007-10-04 Thread Wojciech Gryc
Thank you Carl and thank you Jarek. This makes me feel much better --
on to coding, I shall go. :)

Thanks again,
Wojciech

On Oct 4, 11:27 am, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Oct 4, 11:11 am, Wojciech Gryc <[EMAIL PROTECTED]> wrote:
>
> > Hi,
>
> > I recently started using Python and am extremely happy with how
> > productive it's made me, even as a new user. I'm hoping to continue
> > using the language for my research, and have come across a bit of a
> > stumbling block.
>
> > I'm a seasoned Java programmer and quite a big fan of interfaces...
> > i.e. The idea that if I make a number of distinct classes that
> > implement interface X, I can pass them all as parameters to functions
> > or whatnot that require an X object.
>
> > Is there something similar in Python?
>
> Yes: you do it pretty much the same way you'd do it in Java, except
> for two differences:
> * leave out the "implements Interface" part
> * don't actually create an Interface class
>
> And then, voila!, you can write functions that can accept any class
> that implements your interface.
>
> > What I'd like to do is create a feature detection system for my work
> > -- specifically, a general class / interface called "Feature" and then
> > subclasses that implement functions like isFeaturePresent() in all of
> > their different and unique ways. I'd love to hear how I can do this in
> > Python.
>
> Just define isFeaturePresent() in any class you want.  That's all you
> have to do; any class that defines this method can be passed to any
> function that invokes it, without having to "implement" or "subclass"
> anything.
>
> This is known as "duck typing" in Python lingo.
>
> Carl Banks


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


Re: Trouble with max() and __cmp__()

2007-01-28 Thread Wojciech Muła
Thomas Nelson wrote:
> My code:
>
> class Policy(list):
> def __cmp__(self,other):
> return cmp(self.fitness,other.fitness)

Define method __gt__.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conversion of string to integer

2007-01-29 Thread Wojciech Muła
jupiter wrote:
> I have a problem. I have a list which contains strings and numeric. 
> What I want is to compare them in loop, ignore string and create 
> another list of numeric values.
>
> I tried int() and decimal() but without success.
>
> eq of problem is
>
> #hs=string.split(hs)
> hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"]

tmp = []
for s in hs:
try:
tmp.append( float(s) )
except ValueError:
# function float raises VE, if string 's' doesn't
# represent a number
pass

# tmp contains a list of floats
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Vim search under cursor

2007-02-07 Thread Wojciech Muła
[EMAIL PROTECTED] wrote:
> Hi, I am using gvim to edit python source files. When I press "*" or
> "#", I would want to search for the attribute name under the cursor
> and not the entire string.
>  For example, If I have os.error and pressing * on top of error
> searches for os.error rather than error. How to set this, any Idea?

Press / then Ctrl-R-A then enter -- of course you should recored it
as a macro.

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


readlines() reading incorrect number of lines?

2007-12-20 Thread Wojciech Gryc
Hi,

I'm currently using Python to deal with a fairly large text file (800
MB), which I know has about 85,000 lines of text. I can confirm this
because (1) I built the file myself, and (2) running a basic Java
program to count lines yields a number in that range.

However, when I use Python's various methods -- readline(),
readlines(), or xreadlines() and loop through the lines of the file,
the line program exits at 16,000 lines. No error output or anything --
it seems the end of the loop was reached, and the code was executed
successfully.

I'm baffled and confused, and would be grateful for any advice as to
what I'm doing wrong, or why this may be happening.

Thank you,
Wojciech Gryc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: readlines() reading incorrect number of lines?

2007-12-20 Thread Wojciech Gryc
Hi,

Python 2.5, on Windows XP. Actually, I think you may be right about
\x1a -- there's a few lines that definitely have some strange
character sequences, so this would make sense... Would you happen to
know how I can actually fix this (e.g. replace the character)? Since
Python doesn't see the rest of the file, I don't even know how to get
to it to fix the problem... Due to the nature of the data I'm working
with, manual editing is also not an option.

Thanks,
Wojciech

On Dec 20, 3:30 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Dec 21, 6:48 am, Wojciech Gryc <[EMAIL PROTECTED]> wrote:
>
> > Hi,
>
> > I'm currently using Python to deal with a fairly large text file (800
> > MB), which I know has about 85,000 lines of text. I can confirm this
> > because (1) I built the file myself, and (2) running a basic Java
> > program to count lines yields a number in that range.
>
> > However, when I use Python's various methods -- readline(),
> > readlines(), or xreadlines() and loop through the lines of the file,
> > the line program exits at 16,000 lines. No error output or anything --
> > it seems the end of the loop was reached, and the code was executed
> > successfully.
>
> > I'm baffled and confused, and would be grateful for any advice as to
> > what I'm doing wrong, or why this may be happening.
>
> What platform, what version of python?
>
> One possibility: you are running this on Windows and the file contains
> Ctrl-Z aka chr(26) aka '\x1a'.

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


Re: list example

2006-04-22 Thread Wojciech Muła
PAolo wrote:
> any comment, suggestion? Is there something not elegant?

Try this:

even = range(10)[0::2]
odd  = range(10)[1::2]

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


Re: index in for loops

2006-05-17 Thread Wojciech Muła
manstey wrote:
> in for loops like the following:
>
> word='abcade'
>
> for letter in word:
>print letter
>
>
> Is it possible to get the position of letter for any iteration through
> the loop?

for index, letter in enumerate(word):
print index, letter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting of list containing tuples

2006-05-18 Thread Wojciech Muła
Ronny Mandal wrote:
> Assume we have a list l, containing tuples t1,t2...
>
> i.e. l = [(2,3),(3,2),(6,5)]
>
> And now I want to sort l reverse by the second element in the tuple,
> i.e the result should ideally be:
>
>  l = [(6,5),(2,3),(3,2)]
>
>
> Any ideas of how to accomplish this?

def cmpfun(a,b):
return cmp(b[1],a[1])

l.sort(cmpfun)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread Wojciech Muła
"David Hláčik"  wrote:

> I have to create stable algorithm for sorting n numbers from interval
> [1,n^2] with time complexity O(n) .

Some kind of radix sort or counting sort.  These algo. has O(n) complexity.

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


Re: 1 or 1/0 doesn't raise an exception

2008-12-13 Thread Wojciech Muła
"Daniel Fetchinson"  wrote:

> Is it a feature that
> 
> 1 or 1/0
> 
> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale?

See: http://en.wikipedia.org/wiki/Short-circuit_evaluation
--
http://mail.python.org/mailman/listinfo/python-list


Re: Determine socket family at runtime

2008-05-04 Thread Wojciech Walczak
2008/5/4, Giampaolo Rodola' <[EMAIL PROTECTED]>:
>  For now I've been able to determine the family by using:
>
>  # self.socket = a connected socket.socket instance
>  ip, port = self.socket.getsockname()[0:2]
>  af = socket.getaddrinfo(ip, port)[0][0]
>
>  ...but I'd like to know if some other solution is preferable.

Nope, there is none. Using getaddrinfo() to check address family
is the de facto standard.

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: confused about self, why not a reserved word?

2008-05-05 Thread Wojciech Walczak
2008/5/5, globalrev <[EMAIL PROTECTED]>:
> class Foo(object):
> def Hello(self):
> print "hi"
>
>  object is purple, ie some sort of reserved word.
>
>  why is self in black(ie a normal word) when it has special powers.
>  replacing it with sel for example will cause an error when calling
>  Hello.

Could you give an example of such an error?

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame music, cant read mp3?

2008-05-05 Thread Wojciech Walczak
2008/5/5, globalrev <[EMAIL PROTECTED]>:
> pygame.mixer.music.load('C:/Python25/myPrograms/pygameProgs/example1.mp3')


Are you sure that:

os.path.exists('C:/Python25/myPrograms/pygameProgs/example1.mp3') == True?

Check it with python.

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decimal vs Float comparasion

2008-05-05 Thread Wojciech Walczak
2008/5/6, Yuan HOng <[EMAIL PROTECTED]>:
>  It seems decimal object will always be larger than float in
>  comparasion, which goes against common sense:
>
>  >>> from decimal import Decimal
>  >>> a = Decimal('0.5')
>  >>> a > 9
>  False
>  >>> a > 9.0
>  True
>
>  It seems to me that rather than allowing this to happen, comparasion
>  between the two should either be made correct (by convertion decimal
>  to float e.g.) or forbidden, like arithmatic operations between the
>  two types.

Looks like a nasty bug.

a > 9.0 returns True because NotImplemented > 9.0 returns True.
a < 9.0 returns False because NotImplemented < 9.0 returns False.

As you can see the real comparision has nothing to do with your Decimal number.
I think you can report it at bugs.python.org.

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decimal vs Float comparasion

2008-05-05 Thread Wojciech Walczak
2008/5/6, Wojciech Walczak <[EMAIL PROTECTED]>:
>  a > 9.0 returns True because NotImplemented > 9.0 returns True.
>  a < 9.0 returns False because NotImplemented < 9.0 returns False.

Sorry, it should rather be:

Decimal('0.5') > 9.0 returns True because:
Decimal('0.5') > NotImplemented returns True

and:

Decimal('0.5') < 9.0 returns False because:
Decimal('0.5') < NotImplemented returns False

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-06 Thread Wojciech Walczak
2008/5/6, Banibrata Dutta <[EMAIL PROTECTED]>:
>  > Use /usr/bin/env.  If env is not in /usr/bin, put a link to it there.
>
>  So why not put symlink to Python over there on all machines, if we can
>  put one (or env itself) there ?

To avoid linking all the rest of interpreters like perl, ruby, lua and dozens
of others.

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-06 Thread Wojciech Walczak
2008/5/6, Ben Finney <[EMAIL PROTECTED]>:
>  > >  So why not put symlink to Python over there on all machines, if
>  > >  we can put one (or env itself) there ?
> > To avoid linking all the rest of interpreters like perl, ruby, lua
>  > and dozens of others.
> The argument was being made from "thousands of scripts". Isn't "dozens
>  of symlinks" better?

I think that depending on /usr/bin/env is more farsighted and saves some future
headaches. Creating links in /usr/bin/ means, that you have to change them
whenever you update your software (e.g. any of your many interpreters ;-)).
Changing the "#!/usr/bin/python" into "#!/usr/bin/env python" means that you do
your job once, and you can sleep well. It also is more portable.

How was it in perl?
perl -p -i -e 's/#\!\/usr\/bin\/python/#\!\/usr\/bin\/env python/' *.py

Funny thing, I have just ls'ed /usr/bin/python on my system:
$ ls -l /usr/bin/python
lrwxrwxrwx 1 root root 24 2007-11-16 14:02 /usr/bin/python ->
/usr/local/bin/python2.5

:-)

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: python vs. grep

2008-05-06 Thread Wojciech Walczak
2008/5/6, Anton Slesarev <[EMAIL PROTECTED]>:
>  But I have some problem with writing performance grep analog.
[...]
>  Python code 3-4 times slower on windows. And as I remember on linux
>  the same situation...
>
>  Buffering in open even increase time.
>
>  Is it possible to increase file reading performance?

The best advice would be not to try to beat grep, but if you really
want to, this is the right place ;)

Here is my code:
$ cat grep.py
import sys

if len(sys.argv) != 3:
   print 'grep.py  '
   sys.exit(1)

f = open(sys.argv[2],'r')

print ''.join((line for line in f if sys.argv[1] in line)),

$ ls -lh debug.0
-rw-r- 1 gminick root 4,1M 2008-05-07 00:49 debug.0

---
$ time grep nusia debug.0 |wc -l
26009

real0m0.042s
user0m0.020s
sys 0m0.004s
---

---
$ time python grep.py nusia debug.0 |wc -l
26009

real0m0.077s
user0m0.044s
sys 0m0.016s
---

---
$ time grep nusia debug.0

real0m3.163s
user0m0.016s
sys 0m0.064s
---

---
$ time python grep.py nusia debug.0
[26009 lines here...]
real0m2.628s
user0m0.032s
sys 0m0.064s
---

So, printing the results take 2.6 secs for python and 3.1s for original grep.
Suprised? The only reason for this is that we have reduced the number
of write calls in the python example:

$ strace -ooriggrep.log grep nusia debug.0
$ grep write origgrep.log |wc -l
26009


$ strace -opygrep.log python grep.py nusia debug.0
$ grep write pygrep.log |wc -l
12


Wish you luck saving your CPU cycles :)

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: assert type([]) == type(())

2010-01-02 Thread Wojciech Muła
VanceE  wrote:

> for x in []:
> assert type(x) == type(())
> 
> I expected an AssertionError but get no errors at all.
> Any explaination?

[] is an empty sequence, so your loop executes exactly 0 times. :)

for x in [None]:
assert ...

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


Re: use strings to call functions

2010-02-08 Thread Wojciech Muła
Klaus Neuner  wrote:

> > handlers = {
> >     ".txt" : handle_txt,
> >     ".py" : handle_py,
> >     # etc
> >     }
> >
> 
> That is exactly what I would like to avoid: Having to map the function
> 'handle_txt' to '.txt'. Firstly, because I don't want to repeat
> anything and secondly, because I will one day add a new function and
> forget to add its name to the dictionary.

Use dictionary mantained by runtime:

def handle(extensions):
funname = "handle_" + extension
return globals()[funname]

handle('txt') # => function handle_txt

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


Re: interleave string

2011-02-15 Thread Wojciech Muła
On Tue, 15 Feb 2011 10:53:56 +0100 Andrea Crotti
 wrote:

> Just a curiosity not a real problem, I want to pass from a string like
> 
> xxaabbddee
> to
> xx:aa:bb:dd:ee
> 
> so every two characters insert a ":".
> At the moment I have this ugly inliner
> interleaved = ':'.join(orig[x:x+2] for x in range(0,
> len(orig), 2))
> 
> but also something like this would work
> [''.join((x,y)) for x, y in zip(orig[0::2], orig[1::2])]
> 
> any other ideas?

import re

s = 'xxaabbddee'
m = re.compile("(..)")
s1 = m.sub("\\1:", s)[:-1]

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


How to know if connection is active when using telnetlib?

2005-08-26 Thread Wojciech Halicki-Piszko
How to know if connection is active after telnetlib.Telnet.open(host,port)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to know if connection is active when using telnetlib?

2005-08-26 Thread Wojciech Halicki-Piszko
> If open() doesn't throw an exception then you should have a connection you can
> start reading/writing with.  Unless you have some special meaning for
> 'active'?
> 
> I'm just basing this on reading telnetlib.py.
> 
> Eddie

Well, in fact what I meant is: I won't to check wether established
connection is still active. I have a reading thread and when I send 'quit'
command to a server it (guess what:)) disconnects. So I get plenty of
unwanted output, I want to avoid this. So the problem is how can I inform
my reader thread it is not longer wanted when _server_ disconnects me? To
my defense: repetition is mother of science (in case you did answer and I
did not get it first time).
 
-- 
http://mail.python.org/mailman/listinfo/python-list