Re: Getting some element from sets.Set
> I do not want to remove the element, but get some element > from the Set. . . . > Is there a way to do this. I am doing it like this: > > for x in s: break > > Now x is /some_element/ from s. That is one way to do it. Another is to write: x = iter(s).next() One more approach: x = s.pop() s.add(x) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting some element from sets.Set
On Thu, 03 May 2007 23:08:33 -0700, [EMAIL PROTECTED] wrote: > It is not possible to index set objects. That is OK. > But, what if I want to find some element from the Set. > > from sets import Set > s = Set( range(12 ) > > if I do pop, that particular element gets removed. > I do not want to remove the element, but get some element > from the Set. > > s.some_element() # Is not available Looking at help(sets.Set), it seems that there is no direct way to ask for a single element of a set, except with pop. So you can pop an element, then add it back in: some_element = s.pop() s.add(some_element) Another solution is to extract all the elements, then pick one: some_element = list(s)[0] -- Steven D'Aprano -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are functions atomic?
On May 2, 6:08 am, Carsten Haese <[EMAIL PROTECTED]> wrote: > On Tue, 2007-05-01 at 22:21 -0700, Michael wrote: > > Is there a reason for using the closure here? Using function defaults > > seems to give better performance:[...] > > It does? Not as far as I can measure it to any significant degree on my > computer. I agree the performance gains are minimal. Using function defaults rather than closures, however, seemed much cleaner an more explicit to me. For example, I have been bitten by the following before: >>> def f(x): ... def g(): ... x = x + 1 ... return x ... return g >>> g = f(3) >>> g() Traceback (most recent call last): File "", line 1, in File "", line 3, in g UnboundLocalError: local variable 'x' referenced before assignment If you use default arguments, this works as expected: >>> def f(x): ... def g(x=x): ... x = x + 1 ... return x ... return g >>> g = f(3) >>> g() 4 The fact that there also seems to be a performance gain (granted, it is extremely slight here) led me to ask if there was any advantage to using closures. It seems not. > An overriding theme in this thread is that you are greatly concerned > with the speed of your solution rather than the structure and > readability of your code. Yes, it probably does seem that way, because I am burying this code deeply and do not want to revisit it when profiling later, but my overriding concern is reliability and ease of use. Using function attributes seemed the best way to achieve both goals until I found out that the pythonic way of copying functions failed. Here was how I wanted my code to work: @define_options(first_option='abs_tol') def step(f,x,J,abs_tol=1e-12,rel_tol=1e-8,**kwargs): """Take a step to minimize f(x) using the jacobian J. Return (new_x,converged) where converged is true if the tolerance has been met. """ return (x + dx, converged) @define_options(first_option='min_h') def jacobian(f,x,min_h=1e-6,max_h=0.1): """Compute jacobian using a step min_h < h < max_h.""" return J class Minimizer(object): """Object to minimize a function.""" def __init__(self,step,jacobian,**kwargs): self.options = step.options + jacobian.options self.step = step self.jacobian = jacobian def minimize(self,f,x0,**kwargs): """Minimize the function f(x) starting at x0.""" step = self.step jacobian = self.jacobian step.set_options(**kwargs) jacobian.set_options(**kwargs) converged = False while not converged: J = jacobian(f,x) (x,converged) = step(f,x,J) return x @property def options(self): """List of supported options.""" return self.options The idea is that one can define different functions for computing the jacobian, step etc. that take various parameters, and then make a custom minimizer class that can provide the user with information about the supported options etc. The question is how to define the decorator define_options? 1) I thought the cleanest solution was to add a method f.set_options() which would set f.func_defaults, and a list f.options for documentation purposes. The docstring remains unmodified without any special "wrapping", step and jacobian are still "functions" and performance is optimal. 2) One could return an instance f of a class with f.__call__, f.options and f.set_options defined. This would probably be the most appropriate OO solution, but it makes the decorator much more messy, or requires the user to define classes rather than simply define the functions as above. In addition, this is at least a factor of 2.5 timese slower on my machine than option 1) because of the class instance overhead. (This is my only real performance concern because this is quite a large factor. Otherwise I would just use this method.) 3) I could pass generators to Minimize and construct the functions dynamically. This would have the same performance, but would require the user to define generators, or require the decorator to return a generator when the user appears to be defining a function. This just seems much less elegant. ... @define_options_generator(first_option='min_h') def jacobian_gen(f,x,min_h=1e-6,max_h=0.1): """Compute jacobian using a step min_h < h < max_h.""" return J class Minimizer(object): """Object to minimize a function.""" def __init__(self,step_gen,jacobian_gen,**kwargs): self.options = step_gen.options + jacobian_gen.options self.step_gen = step_gen self.jacobian_gen = jacobian_gen def minimize(self,f,x0,**kwargs): """Minimize the function f(x) starting at x0.""" step = self.step_gen(**kwargs) jacobian = self.jacobian_gen(**kwargs) converged = False while not converged: J = jacobian(f,x) (x,converged) = step(f,x,J) return x ... 4) Maybe ther
Re: Getting some element from sets.Set
[EMAIL PROTECTED] wrote: > It is not possible to index set objects. That is OK. > But, what if I want to find some element from the Set. > > from sets import Set > s = Set( range(12 ) > > if I do pop, that particular element gets removed. > I do not want to remove the element, but get some element > from the Set. > > s.some_element() # Is not available > > Is there a way to do this. I am doing it like this: > > for x in s: break > > Now x is /some_element/ from s. A set is probably not the appropriate container then. What is your use case? Peter -- http://mail.python.org/mailman/listinfo/python-list
enable-shared
How we do if find that python that we are using is compiled with the -- enable-shared option. There is can actually be done using distutils.sysconfig module but this modules is ported only with python- devel but not with standard python install. Is there another way apart from checking the pyconfig.h file. Thanks in advance : )~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacement for HTMLGen?
"Joshua J. Kugler" <[EMAIL PROTECTED]> wrote: > >I realize that in today's MVC-everything world, the mere mention of >generating HTML in the script is near heresy, but for now, it's what I ened >to do. :) > >That said, can someone recommend a good replacement for HTMLGen? I used to be a huge fan of HTMLgen. I built a couple of web sites on them, still in use 7 years later. However, in the time since then, I have come to believe that templating is a better answer. Now, the simple truth is that you need to use the scheme that makes sense to you. For me, templating (Cheetah is my favorite, www.cheetahtemplate.org) makes more sense than building the page bit by bit in Python code, and the separation of function and presentation makes things easier to maintain. In my opinion, of course. ;) -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: relative import broken?
On May 3, 10:08 am, "Alan Isaac" <[EMAIL PROTECTED]> wrote: > "Alex Martelli" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > > > Very simply, PEP 328 explains: > > """ > > Relative Imports and __name__ > > > Relative imports use a module's __name__ attribute to determine that > > module's position in the package hierarchy. If the module's name does > > not contain any package information (e.g. it is set to '__main__') then > > relative imports are resolved as if the module were a top level module, > > regardless of where the module is actually located on the file system. > > """ > > To change my question somewhat, can you give me an example > where this behavior (when __name__ is '__main__') would > be useful for a script? (I.e., more useful than importing relative > to the directory holding the script, as indicated by __file__.) Do you realize it's a different behaviour and it won't work for some packages? One possible alternative is to assume empty parent package and let from . import foo work but not from .. import bar or any other upper levels. The package author should also realize __init__.py will be ignored. -- Leo -- http://mail.python.org/mailman/listinfo/python-list
urllib.quote fails on Unicode URL
The code in urllib.quote fails on Unicode input, when called by robotparser. That bit of code needs some attention. - It still assumes ASCII goes up to 255, which hasn't been true in Python for a while now. - The initialization may not be thread-safe; a table is being initialized on first use. The code is too clever and uncommented. "robotparser" was trying to check if a URL, "http://www.highbeam.com/DynamicContent/%E2%80%9D/mysaved/privacyPref.asp%22"; could be accessed, and there are some wierd characters in there. Unicode URLs are legal, so this is a real bug. Logged in as Bug #1712522. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Getting some element from sets.Set
It is not possible to index set objects. That is OK. But, what if I want to find some element from the Set. from sets import Set s = Set( range(12 ) if I do pop, that particular element gets removed. I do not want to remove the element, but get some element from the Set. s.some_element() # Is not available Is there a way to do this. I am doing it like this: for x in s: break Now x is /some_element/ from s. - Suresh -- http://mail.python.org/mailman/listinfo/python-list
Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?
The Great Attractor wrote: > On Thu, 03 May 2007 13:53:39 +0100, Eeyore > <[EMAIL PROTECTED]> wrote: > >> >> Peter Webb wrote: >> Ask yourself WHY havn't I seen this footage before? >>> OK, why haven't you seen this footage before? >> Nice response ! >> >> Graham >> > You're an utter retard. You are terribly repetitive. Don't you know any other insults other that "retard", "nitwit", "cunt", "twit" and variations on *tard? It is very hard to believe you're a grown man, the way you sputter schoolyard insults. - Im starting to think this "Great Attractor" is a pre-adolescent lad simmering with rage and hormones, an active imagination, and a limited vocabulary. Given his fascination with lame double entendre like "Massive Attractor" and his fixation on cunts Id say he's likely a virgin as well, and very, very frustrated about it too. -- ~coyote -- http://mail.python.org/mailman/listinfo/python-list
Re: pack/unpack zero terminated string
tmp123 <[EMAIL PROTECTED]> wrote: > >After review the "struct" documentation, it seems there are no option >to pack/unpack zero terminated strings. Right. Just as there is no way to describe such a thing as a C struct. You'll have to unpack the fields by hand, which is that case won't be hard. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join
Elliot Peele <[EMAIL PROTECTED]> wrote: >On Tue, 2007-05-01 at 19:27 -0700, 7stud wrote: >> On May 1, 7:36 pm, Elliot Peele <[EMAIL PROTECTED]> wrote: >> > Why does os.path.join('/foo', '/bar') return '/bar' rather than >> > '/foo/bar'? That just seems rather counter intuitive. >> > >> > Elliot >> >> join(path1[, path2[, ...]]) >> Join one or more path components intelligently. If any component is an >> absolute path, all previous components (on Windows, including the >> previous drive letter, if there was one) are thrown away... > >Yes, but that still doesn't answer my question as to why os.path.join >works that way. I understand that that is how it is written, but why? It's behavior is exactly the same as if you did a series of "cd" commands at the shell with the same parameters. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange terminal behavior after quitting Tkinter application
(I apologize if some similar version of this message has already appeared; I've tried several time to post it, seemingly without success.) > If that is satisfactory, well and good. However, there > is a possibility that you may lose some settings that you would > prefer to keep. The terminal settings have been trashed, and > stty sane has restored a minimally workable set, but some > settings may not be what you expect. I agree: I'll consider saving the terminal settings as you suggest. > Just in case, I did a google search. I am not familiar > withTKinter, but a couple of articles out there imply > that rather than calling sys.exit you should be calling aTkInterroutine > root.destroy. I am not sure if root is a > variable for the main window (ie you call the destroy method > on the main window) or if it has some specialTkintermeaning. > Presumably this routine cleans things up before calling sys.exit > or an equivalent. "root" is the name of a variable typically used by people to hold an instance of Tkinter.Tk, the main application window (from http://epydoc.sourceforge.net/stdlib/Tkinter.Tk-class.html: "Toplevel widget of Tk which represents mostly the main window of an appliation. It has an associated Tcl interpreter."). Instead of subclassing Tkinter.Tk and instantiating that subclass for my application, I could create a Tk instance and withdraw() it, then use a Toplevel. In my example code above, I could call any 'root' methods on an instance of my Application class, presumably with the same effect. In any case, that might not be important - I think the problem comes from not calling mainloop(): import Tkinter import sys root = Tkinter.Tk() Tkinter.Button(root,text="Quit",command=sys.exit).pack() root.mainloop() Clicking 'Quit' or on the window's 'x' causes the application to quit without messing up the terminal. With root.mainloop() commented out, though, no combination of root.quit(), root.destroy(), and sys.exit() stops the terminal from getting messed up. So, I should call mainloop() for my application...except that I want to use the commandline, too, and calling mainloop() freezes the commandline. I wonder if there is another way to use the commandline and have a GUI? I couldn't find any clear information about that. Thanks again, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
On May 3, 7:21 pm, Andy Terrel <[EMAIL PROTECTED]> wrote: > Okay does anyone know how to decorate class member functions? > > The following code gives me an error: > > Traceback (most recent call last): > File "decorators2.py", line 33, in > s.update() > File "decorators2.py", line 13, in __call__ > retval = self.fn.__call__(*args,**kws) > TypeError: update() takes exactly 1 argument (0 given) > > -- > > #! /usr/bin/env python > > class Bugger (object): > def __init__ (self, module, fn): > self.module = module > self.fn = fn > > def __call__ (self,*args, **kws): > ret_val = self.fn(*args,**kws) > return ret_val > > def instrument (module_name): > ret_val = lambda x: Bugger(module_name, x) > return ret_val > > class Stupid: > def __init__(self): > self.val = 1 > > @instrument("xpd.spam") > def update(self): > self.val += 1 > > s = Stupid() > s.update() As far as I can tell, the problem is that the decorator executes when the class is parsed, and at that time there is no self(the instance object). The decorator produces a callable Bugger object, but the callable object has no way to get self when s.update() is called. Normally when you call a class function, like s.update(), the __get__() method in the 'update' function object is called (all function objects have a __get__() method and therefore are descriptors). Then __get__() creates a method object out of the function object(update), and python automatically passes the instance object to the method object. However, the Bugger object does not have a __get__() method, so no method object is created when the Bugger object is called, and therefore self is not automatically passed to the Bugger object. The following solution adds a __get__() method to the Bugger object. Python automatically passes the instance object to the __get__() method, and the solution stores the instance in the Bugger object. Then __call__ is defined to send the instance object to update(). class Bugger (object): def __init__ (self, module, fn): self.module = module self.fn = fn def __call__ (self,*args, **kws): ret_val = self.fn(self.obj, *args,**kws) return ret_val def __get__(descr, inst, instCls=None): descr.obj = inst return descr def instrument (module_name): ret_val = lambda func: Bugger(module_name, func) return ret_val class Stupid(object): def __init__(self): self.val = 1 @instrument("xpd.spam") def update(self): self.val += 1 s = Stupid() s.update() s.update() s.update() print s.val --output:-- 4 -- http://mail.python.org/mailman/listinfo/python-list
problem with py2exe and microsoft speech SDK 5.1
>On May 3, 1:29 pm, Dave Lim wrote: >> Hello, this is my first time in the mailing list so >> bear with me. >> >> Basically what I did was I followed this site:http://surguy.net/articles/speechrecognition.xml >> >> So I installed microsoft speech SDK 5.1 and then used >> pythonwin COM MakePy utility for it and it worked out >> fine. However, I need to compile my program into a >> .exe and I have no idea how to make this work. I tried >> using py2exe but I get the error: >> >> Traceback (most recent call last): >> File "simple-speech-recognition.py", line 57, in ? >> TypeError: Error when calling the metaclass bases >> cannot create 'NoneType' instances >> >> If anybody knows a good solution to this problem I >> would very much appreciate it if you can guide me to >> the right path / solution. >> >> Thank you very much! >> -Dave Lim >> >> __ >> Do You Yahoo!? >> Tired of spam? Yahoo! Mail has the best spam protection aroundhttp://mail.yahoo.com > >I've never done this, but I want to at some point, so I went and >grabbed some good links on packaging up Python apps: > >http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html >http://www.pharscape.org/content/view/33/51/ >http://wiki.python.org/moin/Py2Exe >http://www.py2exe.org/index.cgi/Tutorial > >There's also growth in using Python Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs > >Mike Thanks for the links. But I already have compiled it successfully into an executable my only problem is i still have that error. I still have the same error: Traceback (most recent call last): File "simple-speech-recognition.py", line 57, in ? TypeError: Error when calling the metaclass bases cannot create 'NoneType' instances I used py2exe and I also added typelibs in the options however that didn't seem to fix my problem. Below is my setup.py, can anyone tell me what I'm lacking or doing wrong here? setup.py from distutils.core import setup import py2exe setup(options = {"py2exe": {"typelibs": [('{C866CA3A-32F7-11D2-9602-00C04F8EE628}',0,5,0)]}}, console = ["simple.py"]) Dave __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: My Python annoyances
On May 3, 9:27 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Thu, 03 May 2007 10:49:26 -0300, Ben Collver <[EMAIL PROTECTED]> > escribió: > > > I tried to write portable Python code. The zlib CRC function returned > > different results on architectures between 32 bit and 64 bit > > architectures. I filed a bug report. It was closed, without a comment > > from the person who closed it. I get the unspoken message: bug reports > > are not welcome. > > You got a comment from me, that you never disputed nor commented further. > I would have changed the status to "invalid" myself, if I were able to do > so. I think it should have been marked as "won't fix" as it's a wart just like 1/2 == 0, but as there are many users of the current behaviour it's "impossible" to fix it in Python 2.x. Maybe in Python 3.0? -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: hp 11.11 64 bit python 2.5 build gets error "import site failed"
On May 3, 2:54 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > >>> "import site failed" > >>> OverflowError: signed integer is greater than the maximum. > >> - what is the value of ival? > > ival: 4294967295 > > I see. This is 0x, which would be -1 if it were of type > int. So perhaps some value got cast incorrectly at some point, > breaking subsequent computations > > > > >> - where does that number come from? > > > It is coming from the call to PyInt_AsLong. In that function there is > > a call to: > > PyInt_AS_LONG((PyIntObject*)op) > > which returns the value of ival. > > That was not my question, really. I wanted to know where the object > whose AsLong value was taken came from. And before you say "it's > in the arg parameter" of convertsimple() - sure it is. However, how > did it get there? It's in an argument tuple - and where came > that from? Looking at the call stack OP posted, -1 is coming as forth parameter of __import__, I *guess* at the first import in site.py or at implicit "import site". I think it'd be helpful if OP also tried if it works: python -S -c -v "print -1, type(-1), id(0), id(-1)" -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get type methods?
En Fri, 04 May 2007 01:34:20 -0300, <[EMAIL PROTECTED]> escribió: > I'm not against 'dir(MyClass)'; the question is, what should I 'dir()' > to get methods of 'pyuno' type instance? Usually instances don't have its own methods, they get them from the class. So you actually need dir(MyClass). Note that dir() might not show all available methods. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: passing an array of variant in vb to a python COM object = win32com bug ?
En Thu, 03 May 2007 09:41:57 -0300, vml <[EMAIL PROTECTED]> escribió: > On 3 mai, 14:20, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: >> En Thu, 03 May 2007 04:54:43 -0300, vml <[EMAIL PROTECTED]> >> escribió: >> >> > I have a python com object which contains a method to inverse an array >> > in vb 6 the definition of the class is : >> > I just tried to replace the *val by SqVal(self,val) and call the > method in vb but it crashes down : > > "when refilling safe array the sequence must have the same number of > dimension as the existing array" That can't happen with your Python code below, so it must be on the caller. Maybe you wrote something like: xx=something.SqVal(yy) and xx,yy are declared of different sizes. > def SqVal(self,val): > ## ... > return val > > By the way Do you have any idea to debug the com server script ? ( I > would like to know if a can access the value in the function while > calling it from vb 6) Write a log file as suggested, or use OutputDebugString with the DebugView program from www.sysinternals.com -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacement for HTMLGen?
En Thu, 03 May 2007 21:23:42 -0300, Joshua J. Kugler <[EMAIL PROTECTED]> escribió: > I found http://dustman.net/andy/python/HyperText, but it's not listed in > Cheeseshop, and its latest release is over seven years ago. Granted, I > know HTML doesn't change (much) but it's at least nice to know something > you're going to be using is maintained. I use HyperText, and if it's not maintained so much, it's because it does not have to change. BTW, it's amazing how much can you get from so many classes with just a "pass" statement. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Organizing code - import question
En Thu, 03 May 2007 12:41:00 -0300, Brian Blais <[EMAIL PROTECTED]> escribió: > I am trying to organize some of my code, and am having a little trouble > with the import logic. I find I often have something like: > > MyPackage/ > Part1/ # wants to use functions in Common/ > __init__.py # does "from MyClass1 import MyClass1", etc,... > MyClass1.py > MyClass1a.py # depends on MyClass1 > MyClass1b.py # depends on MyClass1 > > Part2/ # wants to use functions in Common/ > __init__.py # does "from MyClass2 import MyClass2", etc,... > MyClass2.py # depends on MyClass1 also, such as containing a > list of MyClass1 > MyClass2a.py # depends on MyClass2 > MyClass2b.py # depends on MyClass2 > > Common/ > __init__.py # does "import fun1,fun2", etc,... > fun1.py > fun2.py > > > > So I have some common utilities that both classes want to access, and I > have two separate class definitions, of which one depends on the other. > In MyClass2.py, I can't seem to do: > > import Common.fun1 > > or > > from Part1.MyClass1 import MyClass1 To be able to do that, MyPackage should be on sys.path If its *container* (i.e. the directory containing MyPackage, perhaps site-packages) is already on sys.path, you could prefix all imports with the package name: import MyPackage.Common.fun1, or from MyPackage.Part1 import MyClass1 (Dont forget the __init__.py on MyPackage, to make it a real package) If you are using Python 2.5, you can use relative imports. Read the "What's new" document. In MyClass2.py you could use, then: from ..Common import fun1, or: from ..Part1.MyClass1 import MyClass1 -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: I wish that [].append(x) returned [x]
On Wed, 2007-05-02 at 13:45 -0800, Joshua J. Kugler wrote: > On Wednesday 02 May 2007 12:05, Tobiah wrote: > > > > >> In addition to the above good advice, in case you are submitting a query > >> to a DB-API compliant SQL database, you should use query parameters > >> instead of building the query with string substitution. > > > > I tried that a long time ago, but I guess I found it to be > > more awkward. I imagine that it is quite a bit faster that way? > > I'm using MySQLdb. > > The issue is not speed, it's security. Query parameters are automatically > escaped to prevent SQL injection attacks. In addition to the important security factor, on many databases, using query parameters will also result in a speed increase. It just so happens that MySQLdb is not one of them. The wording that query parameters are "escaped" implies that handling query parameters is a string formatting exercise and that query parameters are stuffed into the query string as properly escaped literals. That is not always the case. In many databases, the lowlevel database API provides a particular mechanism for binding parameter values to placeholders without "injecting" them into the query string. This saves the client from constructing literals and it saves the server from parsing those literals. It also allows the server to reuse the query string without re-parsing it, because the query string doesn't change if the parameters are transmitted separately. The resulting speedup can be quite significant, as demonstrated for example with an IBM Informix database: # querytest.py class Tester(object): def __init__(self): import informixdb conn = informixdb.connect("ifxtest") self.cur = conn.cursor() self.cur.execute("create temp table t1(a int, b int)") self.counter = 0 def with_params(self): self.counter += 1 self.cur.execute("insert into t1 values(?,?)", (self.counter,self.counter*2) ) def without_params(self): self.counter += 1 self.cur.execute("insert into t1 values(%s,%s)" % (self.counter,self.counter*2) ) [EMAIL PROTECTED] python]$ python -mtimeit -s "from querytest import Tester; t=Tester()" 't.with_params()' 1 loops, best of 3: 146 usec per loop [EMAIL PROTECTED] python]$ python -mtimeit -s "from querytest import Tester; t=Tester()" 't.without_params()' 1000 loops, best of 3: 410 usec per loop I think those numbers speak for themselves. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get type methods?
On May 4, 3:21 am, Stargaming <[EMAIL PROTECTED]> wrote: > What's wrong about `dir()`? > x = MyClass() > x.f() I want to cashe pointers to Python functions in a non-Python app. 'dir()' requires an argument, and I want to get function pointers before I have any variable of given type or class. That's why 'MyClass.f(x)' I'm not against 'dir(MyClass)'; the question is, what should I 'dir()' to get methods of 'pyuno' type instance? Sincerely yours, Dmitri -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
Andy Terrel wrote: > Okay does anyone know how to decorate class member functions? > > The following code gives me an error: > > Traceback (most recent call last): > File "decorators2.py", line 33, in > s.update() > File "decorators2.py", line 13, in __call__ > retval = self.fn.__call__(*args,**kws) > TypeError: update() takes exactly 1 argument (0 given) > > -- > > > #! /usr/bin/env python > > class Bugger (object): > def __init__ (self, module, fn): > self.module = module > self.fn = fn > > def __call__ (self,*args, **kws): > ret_val = self.fn(*args,**kws) > return ret_val > > def instrument (module_name): > ret_val = lambda x: Bugger(module_name, x) > return ret_val > > class Stupid: > def __init__(self): > self.val = 1 > > @instrument("xpd.spam") > def update(self): > self.val += 1 > > > s = Stupid() > s.update() The problem is not that you are decorating a method but that you are trying to use a callable class instance as a method. For that to work the class has to implement the descriptor protocol, see http://users.rcn.com/python/download/Descriptor.htm class Bugger (object): def __init__ (self, module, fn, instance=None): self.module = module self.fn = fn self.instance = instance def __call__ (self, *args, **kws): print "calling %s.%s()" % (self.module, self.fn.__name__) if self.instance is not None: args = (self.instance,) + args ret_val = self.fn(*args, **kws) return ret_val def __get__(self, instance, class_): if instance is None: return self return Bugger(self.module, self.fn, instance) def instrument (module_name): ret_val = lambda x: Bugger(module_name, x) return ret_val class Stupid(object): @instrument("xpd.spam") def update(self): print "update()" s = Stupid() s.update() Stupid.update(s) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: My Python annoyances
En Thu, 03 May 2007 10:49:26 -0300, Ben Collver <[EMAIL PROTECTED]> escribió: > I tried to write portable Python code. The zlib CRC function returned > different results on architectures between 32 bit and 64 bit > architectures. I filed a bug report. It was closed, without a comment > from the person who closed it. I get the unspoken message: bug reports > are not welcome. You got a comment from me, that you never disputed nor commented further. I would have changed the status to "invalid" myself, if I were able to do so. > I installed Cygwin on a Windows machine. I try to quit from an > interactive Python session. It tells me that on my platform, I must > press Control-Z to exit. I press Control-Z and it makes Python a > background process. Maybe because you were running Windows Python from inside a bash prompt? The Cygwin version tells you to use the right key combination to exit. > In short, there is plenty of room for improvement. Admittedly these are > not problems with the language definition. But I downloaded a Python > distribution, and the problems are Python specific. Yes, some documentation is a bit outdated as Python is evolving continuously. I prefer that, to a frozen language. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
New EasyExtend release is out
Hi folks, EasyExtend is a grammar based preprocessor generator and metaprogramming system for Python written in Python. After reworking an initial release for 11 months (!) it's time to present now EasyExtend 2.0-alpha1. You find EasyExtend on the projects homepage: http://www.fiber-space.de/EasyExtend/doc/EE.html The EasyExtend package is also uploaded to the cheeseshop: http://www.python.org/pypi/EasyExtend/2.0-alpha1 To make yourself familiar with EE there is now also an introductory level tutorial: http://www.fiber-space.de/EasyExtend/doc/tutorial/EETutorial.html Have fun! Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter listboxes
[EMAIL PROTECTED] wrote: > I will give a simplified example of the problem at hand -- > > I have a case in which I have two listboxes - listbox1 and listbox2, > if I click on an item in listbox1 the item gets highlighted as > expected. Now if I click on an item in listbox2 the selected item in > listbox1 loses its highlight. My question is how do I keep the > listbox1 item from losing its highlight if I select an item in > listbox2 or to that matter any other widget. > > Thanks > Rahul > You will need to bind '' for each list box to something like: def button1(e): row = e.widget.lists[0].nearest(e.y) e.widget.selection_clear(0, END) e.widget.selection_set(row) return 'break' # how to bind alistbox.bind('', button1) The less than obvious thing here is that selections (highlighted here) are different than the active index (which is marked with an underline). You are probably using the active index and don't realize the difference. James -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
On Thu, 03 May 2007 19:28:52 -0700, Andy Terrel wrote: > I just need to keep the state around. I make a call to some function > that is pretty expensive so I want to save it as a member during the > __init__ of the decorator. > > Yeah I'm afraid it can't be done either, that's why I asked the group. You can do it if you give up on using the decorator syntax. (Now that I've said that, some clever bunny will show me how to do it.) def make_decorator(n): def addspam(fn): def new(*args): print "spam " * n return fn(*args) return new return addspam class Parrot(object): def __init__(self, count=3): from new import instancemethod as im self.describe = im(make_decorator(count)(self.__class__.describe), self) def describe(self): return "It has beautiful plummage." >>> bird = Parrot() >>> bird.describe() spam spam spam 'It has beautiful plummage.' >>> >>> >>> bird = Parrot(5) >>> bird.describe() spam spam spam spam spam 'It has beautiful plummage.' -- Steven D'Aprano -- http://mail.python.org/mailman/listinfo/python-list
Re: file Error
En Thu, 03 May 2007 10:15:52 -0300, <[EMAIL PROTECTED]> escribió: > Thanks for the replyHow do i accept the filename is a > parameter and avoid the error.Can you elaborate. To get the arguments passed to the script, use sys.argv[] Most introductory texts should cover it, like the Python tutorial: http://docs.python.org/tut/node4.html -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67)
Laurent Pointal <[EMAIL PROTECTED]> wrote: ... > > It's an excellent quick-reference card, BTW (though I don't quite > > understand why even-numbered pages are flipped upside-down). > > At work I print it on horizontal A4/USLetter, with recto-back, and with > binding (reliure in french) on small side of paper. Ah, that must be my problem -- I didn't set "binding" to the short side, but left it as I have it by default, on the long side. Thanks. Alex -- http://mail.python.org/mailman/listinfo/python-list
tkinter listboxes
I will give a simplified example of the problem at hand -- I have a case in which I have two listboxes - listbox1 and listbox2, if I click on an item in listbox1 the item gets highlighted as expected. Now if I click on an item in listbox2 the selected item in listbox1 loses its highlight. My question is how do I keep the listbox1 item from losing its highlight if I select an item in listbox2 or to that matter any other widget. Thanks Rahul -- http://mail.python.org/mailman/listinfo/python-list
Re: adding methods at runtime and lambda
En Thu, 03 May 2007 16:52:55 -0300, Mike <[EMAIL PROTECTED]> escribió: > I was messing around with adding methods to a class instance at > runtime and saw the usual code one finds online for this. All the > examples I saw say, of course, to make sure that for your method that > you have 'self' as the first parameter. I got to thinking and thought > "I have a lot of arbitrary methods in several utility files that I > might like to add to things. How would I do that?" And this is what I > came up with: I don't see the reason to do that. If you have a function that does not use its "self" argument, what do you get from making it an instance method? If -for whatever strange reason- you want it to actually be a method, use a static method: py> def foo(x): ... print "I like %r" % x ... py> class A(object): pass ... py> a = A() py> A.foo = staticmethod(foo) py> a.foo() Traceback (most recent call last): File "", line 1, in TypeError: foo() takes exactly 1 argument (0 given) py> a.foo("coffee") I like 'coffee' py> A.foo("tea") I like 'tea' -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I import a variable from another module?
On Thu, 03 May 2007 18:27:12 -0700, noagbodjivictor wrote: > I have a variable names actions in a module named qt_actions.py > > Well this is what I get: import qt_actions qt_actions.actions > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'actions' The error is clear -- you *don't* have an attribute named actions in the module. I'm going to guess that you've imported the module, then edited it, then imported it again. That doesn't help, because imported modules are cached. You need to reload(qt_actions). Either that, or you've got two modules named qt_actions, and only one of them has a variable 'actions'. The first module in the PYTHONPATH is imported. Or, you're mistaken about having such a variable. But my money is on the first one. Use reload(qt_actions). -- Steven D'Aprano -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I import a variable from another module?
On May 4, 6:39 am, [EMAIL PROTECTED] wrote: > On May 3, 9:36 pm, Andy Terrel <[EMAIL PROTECTED]> wrote: > > > are you sure your variable isn't in some code block that wouldn't be > > read on import? Such as: > > > if __name__ == "__main___": > > actions = 1 > > No Andy, I have not put the variable in any code block Does the variable show up in the dir listing of the module? ie. >>> import qt_actions >>> dir(qt_actions) -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
not quite as elegant but here is a workaround... Thanks Virgil for taking some time to think about it. --- class Bugger (object): def __init__ (self, module): print "Entering __init__" self.module = module self.verb = 0 def instrument (module_name): def wrapper(f): def _wrap(*args,**kws): ret_val = f(*args,**kws) return ret_val return _wrap b = Bugger(module_name) if b.verb == 0: ret_val = wrapper else: ret_val = lambda x:x return ret_val class Stupid: def __init__(self): self.val = 1 @instrument("spam") def update(self): self.val += 1 s = Stupid() s.update() s.update() s.update() s.update() print s.val -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
Andy Terrel <[EMAIL PROTECTED]> writes: > I just need to keep the state around. I make a call to some function > that is pretty expensive so I want to save it as a member during the > __init__ of the decorator. > > Yeah I'm afraid it can't be done either, that's why I asked the group. Have you looked at memoize decorators? They seem to do what you want. There are examples at the Python website (some link in there, I'm sorry...). This will give you lots of resources, including full recipes and comments from the Python cookbook: http://www.google.com.br/search?q=python+decorator+memoize -- Jorge Godoy <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
I just need to keep the state around. I make a call to some function that is pretty expensive so I want to save it as a member during the __init__ of the decorator. Yeah I'm afraid it can't be done either, that's why I asked the group. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why stay with lisp when there are python and perl?
Nameless wrote: > Why should I keep on learning lisp when there are python and perl? Lisp compilers are much more advanced, for one thing. Xah Lee wrote: > (if there is some demand, i will add a concrept, little programing > example, that shows, how lisp's symbols and macros concepts, set it > apart from new scripting languages) I already did something similar, writing simple programs to simplify symbolic expressions in different languages: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/239715 Also, here is a symbolic derivative example: http://codecodex.com/wiki/index.php?title=Derivative Note that pattern matching (as found in OCaml, F#, Haskell etc.) is very useful for this kind of term rewriting and is not found in Python, Perl or Lisp. > This lisp's symbol concept, as far as i know, does not exist in some > other high-level functional programing languages such as Haskell. Correct. > I'm > not familiar with many functional languages except Lisp and > Mathematica. I'm curious, as to how Haskell, which itself is quite > with capable of symbolic computation i think, deals with it even > though the language doesn't employ the concep of lisp's symbols per > se. In Standard ML, Haskell and F# you must define a sum type that represents a symbolic expression whereas, in Lisp, you can use the built-in s-expressions. The sum type that you define typically includes a "Symbol" that carries its string name. For example, the F# code cited above used: type expr = | Int of int | Add of expr * expr | Mul of expr * expr | Var of string with static member ( + ) (f, g) = Add(f, g) static member ( * ) (f, g) = Mul(f, g) end in this case, "Var" represents a symbol, e.g. the value Var "x" would represent a variable x. However, note that the best Lisp implementation of the symbolic simplifier (by Pascal Constanza) avoids s-expressions, improving performance. In OCaml, you can rely on the compiler inferring the sum type for you by using polymorphic variants. However, this is not generally a good idea because they are slower and harbor some of the disadvantages of dynamic typing. It is worth noting that eager, statically-typed languages like OCaml and F# are many times faster than the other languages at this task. This is precisely the forte of OCaml and F#, manipulating trees and graphs. -- Dr Jon D Harrop, Flying Frog Consultancy The F#.NET Journal http://www.ffconsultancy.com/products/fsharp_journal/?usenet -- http://mail.python.org/mailman/listinfo/python-list
Re: 4 quadrant atan
Roel Schroeven wrote: > > I might be wrong of course, but can't you just use atan2? Only problem > is that it returns negative angles for quadrants 3 and 4, but that is > easily solved. In Python: > > from math import atan2, pi, fmod > def vectorAngle(x, y): > return fmod(atan2(y, x) + 2*pi, 2*pi) > > No conditionals in sight. > Yes, but there will be some conditionals for special cases in the implementation of atan2(). I am pretty sure that in Python (and Perl) atan2() is the C atan2() from the C math library, also often used by Fortran. This is normally written in assembler for the individual architecture by the hardware vendor or compiler writer, is usually heavily optimized, carefully handles all the corner cases, and often carries extra precision to ensure accuracy. If I recall correctly P. J. Plauger's book on the C standard library ("The Standard C Library") includes a C version of atan2(), which is probably pretty typical of the algorithms used when there is no hardware support for trigonometric functions. As I remember it, atan2 (and atan) in Plauger's book use a ratio of polynomials to approximate atan(x) over a limited range, (such as -1.0 ... +1.0 or 0.0 ... sqrt(2)-1) and formulae (assuming I have remembered high school trigonometry correctly) such as atan(x) = pi/2 - atan(1/x) and atan(x) = pi/4 - atan((1-x)/(1+x)) [derived from tan(pi/4-x) = (1-x)/(1+x)] to extend the range. There is an obvious trade off between the complexity of the approximating polynomials (and the range they cover with acceptable accuracy), and the number of cases needed to extend the range to all valid inputs. For example, if the polynomials cover -1.0 ... +1.0 (atan() values of -pi/4 to +pi/4) then there are at least 5 cases to consider (atan() ranges -pi ... -3pi/4, -3pi/4 ... -pi/4, -pi/4 ... +pi4, +pi/4 ... +3pi/4, +3pi/4 ... +pi), while if the approximations only cover 0.0 ... sqrt(2)-1 (atan() values from 0.0 to pi/8) then there are at least 16 cases. NaNs and infinities would add additional cases, as may the need to preserve accuracy near zero. Charles -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I use Python instead of Joomla?
On May 3, 7:49 pm, John Draper <[EMAIL PROTECTED]> wrote: > I admit, Joomla is easy to use I admit, but very easy to vector into > a root exploit. I had no idea. Thank you for posting that. One thing I really like about joomla is the 1600+ extensions. But, I don't need those kinds of security issues. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
On May 3, 9:21 pm, Andy Terrel <[EMAIL PROTECTED]> wrote: > Okay does anyone know how to decorate class member functions? > > The following code gives me an error: > > Traceback (most recent call last): > File "decorators2.py", line 33, in > s.update() > File "decorators2.py", line 13, in __call__ > retval = self.fn.__call__(*args,**kws) > TypeError: update() takes exactly 1 argument (0 given) > > -- > > #! /usr/bin/env python > > class Bugger (object): > def __init__ (self, module, fn): > self.module = module > self.fn = fn > > def __call__ (self,*args, **kws): > ret_val = self.fn(*args,**kws) > return ret_val > > def instrument (module_name): > ret_val = lambda x: Bugger(module_name, x) > return ret_val > > class Stupid: > def __init__(self): > self.val = 1 > > @instrument("xpd.spam") > def update(self): > self.val += 1 > > s = Stupid() > s.update() Second attempt. After some fuss around, I think it's just not possible to have a class instance as a decorator. the self gets lost in translation. #! /usr/bin/env python class Caller(object): def __init__ (self, fn): self.fn = fn def __call__(self, *args, **kwargs): print 'Caller calling!', repr(args) return self.fn(*args, **kwargs) def mydecorator(f): return Caller(f) class Stupid: def __init__(self): self.val = 1 @mydecorator def update(self): self.val += 1 s = Stupid() s.update() Caller calling! () Traceback (most recent call last): File "/Users/hsoft/Desktop/foo.py", line 22, in ? s.update() File "/Users/hsoft/Desktop/foo.py", line 8, in __call__ return self.fn(*args, **kwargs) TypeError: update() takes exactly 1 argument (0 given) But why do you want to use a class? If you want to have a decorator with argument, you only need to have something like: def instrument(module): def decorator(f): def wrapper(*args, **kwargs): print module return f(*args, **kwargs) return wrapper return decorator -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I use Python instead of Joomla?
On May 3, 11:08 am, Bruno Desthuilliers wrote: > I'm not sure integrating CakePHP stuff into something like Joomla or > Drupal will be that easy. I don't know either. But, there are projects called "jake" and "drake" which are specifically geared toward intergrating cakephp with joomla and drupal, respectively. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I use Python instead of Joomla?
walterbyrd wrote: >If I wanted to build a website with forums, news feeds, galleries, >event calander, document managment, etc. I do so in Joomla easily. > >But, I would perfer to use django/python, if that would be at all >practical. > >I suppose I could put python scripts into django, if those scripts >exist. > > > There are at least 3 Python oriented web apps out there. I highly recommend you ditch Joomla as soon as you can. joomla has a lot of security issues, and I've been trying to get my friend off of this POS for the longest time. Her web sites are constantly getting defaced... there are at least 3 Joomla exploits I know of out there. djangoproject.org turbogears.com plone.org Check these out. But get off of Joomla as soon as you can. I admit, Joomla is easy to use I admit, but very easy to vector into a root exploit. John -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
On May 3, 9:33 pm, Virgil Dupras <[EMAIL PROTECTED]> wrote: > On May 3, 9:21 pm, Andy Terrel <[EMAIL PROTECTED]> wrote: > > > > > Okay does anyone know how to decorate class member functions? > > > The following code gives me an error: > > > Traceback (most recent call last): > > File "decorators2.py", line 33, in > > s.update() > > File "decorators2.py", line 13, in __call__ > > retval = self.fn.__call__(*args,**kws) > > TypeError: update() takes exactly 1 argument (0 given) > > > -- > > > #! /usr/bin/env python > > > class Bugger (object): > > def __init__ (self, module, fn): > > self.module = module > > self.fn = fn > > > def __call__ (self,*args, **kws): > > ret_val = self.fn(*args,**kws) > > return ret_val > > > def instrument (module_name): > > ret_val = lambda x: Bugger(module_name, x) > > return ret_val > > > class Stupid: > > def __init__(self): > > self.val = 1 > > > @instrument("xpd.spam") > > def update(self): > > self.val += 1 > > > s = Stupid() > > s.update() > > A decorator is a function that takes one single parameter: a function. > "instrument" must return a decorator. Oh wait, I just embarrassed myself. Nevermind my last post. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I import a variable from another module?
On May 3, 9:36 pm, Andy Terrel <[EMAIL PROTECTED]> wrote: > are you sure your variable isn't in some code block that wouldn't be > read on import? Such as: > > if __name__ == "__main___": > actions = 1 No Andy, I have not put the variable in any code block -- http://mail.python.org/mailman/listinfo/python-list
Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?
On Thu, 03 May 2007 18:08:31 -0500, quasi <[EMAIL PROTECTED]> wrote: >On Fri, 04 May 2007 09:37:37 +1200, Gib Bogle ><[EMAIL PROTECTED]> wrote: > >>Ah, so the firefighters were in on the conspiracy! > >No, but the firefighters are very much aware that there is more to >9/11 than has been officially revealed. > >This is even more true at Pentagon. The firefighters there brought >dogs trained to search for survivors and/or remains and found nothing. > >quasi You're a goddamned idiot. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I import a variable from another module?
are you sure your variable isn't in some code block that wouldn't be read on import? Such as: if __name__ == "__main___": actions = 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
On May 3, 9:21 pm, Andy Terrel <[EMAIL PROTECTED]> wrote: > Okay does anyone know how to decorate class member functions? > > The following code gives me an error: > > Traceback (most recent call last): > File "decorators2.py", line 33, in > s.update() > File "decorators2.py", line 13, in __call__ > retval = self.fn.__call__(*args,**kws) > TypeError: update() takes exactly 1 argument (0 given) > > -- > > #! /usr/bin/env python > > class Bugger (object): > def __init__ (self, module, fn): > self.module = module > self.fn = fn > > def __call__ (self,*args, **kws): > ret_val = self.fn(*args,**kws) > return ret_val > > def instrument (module_name): > ret_val = lambda x: Bugger(module_name, x) > return ret_val > > class Stupid: > def __init__(self): > self.val = 1 > > @instrument("xpd.spam") > def update(self): > self.val += 1 > > s = Stupid() > s.update() A decorator is a function that takes one single parameter: a function. "instrument" must return a decorator. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating class member functions
Oh I should mention the decorator needs to have some notion of state (such as with the above class) -- http://mail.python.org/mailman/listinfo/python-list
How do I import a variable from another module?
I have a variable names actions in a module named qt_actions.py Well this is what I get: >>> import qt_actions >>> qt_actions.actions Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'actions' -- http://mail.python.org/mailman/listinfo/python-list
Re: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up."
On 3 May 2007 08:53:39 -0700, malibu <[EMAIL PROTECTED]> wrote: >On May 3, 12:18 am, Eric Gisse <[EMAIL PROTECTED]> wrote: >> On May 2, 10:14 pm, malibu <[EMAIL PROTECTED]> wrote: >> >> > On May 2, 9:46 pm, Eric Gisse <[EMAIL PROTECTED]> wrote: >> >> > > On May 2, 7:10 pm, Midex <[EMAIL PROTECTED]> wrote: >> >> > > [...] >> >> > > I guess the explanation that people were looking at the building and >> > > watching its' structure deform is too rational. >> >> > Also, that was a Larry Silverstein impostor who >> > said they were going to 'pull it'. >> >> ...maybe if you read the context, it would make a little more rational >> sense. Fucking nutter. >> >> > And the only reason he took out huge amounts >> > of extra insurance on the buildings two months >> > before this happened was because of global >> > warming, because we all know a little bit of heat >> > will bring down steel buildings. >> >> A little heat and major structural damage. >> >> >> >> > John > >Gee, I'll bet all those explosions in the >subfloors of WTC1 + WTC2 did some >structural damage also! You're an idiot. > >Come to think of it. Slugs do not think. > >When the firefighters got there, all the glass >on the street floors was blown out. You're an idiot. >Shock wave from the plane hitting >80 floors up? You're a goddamned retard, boy. ARe you an islamic extremist by chance? > >Janitors and such coming up from the basement levels >bleeding and dazed. You're full of shit. > >Jet fuel trickling down the elevator shafts being ignited >by someone's roach? And exploding? You're an ifiot. >Severing the three-foot thick steel columns? >All 5 dozen of them? >(That's mighty fine primo, pardner!) The buildings collapsed WAY WAY UP on the floors where the planes hit, and fell from there down, taking floors out as the large top section of the building fell. You could be a bit more retarded, just not in this life. >Your brain got structural damage? No, but your never was right from the moment your retarded felon criminal mother shat you out of her ass and forgot to flush. >Dropped on your head as a kid? Got any more adolescent baby bullshit, little boy? >Don't put that fire iron too close >to the flames, honey. It'll melt >and deform! You're an idiot. There was a tanker crash in Oakland a couple days back (Sunday) that melted sections of the bridge it was on. Got Clue? You and Rosie are retarded. -- http://mail.python.org/mailman/listinfo/python-list
Decorating class member functions
Okay does anyone know how to decorate class member functions? The following code gives me an error: Traceback (most recent call last): File "decorators2.py", line 33, in s.update() File "decorators2.py", line 13, in __call__ retval = self.fn.__call__(*args,**kws) TypeError: update() takes exactly 1 argument (0 given) -- #! /usr/bin/env python class Bugger (object): def __init__ (self, module, fn): self.module = module self.fn = fn def __call__ (self,*args, **kws): ret_val = self.fn(*args,**kws) return ret_val def instrument (module_name): ret_val = lambda x: Bugger(module_name, x) return ret_val class Stupid: def __init__(self): self.val = 1 @instrument("xpd.spam") def update(self): self.val += 1 s = Stupid() s.update() -- http://mail.python.org/mailman/listinfo/python-list
Re: NewB: Glob Question
On Thu, 03 May 2007 10:38:31 -0700, J wrote: > Greetings Group- > > I'm trying to put together a pattern matching script that scans a > directory tree for tif images contained in similar folder names, but > running into a NewB problem already. Is it the way I'm trying to join > multiple paths? Any help would be greatly appericated. Thanks, J! No no, don't tell us what problem you found! We love guessing!!! Let's see... did it reformat your hard drive? If you join multiple paths wrong, Python will reformat your hard drive as punishment. I tell you, you soon learn not to do that! -- Steven D'Aprano -- http://mail.python.org/mailman/listinfo/python-list
Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?
On Thu, 03 May 2007 13:53:39 +0100, Eeyore <[EMAIL PROTECTED]> wrote: > > >Peter Webb wrote: > >> > Ask yourself WHY havn't I seen this footage before? >> > >> > >> >> OK, why haven't you seen this footage before? > >Nice response ! > >Graham > You're an utter retard. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I output a list like the interpreter do?
On May 3, 8:24 pm, [EMAIL PROTECTED] wrote: > On May 3, 8:01 pm, [EMAIL PROTECTED] wrote: > > > On May 3, 8:00 pm, [EMAIL PROTECTED] wrote: > > > > >>> s = ['a','b'] > > > >>> s > > > ['a', 'b'] > > > > This is what I want so that I can put it in a module then import that > > > module to work with my variable. > > > Sorry for that typo in the title... > > I found a was using str(list). Do you know how to get rid of the > surrounding quotes? Nevermind... -- http://mail.python.org/mailman/listinfo/python-list
Replacement for HTMLGen?
I realize that in today's MVC-everything world, the mere mention of generating HTML in the script is near heresy, but for now, it's what I ened to do. :) That said, can someone recommend a good replacement for HTMLGen? I've found good words about it (http://www.linuxjournal.com/article/2986), but every reference to it I find points to a non-existant page (http://starship.python.net/lib.html is 404, http://www.python2.net/lib.html is not responding, http://starship.python.net/crew/friedrich/HTMLgen/html/main.html is 404) Found http://www.python.org/ftp/python/contrib-09-Dec-1999/Network/, but that seems a bit old. I found http://dustman.net/andy/python/HyperText, but it's not listed in Cheeseshop, and its latest release is over seven years ago. Granted, I know HTML doesn't change (much) but it's at least nice to know something you're going to be using is maintained. Any suggestions or pointers? j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I output a list like the interpreter do?
On May 3, 8:01 pm, [EMAIL PROTECTED] wrote: > On May 3, 8:00 pm, [EMAIL PROTECTED] wrote: > > > >>> s = ['a','b'] > > >>> s > > ['a', 'b'] > > > This is what I want so that I can put it in a module then import that > > module to work with my variable. > > Sorry for that typo in the title... I found a was using str(list). Do you know how to get rid of the surrounding quotes? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I output a list like the interpreter do?
On May 3, 8:00 pm, [EMAIL PROTECTED] wrote: > >>> s = ['a','b'] > >>> s > ['a', 'b'] > > This is what I want so that I can put it in a module then import that > module to work with my variable. Sorry for that typo in the title... -- http://mail.python.org/mailman/listinfo/python-list
How do I output a list like the interpreter do?
>>> s = ['a','b'] >>> s ['a', 'b'] >>> This is what I want so that I can put it in a module then import that module to work with my variable. -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 OS on 64-bit machine
On Thursday 03 May 2007 01:10, SamG wrote: > If anyone has a x86_64 machine and is running a 32bit OS on top of > that could you tell me what output would you get for the following > program > > #== > import platform > print platform.processor() > print platform.architecture() > #== > > Thanks in advance > : )~ >>> import platform >>> print platform.processor() >>> print platform.architecture() ('32bit', '') >>> $ cat /proc/cpuinfo processor : 0 vendor_id : AuthenticAMD cpu family : 15 model : 44 model name : AMD Sempron(tm) Processor 3100+ $ uname -a Linux djibouti 2.6.15-28-k7 #1 SMP PREEMPT Thu Feb 1 16:36:09 UTC 2007 i686 GNU/Linux -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com -- http://mail.python.org/mailman/listinfo/python-list
Re: When does input() return an empty string?
On May 3, 7:50 pm, André <[EMAIL PROTECTED]> wrote: > On May 3, 8:43 pm, [EMAIL PROTECTED] wrote: > > > I'm filling an array with user input, I want an empty string to be > > returned when nothing is entered; ie return key hit twice... How do I > > do that? > > use raw_input(), not input(). input() attempts to evaluate the > result, assuming it is a valid python expression. > > André Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: When does input() return an empty string?
On May 3, 8:43 pm, [EMAIL PROTECTED] wrote: > I'm filling an array with user input, I want an empty string to be > returned when nothing is entered; ie return key hit twice... How do I > do that? use raw_input(), not input(). input() attempts to evaluate the result, assuming it is a valid python expression. André -- http://mail.python.org/mailman/listinfo/python-list
When does input() return an empty string?
I'm filling an array with user input, I want an empty string to be returned when nothing is entered; ie return key hit twice... How do I do that? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get type methods?
[EMAIL PROTECTED] schrieb: > Hello! > > If I do > > import uno > localContext=uno.getComponentContext() > > then localContext is of type > I guess it's a new type provided by PyUNO extension. > localContext.__class__ is None > Is there any way to list all methods of that new type, via Python C > API or through interpreter (other then dir(localContext) )? What's wrong about `dir()`? > What I want is to call localContext's methods like in the tutorial > example: > > x=MyClass() > MyClass.f(x) I'd prefer:: x = MyClass() x.f() > > Thank you, > Dmitri > -- http://mail.python.org/mailman/listinfo/python-list
Re: getmtime in 2.5 reports GMT instead of local time
On May 4, 12:26 am, Josef Dalcolmo <[EMAIL PROTECTED]> wrote: > Hello, > > I have tried this only on Windows XP. > > in Python 2.4 os.path.getmtime() used to return an integer representing > the local time. The docs say "seconds since the epoch". Noting that the epoch is usually defined with reference to UTC, "local time" is rather unlikely. > > in Python 2.5 os.path.getmtime() reports a float representing the GMT of the > file's modification time. > > Since I could not find any documentation to this behavioural change, I am > asking > here: was this change intentional? Is it going to stay? Windows reports > the same time for the file as Python 2.4 used to. So I am tempted to > call this a bug, but wanted some feedback from the developers, > before filing a bug report. > > If you want to test this, make sure your local time differs from GMT, > then do: > > import os, time > print time.ctime(os.path.getmtime('foo.txt')) > > on a file foo.txt, once with Python 2.4 then with Python 2.5, > and you should see what I mean. No way, Jose. C:\junk>\python24\python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os, os.path, time; fn = 'hello_u.txt'; print os.stat(fn).st_mtime, os .path.getmtime(fn) 1178228403 1178228403 >>> import os, os.path, time; fn = 'hello_u.txt'; print time.ctime(os.stat(fn).s t_mtime), time.ctime(os.path.getmtime(fn)) Fri May 04 07:40:03 2007 Fri May 04 07:40:03 2007 >>> ^Z C:\junk>\python25\python 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. >>> import os, os.path, time; fn = 'hello_u.txt'; print os.stat(fn).st_mtime, os .path.getmtime(fn) 1178228403.3 1178228403.3 >>> import os, os.path, time; fn = 'hello_u.txt'; print time.ctime(os.stat(fn).s t_mtime), time.ctime(os.path.getmtime(fn)) Fri May 04 07:40:03 2007 Fri May 04 07:40:03 2007 >>> ^Z My TZ is 10 hours (plus/minus daylight saving) away from UTC. The above ctime results are correct AFAICT to plus/minus a few minutes. The change from integer to float in 2.5 is documented under os.stat_float_times. -- http://mail.python.org/mailman/listinfo/python-list
Re: adding methods at runtime and lambda
On May 3, 10:52 pm, Mike <[EMAIL PROTECTED]> wrote: > I was messing around with adding methods to a class instance at > runtime and saw the usual code one finds online for this. All the > examples I saw say, of course, to make sure that for your method that > you have 'self' as the first parameter. I got to thinking and thought > "I have a lot of arbitrary methods in several utility files that I > might like to add to things. How would I do that?" And this is what I > came up with: > > def AddMethod(currObject, method, name = None): > if name is None: name = method.func_name > class newclass(currObject.__class__):pass > setattr(newclass, name, method) > return newclass() > > And lets say I have a utility function that can check if a drive > exists on my windows box called HasDrive. I can add that like this: > > superdict = addm(dict(), lambda self, d: myUtils.HasDrive(d), > "hasdrive") > > and then I can call > > superdict.HasDrive('c') > > lambda makes it possible to add any random function because you can > use it to set self as the first parameter. I've found several real > uses for this already. My big question is, will something like this be > possible in python 3000 if lambda really does go away? I've not heard > much about lambda, reduce, etc. lately but I know Guido wanted them > out of the language. > > Is there a better way to do this today than to use lambda? It seemed > the simplest way to do this that I could find. from win32com.client import Dispatch as CreateObject class HDDs(list): def __init__(self): fso = CreateObject('Scripting.FileSystemObject') for d in fso.Drives: if d.DriveType == 2: # Fixed list.append(self, d.DriveLetter) if __name__ == "__main__": drv_list = HDDs() for d in drv_list: print d try: # Found print drv_list.index('P') except ValueError: # Not Found print "P: Not Exists!" -- http://mail.python.org/mailman/listinfo/python-list
Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?
On Fri, 04 May 2007 09:37:37 +1200, Gib Bogle <[EMAIL PROTECTED]> wrote: >Ah, so the firefighters were in on the conspiracy! No, but the firefighters are very much aware that there is more to 9/11 than has been officially revealed. This is even more true at Pentagon. The firefighters there brought dogs trained to search for survivors and/or remains and found nothing. quasi -- http://mail.python.org/mailman/listinfo/python-list
Re: _csv.Error: string with NUL bytes
On May 4, 3:40 am, [EMAIL PROTECTED] wrote: > On Thu, May 03, 2007 at 10:28:34AM -0700, [EMAIL PROTECTED] wrote: > > On May 3, 10:12 am, [EMAIL PROTECTED] wrote: > > > On Thu, May 03, 2007 at 09:57:38AM -0700, fscked wrote: > > > > > As Larry said, this most likely means there are null bytes in the CSV > > > > > file. > > > > > > Ciao, > > > > > Marc 'BlackJack' Rintsch > > > > > How would I go about identifying where it is? > > > > A hex editor might be easiest. > > > > You could also use Python: > > > > print open("filewithnuls").read().replace("\0", ">>>NUL<<<") > > > > Dustin > > > Hmm, interesting if I run: > > > print open("test.csv").read().replace("\0", ">>>NUL<<<") > > > every single character gets a >>>NUL<<< between them... > > > What the heck does that mean? > > > Example, here is the first field in the csv > > > 89114608511, > > > the above code produces: > > >>>NUL<<<8>>>NUL<<<9>>>NUL<<<1>>>NUL<<<1>>>NUL<<<4>>>NUL<<<6>>>NUL<<<0>>>NUL<<<8>>>NUL<<<5>>>NUL<<<1>>>NUL<<<1>>>NUL<<<, > > I'm guessing that your file is in UTF-16, then -- Windows seems to do > that a lot. Do what a lot? Encode data in UTF-16xE without putting in a BOM or telling the world in some other fashion what x is? Humans seem to do that occasionally. When they use Windows software, the result is highly likely to be encoded in UTF-16LE -- unless of course the human deliberately chooses otherwise (e.g. the "Unicode bigendian" option in NotePad's "Save As" dialogue). Further, the data is likely to have a BOM prepended. The above is consistent with BOM-free UTF-16BE. -- http://mail.python.org/mailman/listinfo/python-list
Re: My Python annoyances
Terry Reedy wrote: > "John Nagle" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > | Ben Collver wrote: > || > from the person who closed it. I get the unspoken message: bug > reports > | > are not welcome. > > | Getting through the process requires a year or so. > > Ben got a respond in 3 days. He didn't actually need anything fixed. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: hp 11.11 64 bit python 2.5 build gets error "import site failed"
>>> "import site failed" >>> OverflowError: signed integer is greater than the maximum. >> - what is the value of ival? > ival: 4294967295 I see. This is 0x, which would be -1 if it were of type int. So perhaps some value got cast incorrectly at some point, breaking subsequent computations > >> - where does that number come from? > > It is coming from the call to PyInt_AsLong. In that function there is > a call to: > PyInt_AS_LONG((PyIntObject*)op) > which returns the value of ival. That was not my question, really. I wanted to know where the object whose AsLong value was taken came from. And before you say "it's in the arg parameter" of convertsimple() - sure it is. However, how did it get there? It's in an argument tuple - and where came that from? IOW, you really need to know who the caller of convertsimple is, and what line of Python code precisely was triggering that call. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: hp 11.11 64 bit python 2.5 build gets error "import site failed"
[EMAIL PROTECTED] schrieb: > I am on a hp 11.11 machine doing a 64 bit python 2.5 build. When I get > my python executable created and run it, I get the error: > > "import site failed" > OverflowError: signed integer is greater than the maximum. Are you sure about the error message? That error is never produced in Python. Instead, it may print an OverflowError with signed integer is greater than maximum (i.e. no period, no "the"). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: cannot import name .....
I do see one problem there... if __name__ == 'main': t = nBaseTest('nBaseTest') t.logon() That should be: if __name__ == "__main__": t = nBaseTest('nBaseTest') t.logon() It should be like that in both files. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to replace the last (and only last) character in a string?
Dave Borne wrote: Let's suppose s='12345 4343 454' How can I replace the last '4' character? If the last '4' will not always be the last character in the string, you could do: 'X'.join(s.rsplit('4',1)) from string import rfind def replaceLast_X_with_Y( s, x, y ): lastX = s.rfind(x) return s[:lastX]+ y + s[lastX+1:] s = '12345 4343 454' replaceLast_X_with_Y( s, '4', '9' ) '12345 4343 459' sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- http://mail.python.org/mailman/listinfo/python-list
Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?
Ah, so the firefighters were in on the conspiracy! -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 OS on 64-bit machine
At Amd Turion 64, it gives: ('32bit', 'ELF') -- http://mail.python.org/mailman/listinfo/python-list
Re: How to replace the last (and only last) character in a string?
On May 3, 9:44 am, Johny <[EMAIL PROTECTED]> wrote: > On May 3, 4:37 pm, [EMAIL PROTECTED] wrote: > > > > > On May 3, 9:27 am, Johny <[EMAIL PROTECTED]> wrote: > > > > Let's suppose > > > s='12345 4343 454' > > > How can I replace the last '4' character? > > > I tried > > > string.replace(s,s[len(s)-1],'r') > > > where 'r' should replace the last '4'. > > > But it doesn't work. > > > Can anyone explain why? > > > > Thanks > > > L. > > > I think the reason it's not working is because you're doing it kind of > > backwards. For one thing, the "string" module is deprecated. I would > > do it like this: > > > s = s.replace(s[len(s)-1], 'r') > > > Although that is kind of hard to read. But it works. > > > Mike > > Mike it does NOT work for me.>>> s.replace(s[len(s)-1], 'r') > > '123r5 r3r3 r5r' > > I need only the last characte Yeah...I'm an idiot. Sorry about that. Listen to the other users! Mike -- http://mail.python.org/mailman/listinfo/python-list
PyGTK and Window Size
Hi, Currently i am developing a python script that will be executed in Gnome. This script uses the PyGTK library, however i have a question: How can I make my application to remember the last window size when it was closed? This behavior is natural for the majority of Gnome applications (i think). The trivial solution that i've imagined is to save to a config file the current status of the window, but i wish that PyGTK automatic handled this for me. Thanks, Flavio -- http://mail.python.org/mailman/listinfo/python-list
Re: My Python annoyances
* Paul Boddie (3 May 2007 07:27:11 -0700) > On 3 Mai, 15:49, Ben Collver <[EMAIL PROTECTED]> wrote: > > I installed Cygwin on a Windows machine. I try to quit from an > > interactive Python session. It tells me that on my platform, I must > > press Control-Z to exit. I press Control-Z and it makes Python a > > background process. > > Yes, Ctrl-Z exits Python in the standard Windows edition. Since Cygwin > provides a POSIX-like environment, Ctrl-D should be used instead. If > the documentation is wrong, a bug report or patch should be filed > against the software. He was using /Windows/ Python in Cygwin *chuckle*... Windows Python says Ctrl-Z because it doesn't know that it's been run from bash where Ctrl-Z is for job control. And the lesson we learn from that: if you're using Windows Python use a Windows shell. If you're using a Cygwin shell use Cygwin Python - unless you know what you're doing (which he wasn't). Thorsten -- http://mail.python.org/mailman/listinfo/python-list
Re: My Python annoyances
"Ben Collver" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] |I rewrote my code in Python and I found myself running into many of the | same hassles that I run into with other languages: inaccurate and | incomplete documentation, a maze of little platform-specific quirks to | work around in the base classes, and a macho community of users. Including you. | I tried to write portable Python code. The zlib CRC function returned | different results on architectures between 32 bit and 64 bit | architectures. I filed a bug report. It was closed, without a comment | from the person who closed it. Misleading and untrue. Here is the link you omitted http://sourceforge.net/tracker/index.php?func=detail&aid=1678102&group_id=5470&atid=105470 www.python.org/sf/1678102 Three days after you posted, 'gagenellina' explained that he thought your complaint was invalid. "py> -531560245 & 0x 3763407051L It's the same number (actually, the same bit pattern). ..." A few weeks later, noticing that you had not challenged his explanation, I closed after changing the Resolution box to Invalid. THAT WAS MY COMMENT. A month later, I notice that you still have not directly challenged G's claim of invalidity. Instead, you ignored it and simply repeated your claim here. WHO IS IGNORING WHO? | I get the unspoken message: bug reports are not welcome. Giving the shortage of reviewer time, invalid bug reports on tracker are a nuisance and a diversion from attending to valid reports and reviewing patches. That is why I encourage people to post here for community review. Real bug reports are quite welcome, as any honest person could determine by looking thru the tracker. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: My Python annoyances
"John Nagle" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | Ben Collver wrote: || > from the person who closed it. I get the unspoken message: bug reports | > are not welcome. | | That's the problem with bug reporting systems which let developers | close bugs arbitrarily. I think you should have looked at the actual tracker item, the evidence, before responding, instead of relying on a misleading claim. The item was closed as invalid three week after an explantion was given with no response from the OP. The link is in my response. | Defect reporting systems should have a status for "developer in denial". The willingness of bystanders like you to trash volunteers with random hobby horses is one reason there are fewer volunteers than needed. | Bug handling in loosely managed projects tends to follow the | same path as the "stages of grief": denial, anger, bargaining, | depression, and acceptance. Blah, blah. Not as profound as you seem to think. | Getting through the process requires a year or so. Ben got a respond in 3 days. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Real Time Battle and Python
On May 3, 5:20 am, hg <[EMAIL PROTECTED]> wrote: > Hi, > > I have started to work on a python-based robot, and am interested in your > feedback: > > http://realtimebattle.sourceforge.net/www.snakecard.com/rtb > > hg This is not necessarily a response to your effort, but just a note (rant) about realtimebattle. It reminds me more of homework in 300 and 400 level college engineering classes than a game. Based upon my previous effort and realizations, I found realtimebattle coding to be, from a programming perspective, an exercise in protocol implementation first. Once the protocol work is done you need to implement control algorithms for movement and enemy tracking. Think PID algorithms (Proportional, Integral and Differential). Only when the protocol and control portions are done can you focus on strategy and play the game. You should also note, however, that the first two tasks are quite daunting. And the second is difficult to get right. I found the whole process to be very tiring and not very rewarding. I don't mean to discourage you, I just think it would be more fun to write my own game than to 'play' that one. A better game, from a programming perspective, would be "discretetimebattle". Where each player controls their robot with second order parameters (velocity not force), the world has no third order effects (friction) and the time is discrete. Discrete time meaneing that the protocol updates every player at regular intervals with the same information and, in terms of the simulation, each update represents a set time delta. I would be interested to know if anybody else has played, or tried to play, realtimebattle and has similar sentiments. I do wish you luck though. If you get a robot working you are a far more dedicated and patient individual than me. -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check if a string is empty in python?
On May 3, 2:03 pm, John Salerno <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > On May 2, 3:49 pm, Basilisk96 <[EMAIL PROTECTED]> wrote: > >> A simple > > >> if s: > >> print "not empty" > >> else: > >> print "empty" > > >> will do. > > > How do you know that s is a string? > > Seems like a fair assumption given the OP's question and example. A fair assumption for languages other than Python. Just because s was a string at some point in the past doesn't mean it's a string now. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to replace the last (and only last) character in a string?
> Let's suppose > s='12345 4343 454' > How can I replace the last '4' character? If the last '4' will not always be the last character in the string, you could do: 'X'.join(s.rsplit('4',1)) -Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: Using python with MySQL
hlubenow wrote: > There's even another approach: ... On the other hand you may be better off with the "mysql-python"-module. Anyway, here's a nice overview over the most commonly used MySQL-commands (The commands should speak for themselves, even if the explanations are in German): http://www.linux-club.de/ftopic49585.html H. -- http://mail.python.org/mailman/listinfo/python-list
Re: adding methods at runtime and lambda
Mike wrote: > I was messing around with adding methods to a class instance at > runtime and saw the usual code one finds online for this. All the > examples I saw say, of course, to make sure that for your method that > you have 'self' as the first parameter. I got to thinking and thought > "I have a lot of arbitrary methods in several utility files that I > might like to add to things. How would I do that?" And this is what I > came up with: > > > def AddMethod(currObject, method, name = None): > if name is None: name = method.func_name > class newclass(currObject.__class__):pass > setattr(newclass, name, method) > return newclass() > > And lets say I have a utility function that can check if a drive > exists on my windows box called HasDrive. I can add that like this: > > superdict = addm(dict(), lambda self, d: myUtils.HasDrive(d), > "hasdrive") > > and then I can call > > superdict.HasDrive('c') > > lambda makes it possible to add any random function because you can > use it to set self as the first parameter. I've found several real > uses for this already. My big question is, will something like this be > possible in python 3000 if lambda really does go away? I've not heard > much about lambda, reduce, etc. lately but I know Guido wanted them > out of the language. > > Is there a better way to do this today than to use lambda? It seemed > the simplest way to do this that I could find. > You don't absolutely require lambda. def add_self(afun): def _f(self, *args, **kwargs): return afun(*args, **kwargs) return _f superdict = addm(dict(), add_self(myUtils.HasDrive), "hasdrive") James -- http://mail.python.org/mailman/listinfo/python-list
Re: adding methods at runtime and lambda
In the above example 'addm' should be 'AddMethod' superdict = AddMethod(dict(), lambda self, d: myUtils.HasDrive(d),"hasdrive") -- http://mail.python.org/mailman/listinfo/python-list
Re: Using python with MySQL
HMS Surprise wrote: > Greetings, > > I need to peform some simple queries via MySQL. Searching the list I > see that folks are accessing it with python. I am very new to python > and pretty new to MySQL too. Would appreciate it if you could point me > to some documentation for accessing MySQL via python. Something of the > "Python and MySQL for Dummies" caliber would be about my speed, but of > course I will be thankful for anything offered. > > Thanks, > > jvh There's even another approach: If you're on Linux, Qt3 may be available. Install its Python-bindings. Given a database "MyDatabase", with password "MyPassword" for user "root" and inside the database a table "MyTable", you can then do something like this: #!/usr/bin/env python from qt import * import sys from qtsql import QSqlDatabase, QSqlQuery app = QApplication(sys.argv) DB = QSqlDatabase("QMYSQL3", "MyDatabase", app) DB.setDatabaseName("MyDatabase") DB.setUserName("root") DB.setPassword("MyPassword") DB.setHostName("localhost") DB.open() c = DB.execStatement("select * from MyTable") while c.next(): print c.value(0).toString() print c.value(1).toString() print c.value(2).toString() print c.value(3).toString() c.first() c2 = DB.execStatement("select count(*) from MyTable") c2.next() print c2.value(0).toString() Some further documentation: http://www.arl.hpc.mil/ice/Manuals/PyQt/t1.html http://doc.trolltech.com/4.2/database.html H. -- http://mail.python.org/mailman/listinfo/python-list
Re: Article on wxPython ToolKit for Mac OS X
James Stroud wrote: > miah_gbg wrote: > >> Hi there! >> >> Just wanted to let people know in this group that I have recently >> (April 24th) published an introductory article on wxPython and Mac OS >> X. It is available here: http://www.macdevcenter.com/ >> >> Hope someone finds it useful. >> >> Regards, >> >> Jeremiah >> > > Nice article, but it has an inaccuracy: > > "The first thing we need to do is download wxPython so we can begin > creating applications." > > This is not entirely correct. The stock 10.4 that came in a G5 bought in > June has wx built-in: > > cabin % /usr/bin/python > Python 2.3.5 (#1, Oct 5 2005, 11:07:27) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import wx > >>> > > Of course the stock python is 2.3, but its very cool that one can depend > on wx being present on 10.4+ machines. So there is no need to bundle > python/wx with your app when developing for Macs. (Yes, I noticed the > author is running OS X 10.3.) > > James Oh yes, a mactel (Quad Xeon) bought in January? platinum 1% /usr/bin/python Python 2.3.5 (#1, Aug 12 2006, 00:08:11) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wx >>> Hell yeah, baby! -- http://mail.python.org/mailman/listinfo/python-list
adding methods at runtime and lambda
I was messing around with adding methods to a class instance at runtime and saw the usual code one finds online for this. All the examples I saw say, of course, to make sure that for your method that you have 'self' as the first parameter. I got to thinking and thought "I have a lot of arbitrary methods in several utility files that I might like to add to things. How would I do that?" And this is what I came up with: def AddMethod(currObject, method, name = None): if name is None: name = method.func_name class newclass(currObject.__class__):pass setattr(newclass, name, method) return newclass() And lets say I have a utility function that can check if a drive exists on my windows box called HasDrive. I can add that like this: superdict = addm(dict(), lambda self, d: myUtils.HasDrive(d), "hasdrive") and then I can call superdict.HasDrive('c') lambda makes it possible to add any random function because you can use it to set self as the first parameter. I've found several real uses for this already. My big question is, will something like this be possible in python 3000 if lambda really does go away? I've not heard much about lambda, reduce, etc. lately but I know Guido wanted them out of the language. Is there a better way to do this today than to use lambda? It seemed the simplest way to do this that I could find. -- http://mail.python.org/mailman/listinfo/python-list
Re: Article on wxPython ToolKit for Mac OS X
miah_gbg wrote: > Hi there! > > Just wanted to let people know in this group that I have recently > (April 24th) published an introductory article on wxPython and Mac OS > X. It is available here: http://www.macdevcenter.com/ > > Hope someone finds it useful. > > Regards, > > Jeremiah > Nice article, but it has an inaccuracy: "The first thing we need to do is download wxPython so we can begin creating applications." This is not entirely correct. The stock 10.4 that came in a G5 bought in June has wx built-in: cabin % /usr/bin/python Python 2.3.5 (#1, Oct 5 2005, 11:07:27) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wx >>> Of course the stock python is 2.3, but its very cool that one can depend on wx being present on 10.4+ machines. So there is no need to bundle python/wx with your app when developing for Macs. (Yes, I noticed the author is running OS X 10.3.) James -- http://mail.python.org/mailman/listinfo/python-list
Re: Why stay with lisp when there are python and perl?
Xah Lee <[EMAIL PROTECTED]> writes: > (if there is some demand, i will add a concrept, little programing No. There ain't. - M -- http://mail.python.org/mailman/listinfo/python-list
Re: Article on wxPython ToolKit for Mac OS X
miah_gbg wrote: > Hi there! > > Just wanted to let people know in this group that I have recently > (April 24th) published an introductory article on wxPython and Mac OS > X. It is available here: http://www.macdevcenter.com/ > > Hope someone finds it useful. > > Regards, > > Jeremiah > For the impatient: http://tinyurl.com/2z6qeq James -- http://mail.python.org/mailman/listinfo/python-list
How do I get type methods?
Hello! If I do import uno localContext=uno.getComponentContext() then localContext is of type I guess it's a new type provided by PyUNO extension. localContext.__class__ is None Is there any way to list all methods of that new type, via Python C API or through interpreter (other then dir(localContext) )? What I want is to call localContext's methods like in the tutorial example: x=MyClass() MyClass.f(x) Thank you, Dmitri -- http://mail.python.org/mailman/listinfo/python-list
Real Time Battle and Python
Hi, I have started to work on a python-based robot, and am interested in your feedback: http://realtimebattle.sourceforge.net/ www.snakecard.com/rtb hg -- http://mail.python.org/mailman/listinfo/python-list
Re: Why stay with lisp when there are python and perl?
Nameless wrote: « Python has readable syntax, a huge library, and bindings for what seems like every major in linux. Perl has CPAN. It seems with those languages if you want to do something all you have to do is import functionality from a library someone had written and use that. In lisp you'd have to "roll your own". Why should I keep on learning lisp when there are python and perl? » You question is a valid question. Unfortunately, so far in the 14 replies in the thread, vast majority are one-liner drivels from reactionary lisp fuckheads, many of which long time dwellers of comp.lang.lisp. A common scene in any programing newsgroup. They feel attacked, reasonably by your irrespective and incentive tone, and they have the need to sputter drivel back, to entertain themselves. (I wish perl and python programers take a glimpse of that thread to realize what computing factions are driveling behind each other's back) Although your message is written in a taunting style, but it has a valid point, and in fact is a Frequently Ask Question among the vast majority of programers in the computing industry. Namely, today, languages like Perl, PHP, and to a lesser degree Python, are so popular, and ubiquitous, widely deployed and widely demanded in the job market, and also, that these languages in general and in comparison to Lisp, have far wide library support and as well as community support, and also, that these comparatively young languages are relatively high-level modern languages, that they are at a level above C, Java, making them ideal for saving programer's time as does lisp. So, what are some reasons, if any, should today's programer invest time into another language lisp (especially it has trivial percentage in programing job market), while not using the time, to perhaps master a industrial language they already know, such as Perl, or even venture into another language like Python, PHP or the new kid on the block Ruby? So far, “D Herring” and “fireblade/bobi” has given their personal take on this question. Lars Rune Nøstdal, provided a link http://wiki.alu.org/The_Road_to_Lisp_Survey that details lispers's stories on why lispers lisp. Please allow me to give my take, and i believe it is a most important _technical_ reason, why, Perl, Python, etc languages today simply cannot replace lisp. And why, if you are a programer with serious intention of refining your craft, then learning lisp is a good investment. (one non-technical reason in learning lisp, is that the widely popular programer's text editor emacs has lisp embedded as its extension language. As a coder, knowing emacs and lisp, will enpower you greatly in the long term.) I think the one most important techincal aspect, that lisp is in fact superior and cannot be replaced by the current crop of high-level languages, is the peculiar fact that the language deals with symbols. Namely, sometimes called symbolic computing. I have written a exposition on this issue before. It is archived at this page: “What is Expressiveness in a Computer Language” http://xahlee.org/perl-python/what_is_expresiveness.html at the section Symbolic Computation. There are many “papers” or articles that address the question of what does it mean when someone says lisp is a symbolic language. In my opnion, they are all fuzzy, or filled with academic jargons that is practically and most likely theoretically useless. In the following exposition, you will see what lisp's “symbolic computation” in a way that makes you understand. I excerpt the section below. SYMBOLIC COMPUTATION Lisp differs from most imperative programing languages in that it deals with symbols. What does this mean? In imperative languages, a value can be assigned a name, and this name is called a variable. For example, “x=3”, and whenever this “name” is encountered, it is evaluated to its value. It does not make any sense, to have variables without a assigned value. That is, the “x” is not useful and cannot be used until you assign something to it. However, in lisp, there is a concept of Symbols. As a way of explanation, a “variable” needs not to be something assigned of a value. Symbols can stand by themselves in the language. And, when a symbol is assigned a value, the symbol can retain its symbolic form without becoming a value. This means that in lisp, “variables” can be manipulated in its un- evaluated state. The situation is like the need for the “evaluate” command in many languages, where the programer can built code as strings and do “evaluate(myCodeString)” to achieve meta-programing. For example, in imperatives languages once you defined “x=3”, you cannot manipulate the variable “x” because it gets evaluated to 3 right away. If you want, you have to build a string “"x"” and manipulate this string, then finally use something like “evaluate(myCodeString)” to achieve the effect. If the imperative language does provide a “evaluate()” function, its use breaks down quickly because the language
Re: How to check if a string is empty in python?
[EMAIL PROTECTED] wrote: > On May 2, 3:49 pm, Basilisk96 <[EMAIL PROTECTED]> wrote: >> A simple >> >> if s: >> print "not empty" >> else: >> print "empty" >> >> will do. > > How do you know that s is a string? Seems like a fair assumption given the OP's question and example. -- http://mail.python.org/mailman/listinfo/python-list
Re: _csv.Error: string with NUL bytes
[EMAIL PROTECTED] wrote: > I'm guessing that your file is in UTF-16, then -- Windows seems to do > that a lot. It kind of makes it *not* a CSV file, but oh well. Try > > print open("test.csv").decode('utf-16').read().replace("\0", > ">>>NUL<<<") > > I'm not terribly unicode-savvy, so I'll leave it to others to suggest a > way to get the CSV reader to handle such encoding without reading in the > whole file, decoding it, and setting up a StringIO file. Not pretty, but seems to work: from __future__ import with_statement import csv import codecs def recoding_reader(stream, from_encoding, args=(), kw={}): intermediate_encoding = "utf8" efrom = codecs.lookup(from_encoding) einter = codecs.lookup(intermediate_encoding) rstream = codecs.StreamRecoder(stream, einter.encode, efrom.decode, efrom.streamreader, einter.streamwriter) for row in csv.reader(rstream, *args, **kw): yield [unicode(column, intermediate_encoding) for column in row] def main(): file_encoding = "utf16" # generate sample data: data = u"\xe4hnlich,\xfcblich\r\nalpha,beta\r\ngamma,delta\r\n" with open("tmp.txt", "wb") as f: f.write(data.encode(file_encoding)) # read it with open("tmp.txt", "rb") as f: for row in recoding_reader(f, file_encoding): print u" | ".join(row) if __name__ == "__main__": main() Data from the file is recoded to UTF-8, then passed to a csv.reader() whose output is decoded to unicode. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with py2exe and microsoft speech SDK 5.1
On May 3, 1:29 pm, Dave Lim <[EMAIL PROTECTED]> wrote: > Hello, this is my first time in the mailing list so > bear with me. > > Basically what I did was I followed this > site:http://surguy.net/articles/speechrecognition.xml > > So I installed microsoft speech SDK 5.1 and then used > pythonwin COM MakePy utility for it and it worked out > fine. However, I need to compile my program into a > .exe and I have no idea how to make this work. I tried > using py2exe but I get the error: > > Traceback (most recent call last): > File "simple-speech-recognition.py", line 57, in ? > TypeError: Error when calling the metaclass bases > cannot create 'NoneType' instances > > If anybody knows a good solution to this problem I > would very much appreciate it if you can guide me to > the right path / solution. > > Thank you very much! > -Dave Lim > > __ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection > aroundhttp://mail.yahoo.com I've never done this, but I want to at some point, so I went and grabbed some good links on packaging up Python apps: http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html http://www.pharscape.org/content/view/33/51/ http://wiki.python.org/moin/Py2Exe http://www.py2exe.org/index.cgi/Tutorial There's also growth in using Python Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: My Python annoyances
André wrote: > Fortunately, Python has incorporated some newbie-unfriendly features, > like metaclasses and, to a lesser extent, decorators which, at last, > make use of a special character. There should be more of these, to > make Python something more challenging to learn. After reading the entire post about Python's ease of use, I find this particular paragraph especially pointed. :) I guess all the previous points about Python's features helps to show how these other things (decorators, etc.) really stand out as perhaps being un-Pythonic? At least, to me, it was an interesting way to make that argument. -- http://mail.python.org/mailman/listinfo/python-list
Re: Slicing Arrays in this way
John Machin wrote: > On May 3, 8:55 am, Steven D'Aprano > <[EMAIL PROTECTED]> wrote: >> On Wed, 02 May 2007 15:03:24 -0700, Tobiah wrote: >> >>> >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) >>> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] >> Wow! That's impressive. What version of Python are you using? When I try >> it, I get this: >> > elegant_solution([1,2,3,4,5,6,7,8,9,10]) >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'elegant_solution' is not defined >> > > The OP has already confessed. Don't rub it in. > Well, my first post made perfect sense. My 'confession' involved noticing that I had replied to one respondent saying that I wanted something more concise, while praising the aptness of the same solution to the next poster. Lack of oxygen, I think. -- Posted via a free Usenet account from http://www.teranews.com -- http://mail.python.org/mailman/listinfo/python-list