Re: Coding style
In message <[EMAIL PROTECTED]>, Bob Greschke wrote: > I'd go even one step further. Turn it into English (or your favorite > non-computer language): > > 1. While list, pop. > > 2. While the length of the list is greater than 0, pop. > > Which one makes more sense? Guess which one I like. CPU cycles be > damned. > :) One of my rules is, always program like the language actually has a Boolean type, even if it doesn't. That means, never assume that arbitrary values can be interpreted as true or false, always put in an explicit comparison if necessary so it's obvious the expression is a Boolean. -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode html
[EMAIL PROTECTED] wrote: > Hi, I've found lots of material on the net about unicode html > conversions, but still i'm having many problems converting unicode > characters to html entities. Is there any available function to solve > this issue? > As an example I would like to do this kind of conversion: > \uc3B4 => ô > for all available html entities. I don't know how you generate your HTML, but ElementTree and lxml both have good HTML parsers, so that you can let them write out the result with an "US-ASCII" encoding and they will generate numeric entities for everything that's not ASCII. >>> from lxml import etree >>> root = etree.HTML(my_html_data) >>> html_7_bit = etree.tostring(root, "us-ascii") Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Capturing instant messages
Ed Leafe <[EMAIL PROTECTED]> writes: > But assuming that there is no such product, would it be > possible to create something in Python, using the socket or a similar > module? They have a number of servers that provide NAT for each group > of machines; I was thinking that something on those servers could > capture all traffic on port 5190 and write it to disk. Is this > reasonable, or am I being too simplistic in my approach? Are you talking about IM's within the company, or over the internet? According to http://en.wikipedia.org/wiki/Instant_Message There are about a bazillion different protocols in use. You have to make sure everyone's using the same thing. Some of these protocols use end to end encryption, which means logging at the network side would just record ciphertext. You need to get these issues figured out. Also ask them if they're sure they need to log the conversations. According to some legal decisions, in some states, logging chats without both parties' permission is illegal, like recording a phone call. IM's are supposed to be transient communications, unlike email. As such, logging all the company's IM's is sort of like audio recording all the company's phone calls. I think the company should get a lawyer to look at this question if it hasn't already. -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
tac-tics wrote: > dwelch91 wrote: > >>tac-tics wrote: >> >>>I'd say the second one. Empty lists are not false. They are empty. Long >>>live dedicated boolean data types. >>> >> >>Uh, no, empty lists are False in a boolean context: >> >>http://docs.python.org/lib/truth.html >> >>-Don > > > Perhaps I should have specified it like this: > > empty_list = [] empty_list is not False > > True > > I'm well aware that both of these snippets does the same thing. I'm > just spouting my opinion that lists and integers are not tests, and in > an ideal world (Java??? X-) if statements support only boolean types. > > DISCLAIMER: I do not promote the use of Java. > You don't promote use of Python either if you deliberately ignore programming paradigms that have stood the test of time. Under what set of rules could it make sense to test a list for equality with a Boolean value (note also that capital "B": the word is based on someone's name). The if lst: metaphor is so well established as a means of guarding statements that should be executed only when there are elements in the list (or other container, come to that), promoting any other way to perform the test will only lead to confusion: there should be one (and preferably only one) obvious way to do it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
Peter Otten wrote: > Carl Banks wrote: > > > def process_values(lst): > > if not lst: > > return > > do_expensive_initialization_step() > > for item in lst: > > do_something_with(item) > > do_expensive_finalization_step() > > > What if you called the function like this: > > > > process_values(x.strip() for x in values_lst) > > > > Oops, now we've just gone through an expensive initialization and > > finalization for nothing (since values_lst was empty). Maybe some > > subtle bugs introduced. If we're lucky, the finalization step will > > throw an exception. > > The good news is that the above has a 99 percent chance that it just works > with iterators/generators -- even though the writer may not have been aware > of them/they didn't exist when the code was written... There's a litmus test I like to use when justifying something with percentages: I imagine that I'm presenting it to my boss, and ask myself if I still expect to have a job the next day. :-) Yes, I agree with you, it most cases I expect merely unnecessary work. (Which is not the best news; the best news would be an exception right away.) That's why I think this is only a "pretty good" reason to use "if len(lst)>0", not a slam dunk. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Solution Code
dylpkls91 wrote: > [EMAIL PROTECTED] wrote: > >>Mind posting it for us lesser beings? ;) > > > Not at all. I have yet to test it on networked computers, but it works > fine when I run both scripts on my machine. > > The hard part now is getting the server code to run as a Windows > service- argh!!! > I can get it installed and started using modified code from: > http://www.schooltool.org/products/schooltool-calendar/documentation/how-to/running-as-a-windows-service/schooltool-service.py/view > > but for some reason when the server is a service the client refuses to > connect properly! > Grrr... anybody know why? > Because there are specific requirements for Windows services, that your program isn't comlpying with. > Here is the code for the server, the machine that will execute the > commands: > > import SimpleXMLRPCServer, os > server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000)) > server.register_function(lambda command: os.popen4(command)[1].read(), > "execute") > server.serve_forever() > > And here's the code for the client, the computer that will tell the > server what command to execute: > > import xmlrpclib > server = xmlrpclib.Server("http://"; + raw_input("Enter the IP address > of the server: ") + ":8000") > output = server.execute(raw_input("Enter a command for the server to > execute: ")) > print output > I'm afraid you'll need to Google for "python windows service" or similar: in essence the main thing the service has to do (besides serve) is ensure a continuous flow of messages through the system. It's ugly, but people have done it before. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
Carl Banks wrote: > def process_values(lst): > if not lst: > return > do_expensive_initialization_step() > for item in lst: > do_something_with(item) > do_expensive_finalization_step() > What if you called the function like this: > > process_values(x.strip() for x in values_lst) > > Oops, now we've just gone through an expensive initialization and > finalization for nothing (since values_lst was empty). Maybe some > subtle bugs introduced. If we're lucky, the finalization step will > throw an exception. The good news is that the above has a 99 percent chance that it just works with iterators/generators -- even though the writer may not have been aware of them/they didn't exist when the code was written... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Track keyboard and mouse usage
That IS brain-crushingly complicated. However, thanks for the insight. I really appreciate it. Dennis Lee Bieber wrote: > On 17 Jul 2006 21:00:09 -0700, "dfaber" <[EMAIL PROTECTED]> declaimed > the following in comp.lang.python: > > > Is there no clean method of accessing the keyboard device or the mouse > > on linux? > > It seems that looking at /proc/interrupts might prove to be useful for > > keyboard monitoring. What about checking if the left mouse button is > > clicked or finding the position of the cursor on the screen? > > For a GUI application, it probably depends upon the interface > supplied by that GUI system... So far as I know, all Linux variants are > using an X-Window clone as the bottom protocol. > > Problem: X-Window supports remote displays; you'd need a means of > specifying which display to track (unless you've opened a GUI > application and that application is asking for positions -- but it may > not be able to track outside the application window... Sorry to be so > vague -- I last coded an X interface back in 1990, using xt/DECWindows > calls; didn't even have a GUI designer available*) > > I don't think anyone has ported raw X-protocol access to Python. > > All those "monitoring" operations you are asking for are "events" to > a windowing environment, and applications have to "register" for the > events they are interested in seeing. > > > > * If working raw xt/DECWindows wasn't bad enough... Add GKS (is that > still around?) on top of it -- I had a DECWindows UI whose main window > was a plain drawing region, and GKS was used to handle the underlying > data. The application was both graphics intensive, and needed a display > list (in scaleable coordinates to handle window resize) for refresh > operations; it used a 32 color "data" field, and four or so single color > "overlays" -- and any one of the five could be enabled/disabled without > requiring a recomputation of the drawing. This mess was because the > DECWindows/GKS application was an emulation (at the API level) of a late > 70s/early 80s RAMTEK graphics engine... The "main" application was > really something like 50 specialized programs that all "connected" to > the "graphics engine", drew some data, and exited; allowing other > programs in the suite to draw on the /same/ window -- which is why the > need for GKS; refreshes couldn't ask for the source application to > repaint the screen. {The very oldest version of the software ran on > PDP-11s, hence the modular programs, the control program would collect > user data/parameters, write a "common block file" then invoke the needed > submodule as an overlay. > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
Paul Rubin wrote: > "Carl Banks" <[EMAIL PROTECTED]> writes: > > What if you called the function like this: > > > > process_values(x.strip() for x in values_lst) > > > > Oops, now we've just gone through an expensive initialization and > > finalization for nothing (since values_lst was empty). Maybe some > > subtle bugs introduced. If we're lucky, the finalization step will > > throw an exception. > > You've got a function written to take a list arg and are passing it > something other than a list. Why do you expect it to work? I don't expect it to work as is. Disregarding the test for emptiness at the beginning, I would expect it to work for any iterable, even if the author only intended it for a list. That's the problem: it looks like it should work for any iterable, but it doesn't. I would think it's a pretty easy mistake to make. (I suspect lots of programmers don't even realize that empty generator expressions are true. Even if they do, it's easy to overlook that test if you're not careful.) > As soon as the function uses lst[3] for something, Notice that the function I wrote never indexes the list. It only iterates. > it will crash > if you pass it a sequence like that. The particular function I wrote might crash. Or it might merely do unnecessary work. Or it might have subtle bugs. (OTOH, if it had used the "if len(lst)>0", it would crash right away; no subtle bugs.) > Your example is mainly an > argument for static type checking. Not really. I'm merely putting forth one argument for using "if len(lst)>0" rather than "if lst". ISTM the scenerio I described isn't terribly rare: you write a function that iterates over an iterable, and carelessly use a test ("if lst") that doesn't work for all iterables, and the result could lead to subtle bugs. Which is not as bad as carelessly using a test ("if len(lst)>0") that doesn't work for all iterables, and the result is an immediate exception. I've given two pretty good reasons for using "if len(lst)>0": it allows functions to be written generically for lists and numpy arrays, and it catches the rather plausible mistake of testing the truth value an iterable (which can lead to subtle bugs). This is contrasted to the good reasons for using "if lst", which are... um... hmm... saving a few keystrokes? Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: function v. method
I guess the python devs are not interested in implementing something that would require new syntax and does not give something entirely new to the language. The good thing about python is, that the devs are only implementing ideas that are very cool. There are a lot of cool (!= very cool) ideas in rejected peps - but they were never implemented for good reasons. If you *really* need privates, just use the naming convention. -- http://mail.python.org/mailman/listinfo/python-list
Capturing instant messages
I've been approached by a local business that has been advised that they need to start capturing and archiving their instant messaging in order to comply with Sarbanes-Oxley. The company is largely PC, but has a significant number of Macs running OS X, too. Googling around quickly turns up IM Grabber for the PC, which would seem to be just what they need. But there is no equivalent to be found for OS X. So if anyone knows of any such product, please let me know and there will be no need for the rest of this post. But assuming that there is no such product, would it be possible to create something in Python, using the socket or a similar module? They have a number of servers that provide NAT for each group of machines; I was thinking that something on those servers could capture all traffic on port 5190 and write it to disk. Is this reasonable, or am I being too simplistic in my approach? -- Ed Leafe -- http://leafe.com -- http://dabodev.com -- http://mail.python.org/mailman/listinfo/python-list
Google Earth contact? (OT, sort of...)
Sorry if this is an off topic shot in the dark, but... Does anyone know a contact for anyone that works for Google Earth? I wanted to shoot 'em an email about a possible enhancement, but they're smart enough to not leave contact info ANYWHERE on their websites. -- http://mail.python.org/mailman/listinfo/python-list
Help me
Simple though but how do you check your internet connection by Python ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
"Carl Banks" <[EMAIL PROTECTED]> writes: > What if you called the function like this: > > process_values(x.strip() for x in values_lst) > > Oops, now we've just gone through an expensive initialization and > finalization for nothing (since values_lst was empty). Maybe some > subtle bugs introduced. If we're lucky, the finalization step will > throw an exception. You've got a function written to take a list arg and are passing it something other than a list. Why do you expect it to work? As soon as the function uses lst[3] for something, it will crash if you pass it a sequence like that. Your example is mainly an argument for static type checking. -- http://mail.python.org/mailman/listinfo/python-list
Re: about Python types and objects
> I have read the booth python types and objects. I think its book for > clearificating types and objects in python. It says there will be a > book named python attributes and methods. Do you know any information > about this book. I am interested in it. Hey pipehappy, __Python Attributes and Methods__ can be found at: http://www.cafepy.com/article/python_attributes_and_methods/ For anyone else interested, the 'book' pipehappy originally referred to is __Python Types and Objects__: http://www.cafepy.com/article/python_types_and_objects/ Hope this helps. -alex23 -- http://mail.python.org/mailman/listinfo/python-list
function v. method
At first I was going to post the following: I just discovered the inspect module, which contains the isfunction and ismethod functions. For some reason, I used to be under the impression that Python methods are no different from Python functions. Naturally, I wondered why both of these needed to exist (I also later discovered the isroutine function). So I started to experiment at prompt. Here's what I did: >>> from inspect import * >>> def dan(): pass ... >>> ismethod(dan) False >>> isfunction(dan) True >>> class Foo: ... def meth(self): pass ... >>> m = Foo.meth >>> m >>> ismethod(m) True >>> Foo.func = dan# <-- Appearantly, something magical happens here, >>> because... >>> Foo.func >>> f = Foo.func >>> f is dan # <-- things begins to look suprising here. False >>> ismethod(f) True Imagine my surprise. Why would Python do this? but then I tried this: >>> res = Foo.__dict__['func'] >>> res is dan True And it all started to make sense. The surprising thing turned out to be not so surprising: When the expression Foo.func gets evaluated, we get a method which is just a wrapper around dan. Therefore, f is not dan! This is still a little bit of magic, which gets me thinking again about the stuff I self-censored. Since the dot syntax does something special and unexpected in my case, why not use some more dot-magic to implement privates? Privates don't have to be entirely absent from Klass.__dict__ (which would make Python not introspective); they can just be invisible when using the dot-syntax. BTW, I am aware of Python's name mangling feature. -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
PTY wrote: > Which is better? > > lst = [1,2,3,4,5] > > while lst: > lst.pop() > > OR > > while len(lst) > 0: > lst.pop() Here's another reason not to use "if lst". Say you have a function that looks like this: def process_values(lst): if not lst: return do_expensive_initialization_step() for item in lst: do_something_with(item) do_expensive_finalization_step() That works, right? No problem, right? What if you called the function like this: process_values(x.strip() for x in values_lst) Oops, now we've just gone through an expensive initialization and finalization for nothing (since values_lst was empty). Maybe some subtle bugs introduced. If we're lucky, the finalization step will throw an exception. If we had used "if len(list)>0", we'd have gotten a nice exception telling us that a generator is not welcome. Then we'd have changed the argument to a list comprehension, or better, changed the function to work for any iterator. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: range() is not the best way to check range?
Grant Edwards wrote: > for pete's sake use the comparison operator like god intended. > > if 0 <= i <= 1: I'm assuming you used Python's compound comparison as opposed to the C-style of and'ing two comparisons together to emphasize the fact it is god's chosen way of doing this ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
Patrick Maupin wrote: > PTY wrote: > > > It looks like there are two crowds, terse and verbose. I thought terse > > is perl style and verbose is python style. BTW, lst = [] was not what > > I was interested in :-) I was asking whether it was better style to > > use len() or not. > > It's not canonical Python to use len() in this case. From PEP 8: > > - For sequences, (strings, lists, tuples), use the fact that empty > sequences are false. > > Yes: if not seq: >if seq: > > No: if len(seq) > if not len(seq) > > The whole reason that a sequence supports testing is exactly for this > scenario. This is not an afterthought -- it's a fundamental design > decision of the language. That might have made sense when Python and string, list, tuple were the only sequence types around. Nowadays, Python has all kinds of spiffy types like numpy arrays, interators, generators, etc., for which "empty sequence is false" just doesn't make sense. If Python had been designed with these types in mind, I'm not sure "empty list is false" would have been part of the language, let alone recommend practice. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
PTY wrote: > Which is better? > > lst = [1,2,3,4,5] > > while lst: > lst.pop() > > OR > > while len(lst) > 0: > lst.pop() I'm going to go against general opinion and suggest using "len(lst)>0", though this is not a good example of why I think that. In practice, I'd say the former is less generic. No, that's not a typo. If you were to write a function that expects a list (and actually uses the list interface, indexing and such, rather than merely passing it off to another function), the function would almost certainly fail if you were to pass in an integer or some other non-sequence type. However, functions expecting a list have a decent chance of working if you were to pass in a numpy array. But if you were to write "if lst" instead of "if len(lst)>0", then you've just ensured your function will fail for numpy arrays. But you get no benefit in genericity, because non-sequence types almost certainly wouldn't work anyways. Therefore, the only time I'd recommend using "if lst" is if all you're doing is passing it to other functions. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: How properly manage memory of this PyObject* array?? (C extension)
On 18/07/2006 1:45 PM, [EMAIL PROTECTED] wrote: >> Let's try reductio ad adsurdum on that one. Suppose that instead of >> filling in a malloced chunk of memory, you had stored those gizmoids in >> local variables foo0, foo1, foo2, etc. Using your reasoning: we can't >> ever return from our function (which frees up the stack memory >> containing foo0 etc) because we don't know when garbage collector will >> free foo0 etc. Avoiding that problem would require a Python/C API >> function with a name like Py_AwaitGarbageCollection() ... but there >> isn't one. > > There are 2 memory components that make up a Python object. > First, there is the object in memory itself. Secondly, there > is the 4 bytes or so that hold the address to the object in memory. > (the 'pointer') *WRONG*. The object exists in and of itself. There may be one *or more* references to it, via pointers, scattered about in memory; they are *NOT* components of the object. A reference count is maintained inside the object and manipulated by Py_INCREF etc. The Python garbage collector knows *nothing* about the memory occupied by those pointers; it is *your* responsibility to allocate and free them. If the pointers are in a function's local variables, that memory is automatically returned when you return from the function. If the pointers are in a chunk of memory that you grabbed using malloc(), then you must free() the chunk as soon as you are finished with it. Like I said: You malloced it? You free it. You didn't malloc it? You don't free it. > > I think what I hear you saying is that garbage collection has > to automagically take care of my second component above as well. I'm terribly sorry, but there is no magic involved with memory management at this level; only hard, tedious, error-prone work. Python garbage collection has neither the responsibility nor the necessary information for carrying out that task. *YOU* have that information; it is *YOUR* responsibility. > > So can I assume you are also saying our original malloc'd pointer > to Python objects will be take care of as well as the objects? *NO* You must free() any memory that you malloc()ed. > (Hence, no free(my_array) necessary?) *NO* You must free() any memory that you malloc()ed. > (Only Py_INCREFs and Py_DECREFs need apply?) *NO* You must free() any memory that you malloc()ed. "What I tell you three times is true" -- the Bellman in "The Hunting of the Snark", by Lewis Carroll. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
win32com.client.Dispatch - understanding error messages
O/S : Win2K vsn of Python: 2.4 Hoping to find information that provide information about error messages being encountered. Pythonwin session: >>> import win32com.client >>> blah = win32com.client.Dispatch('MSXML2.XMLHTTP') >>> blah.open("POST", "12.5.81.49/crg_cbsil_vtest_52/crg.aspx", 0) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in open com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None) I tried various combinations in Google involving "win32com.client.Dispatch", "MSXML2", "XMLHTTP" and the 2 different error codes: -2147352567 and -2147467259. So far, I haven't been able to locate anything that has helped me zero in on the error. The fact that no error was issued after the blah = ... statement plus the fact that as soon as I typed the '(' character after blah.open, that the arguments for the open method were displayed; those two things make me think that the COM object is installed/registered on the workstation. Is that a reasonable conclusion? I observed that there are a few other similarly named objects/methods, so I tried them as well. The error messages reference some different dll's, but those error message seemed as inscrutable as the first set of error messages above. >>> blah = win32com.client.Dispatch('MSXML2.XMLHTTP.4.0') >>> blah.open("POST", "12.5.81.49/crg_cbsil_vtest_52/crg.aspx", 0) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in open com_error: (-2147352567, 'Exception occurred.', (0, 'msxml4.dll', 'System error: -2147012890.\r\n', None, 0, -2147012890), None) and >>> blah = win32com.client.Dispatch('MSXML2.ServerXMLHTTP') >>> blah.open("POST", "12.5.81.49/crg_cbsil_vtest_52/crg.aspx", 0) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in open com_error: (-2147352567, 'Exception occurred.', (0, 'msxml3.dll', 'Unspecified error\r\n', None, 0, -2147467259), None) Also tried varying the 3rd argument...instead of using 0 to represent False, I tried: >>> False False >>> blah = win32com.client.Dispatch('MSXML2.XMLHTTP') >>> blah.open("POST", "12.5.81.49/crg_cbsil_vtest_52/crg.aspx", False) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in open com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None) So, if possible, it would be nice to know two different types of things: 1) what steps to take to correct these errors 2) where one can locate information about these types of errors -- http://mail.python.org/mailman/listinfo/python-list
Matplotlib and mouse events
I am trying to use matplotlib to display two images and then by mouse clickidentify a source in each image. The setup is as follows figim = figure(figsize=(8,4)) axsrc24 = figim.add_subplot(121, xlim=(0,200), ylim=(0,200), autoscale_on=False) axsrc24.set_title('Click to zoom') axsrc70 = figim.add_subplot(122, xlim=(0,100), ylim=(0,100), autoscale_on=False) axsrc70.set_title('Click to zoom') def clicker(event): if event.inaxes == axsrc24: print 'you clicked on the 24 micron image' if event.inaxes == axsrc70: print 'you clicked on the 70 micron image' return figim.canvas.mpl_connect("button_press_event",clicker)Now I want to only be able to click each subplot once then lock that subplot(making it unclickable) and also close the figure when both images have beenclicked on, but I am stuck on implementing this. Anyone have any suggestions. I am using the TkAgg interface on a Mac.Cheers Tommy[EMAIL PROTECTED]http://homepage.mac.com/tgrav/"Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genious -- and a lot of courage -- to move in the opposite direction" -- Albert Einstein -- http://mail.python.org/mailman/listinfo/python-list
Re: range() is not the best way to check range?
On 2006-07-18, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > it seems that range() can be really slow: > > the following program will run, and the last line shows how long it ran > for: > > import time > > startTime = time.time() > > a = 1.0 > for i in range(0, 3): > if i in range (0, 1): > a += 1 > if not i % 1000: print i > > print a, " ", round(time.time() - startTime, 1), "seconds" > or is there an alternative use of range() or something similar that can > be as fast? Creating and then searching a 10,000 element list to see if a number is between two other numbers is insane. Using xrange as somebody else suggested is also insane. If you want to know if a number is between two other numders, for pete's sake use the comparison operator like god intended. if 0 <= i <= 1: -- Grant Edwards grante Yow! ANN JILLIAN'S HAIR at makes LONI ANDERSON'S visi.comHAIR look like RICARDO MONTALBAN'S HAIR! -- http://mail.python.org/mailman/listinfo/python-list
Re: Track keyboard and mouse usage
Is there no clean method of accessing the keyboard device or the mouse on linux? It seems that looking at /proc/interrupts might prove to be useful for keyboard monitoring. What about checking if the left mouse button is clicked or finding the position of the cursor on the screen? -- http://mail.python.org/mailman/listinfo/python-list
Re: How properly manage memory of this PyObject* array?? (C extension)
> if you use malloc to allocate a memory block and store PyObject pointers > in it, you must > > 1) make sure that the reference count is *incremented* (Py_INCREF) when > you add the objects (unless the object is new; when you create an > object, the reference count is set to 1). this tells Python that you > have a pointer to an object that you plan to use some time in the future. > > 2) make sure that the reference count is *decremented* (Py_DECREF) if > you remove the objects (this tells Python that *you* won't access the > object any more; if nobody else uses it either, it can safely be removed). OK, I'll read your 'required reading' I promise. Let me just make the obvious obvious for a minute. Your 'requirements' above only mention Py_INCREFs and Py_DECREFs and never mention free(my_array). Hence, I will assume the answer to my previous question is that I do NOT have to do free(my_array) because Py_INCREFs and Py_DECREFs will allow garbage collection to take care of even the malloc'd part that hold the pointers to the objects. By the way, we are allowing garbage collector to free different elements (pointers) of my_array one at a time here. I just found out that curiously enough, you CANNOT do this in C with primitive types. i.e. my_int_array = malloc(5 * sizeof(int)); You CANNOT do this... free(&my_int_array[1]); free(&my_int_array[2]); free(&my_int_array[3]); ...etc. You can ONLY free the entire enchilada all at the same time... free(my_int_array); Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: How properly manage memory of this PyObject* array?? (C extension)
> Let's try reductio ad adsurdum on that one. Suppose that instead of > filling in a malloced chunk of memory, you had stored those gizmoids in > local variables foo0, foo1, foo2, etc. Using your reasoning: we can't > ever return from our function (which frees up the stack memory > containing foo0 etc) because we don't know when garbage collector will > free foo0 etc. Avoiding that problem would require a Python/C API > function with a name like Py_AwaitGarbageCollection() ... but there > isn't one. There are 2 memory components that make up a Python object. First, there is the object in memory itself. Secondly, there is the 4 bytes or so that hold the address to the object in memory. (the 'pointer') I think what I hear you saying is that garbage collection has to automagically take care of my second component above as well. So can I assume you are also saying our original malloc'd pointer to Python objects will be take care of as well as the objects? (Hence, no free(my_array) necessary?) (Only Py_INCREFs and Py_DECREFs need apply?) Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Track keyboard and mouse usage
MCI> Look PyHook ( http://cheeseshop.python.org/pypi/pyHook/1.4 ) MCI> Ooooh!!! Sorry! It's for Windows... That's okay (well, for me anyway). Watch runs on Windows. Perhaps someone with Windows would like to plug pyHook into watch? Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: General Hash Functions In Python
John Machin wrote: > Perhaps you should, if you profess an interest in hashed lookup -- it > gives some interesting commentary on the second aspect: collision > handling. What matters is the *total* time to return an answer. > Time or algorithm complexity is merely one aspect of a hash function design. there are many others. > > as far as time, well > > people interested, as is how started my original port, would be more > > than willing to try/assess the routines for sets of strings that they > > wish to hash etc. > > > this site may help explain plus has some code > > snippets that may help you understand what I mean. > > > > http://www.partow.net/programming/hashfunctions/index.html > > That JSHAsh allegedly written by "Justin Sobel": by coincidence, there's > a Melbourne academic named Justin Zobel who has done something amazingly > similar: > > http://goanna.cs.rmit.edu.au/~hugh/zhw-ipl.html > Same guy, he was a lecturer during my uni days. As far as his surname that is another issue altogether. > Searching for "Justin Sobel" did lead me to a Russian website which > apart from repeating your typo/reado/whatevero did propose (and test) > some more hash functions. > > http://vak.ru/doku.php/proj/hash/efficiency-en > > In particular look at the "rot13" function which was right up near the > front as far as number of collisions goes, and which would appear (my > guess based on reading the source) to be very fast (with the right > compiler (e.g. gcc 4)). > I've already spoken to the guy that did those measurements, there are some flaws in the way he represents data which could lead one to make inaccurate assumptions about the "quality" of the hash functions. One of the many issues that i took up with him is that he only used 1 set of data instead of having multiple sets and aggregating the results. Whether or not he decides to re-do is analysis is another issue altogether. TAOCP has a nice section on how potential analysis can be done. > I would have thought it important especially in the case of well-known > functions whose properties have been discussed in the literature that > you should not publish a version that gives a different answer, without > noting that fact prominently. > True, the c versions work fine, i guess the python versions require a bit more work. feel free to re-post modified versions :) > You can't avoid using Python longs if you want to simulate unsigned > 32-bit arithmetic. However judicious truncation can be used to stop the > longs becoming longer and slower. General rules: > 1. Avoid exceeding 32 bits where possible. E.g. instead of > hash <<= 8 > do > hash = (hash & 0xFF) << 8 > 2. Where unavoidable (e.g. hash *= constant), use hash &= 0x to > chop back to 32 bits, once per iteration. > > That is something I thought about, but I also considered, as I mentioned before, the extra bits. The more bits you have to avalanche with - (in a very general and oversimplified way) the better your hash function "can" be. > Thanks to Josh Bloch ([EMAIL PROTECTED]) who also informed me about > another fault that is found in Aho, Sethi and Ullman's book: The line > with h ^= (g >> 28) now replaces the original h ^= (g >> 24). According > to a correspondence of Josh Bloch with Ravi Sethi this correction will > be made in the next edition of the book. Including these two changes > this hash function is now comparable to Vo's, Torek's and WAIS's hash > functions. > """ > > (1) Whoops! (2) Vo? Torek? WAIS? Could these be possible additions to > your website? > Indeed! I had read about WAIS a long time ago, I'll be putting them up very soon, thanks for the input. > http://www.math.columbia.edu/~bayer/annote/root/root.html > """ > Peter J. Weinberger hash function; see e.g. 21st Century Compilers, by > Alfred V. Aho, Ravi Sethi, Monica Lam, Jeffrey D. Ullman, ISBN 0321131436. > > Hash unsigned X into H, using the temporary variable G. G and H are > unsigned variables; X may be an expression. G is nonzero e.g. 92% of > time, so a conditional expression would be slower. As noted by Josh > Bloch, 28 is the correct replacement for the frequent misprint 24. > > #define HASH(G,H,X) ( H <<= 4, H += (X), G = H & 0xf000, H ^= G >> > 28, H ^= G ) > """ I'm planning on adding various integer hash functions as well, just haven't had the time. the above seems like one so I'll give it a go. Arash Partow Be one who knows what they don't know, Instead of being one who knows not what they don't know, Thinking they know everything about all things. http://www.partow.net -- http://mail.python.org/mailman/listinfo/python-list
RFC: my iterthreader module
I have this iterthreader module that I've been working on for a while now. It is similar to itertools.imap, but it calls each function in its own thread and uses Queues for moving the data around. A better name for it would probably be ithreadmap, but anyway... The short explanation of it is if you have a loop like for item in biglist: print "The value for %s is %s" % (item, slowfunc(item)) or for item,val in ((item, slowfunc(item)) for item in biglist): print "The value for %s is %s" % (item, val) you can simply rewrite it as for item,val in iterthreader.Threader(slowfunc, biglist): print "The value for %s is %s" % (item, val) and it will hopefully run faster. The usual GIL issues still apply of course You can also subclass it in various ways, but I almost always just call it in the above manner. So, can anyone find any obvious problems with it? I've been meaning to re-post [1] it to the python cookbook, but I'd like to hear what others think first. I'm not aware of any other module that makes this particular use of threading this simple. [1] I _think_ I posted it before, but that may have just been in a comment import threading import Queue class Threader: def __init__(self, func=None, data=None, numthreads=2): if not numthreads > 0: raise AssertionError("numthreads should be greater than 0") if func: self.handle_input=func if data: self.get_input = lambda : data self._numthreads=numthreads self.threads = [] self.run() def __iter__(self): return self def next(self): still_running, input, output = self.DQ.get() if not still_running: raise StopIteration return input, output def get_input(self): raise NotImplementedError, "You must implement get_input as a function that returns an iterable" def handle_input(self, input): raise NotImplementedError, "You must implement handle_input as a function that returns anything" def _handle_input(self): while 1: work_todo, input = self.Q.get() if not work_todo: break self.DQ.put((True, input, self.handle_input(input))) def cleanup(self): """wait for all threads to stop and tell the main iter to stop""" for t in self.threads: t.join() self.DQ.put((False,None,None)) def run(self): self.Q=Queue.Queue() self.DQ=Queue.Queue() for x in range(self._numthreads): t=threading.Thread(target=self._handle_input) t.start() self.threads.append(t) try : for x in self.get_input(): self.Q.put((True, x)) except NotImplementedError, e: print e for x in range(self._numthreads): self.Q.put((False, None)) threading.Thread(target=self.cleanup).start() -- - Justin -- http://mail.python.org/mailman/listinfo/python-list
Re: range() is not the best way to check range?
[EMAIL PROTECTED] wrote: > so if i change the line > if i in range (0, 1): > to > if i >= 0 and i < 1: [snip;] > is there an alternative use of range() or something similar that can > be as fast? you've found that alternative yourself! just use the comparison operators... in fact, you can write a little more compact as: if 0 <= i < 1 : [sreeram;] signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: range() is not the best way to check range?
On 18/07/2006 12:41 PM, [EMAIL PROTECTED] wrote: > it seems that range() can be really slow: > > the following program will run, and the last line shows how long it ran > for: > > import time > > startTime = time.time() > > a = 1.0 > for i in range(0, 3): > if i in range (0, 1): > a += 1 > if not i % 1000: print i > > print a, " ", round(time.time() - startTime, 1), "seconds" > > > - > the last line of output is > - > > 10001.0 22.8 seconds > > so if i change the line > > if i in range (0, 1): > > to > > if i >= 0 and i < 1: > > the the last line is > > 10001.0 0.2 seconds > > so approximately, the program ran 100 times faster! > > or is there an alternative use of range() or something similar that can > be as fast? Some things to try: 1a. Read what the manual has to say about the range() function ... what does it produce? 1b. Read what the manual has to say about time.time() and time.clock(). Change over to using time.clock(). Change the round(, 1) to (say) 4. Alternatively, use something like this: print "%.1f ... %.4f seconds" % (a, time.clock() - startTime) 1c. Repeat the two ways that you tried already. 2. First alternative: Do this: test_range = range(1) *once*, just after "a = 1.0". and change your if test to if i in test_range: 3. Now change that to: test_range = set(range(1)) 4. Now forget about test_range, and change your if test to this: if 0 <= i < 1: HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: range() is not the best way to check range?
Leif K-Brooks wrote: > [EMAIL PROTECTED] wrote: > > or is there an alternative use of range() or something similar that can > > be as fast? > > You could use xrange: > > [EMAIL PROTECTED]:~$ python -m timeit -n1 "1 in range(1)" > 1 loops, best of 3: 260 usec per loop > [EMAIL PROTECTED]:~$ python -m timeit -n1 "1 in xrange(1)" > 1 loops, best of 3: 0.664 usec per loop That's only because you're choosing a number that's early in the list. ~$ python -m timeit -n1 "1 in xrange(1)" 1 loops, best of 3: 1.22 usec per loop ~$ python -m timeit -n1 " in xrange(1)" 1 loops, best of 3: 1.24 msec per loop That's *milliseconds*, not microseconds. -- http://mail.python.org/mailman/listinfo/python-list
Re: question about what lamda does
[EMAIL PROTECTED] wrote: > Hey there, > i have been learning python for the past few months, but i can seem to > get what exactly a lamda is for. It defines a function. f = lambda x, y: expression is equivalent to def f(x, y): return expression Note that lambda is an expression while def is a statement. > What would i use a lamda for that i > could not or would not use a def for ? Is there a notable difference ? > I only ask because i see it in code samples on the internet and in > books. Lambdas are typically used as parameters to functions that take functions as arguments, like property() and reduce(). You never *need* to use one, but sometimes it's convenient. -- http://mail.python.org/mailman/listinfo/python-list
Re: range() is not the best way to check range?
[EMAIL PROTECTED] wrote: > or is there an alternative use of range() or something similar that can > be as fast? You could use xrange: [EMAIL PROTECTED]:~$ python -m timeit -n1 "1 in range(1)" 1 loops, best of 3: 260 usec per loop [EMAIL PROTECTED]:~$ python -m timeit -n1 "1 in xrange(1)" 1 loops, best of 3: 0.664 usec per loop -- http://mail.python.org/mailman/listinfo/python-list
Re: using capicom with python
"stéphane bard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi all, > Has anyone ever used Python to work with Certificate Services in > Windows? I'm trying to capicom dll with pywin32. > > > I've found some reference about python and capicom in > this mail archive > http://mail.python.org/pipermail/python-win32/2006-March.txt > > but nothing really helpfull. > I try to use windll from ctypes module > > > >> windll.load( > > but don't get access to capicom. > > any idea ? COM dll's usually aren't designed to be used directly. You request instances of the interfaces they implement by guid or program id. import win32com.client certstore=win32com.client.Dispatch('capicom.store') certstore.Open(StoreName='Root') for cert in certstore.Certificates: print 'SubjectName:', cert.SubjectName, 'IssuerName:', cert.IssuerName Roger -- http://mail.python.org/mailman/listinfo/python-list
Re: range() is not the best way to check range?
[EMAIL PROTECTED] wrote: > it seems that range() can be really slow: ... > if i in range (0, 1): This creates a 10,000-element list and sequentially searches it. Of course that's gonna be slow. -- http://mail.python.org/mailman/listinfo/python-list
Re: Any pyChart experts lend a hand?
[EMAIL PROTECTED] wrote: > Code > > from pychart import * > import sys > theme.get_options() > > theme.use_color = True > theme.output_format="png" > theme.output_file="C:\Comp\graphic\pic1.png" > theme.reinitialize() > > data = [("foo", 10),("bar", 20), ("baz", 30), ("ao", 40)] > > ar = area.T(size=(300,300), legend=legend.T(), > x_grid_style = None, y_grid_style = None) > > plot = pie_plot.T(data=data, arc_offsets=[0,10,0,10], > shadow = (2, -2, fill_style.gray50), > label_offset = 25, > arrow_style = arrow.a3) > ar.add_plot(plot) > ar.draw() > i've been playing with pychart for exactly 5 minutes just before i read your post, so i doubt that makes me an expert, but i did your code to work by changing your code to this: from pychart import * import sys theme.get_options() theme.use_color = True can = canvas.init('pic1.png') data = [("foo", 10),("bar", 20), ("baz", 30), ("ao", 40)] ar = area.T(size=(300,300), legend=legend.T(), x_grid_style = None, y_grid_style = None) plot = pie_plot.T(data=data, arc_offsets=[0,10,0,10], shadow = (2, -2, fill_style.gray50), label_offset = 25, arrow_style = arrow.a3) ar.add_plot(plot) ar.draw() bryan -- http://mail.python.org/mailman/listinfo/python-list
python script reading special keys like , etc.
I am planning to write a very simple python script that displays files based on user input. E.g. I need to display f1.msg file if the user presses key, f2.msg file if the user presses key. What is the easiest way to do this on Linux (xterm/vt100/asni etc). I tried using curses and it works, but I want something that does NOT modify or redraw the user screen. Something like this: def display(): key = raw_input() if key == sys.stdout.write(open(f1.msg, "r").read()) elif key == sys.stdout.write(open(f2.msg, "r").read()) else: # I need to capture his input string too. return key I can make a restriction that the user press after typing the above keys if required. Is there a solution that doesn't redraw the screen like curses does and kind of portable at the same time to different terminals on Linux/Unix? -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
PTY wrote: > It looks like there are two crowds, terse and verbose. I thought terse > is perl style and verbose is python style. BTW, lst = [] was not what > I was interested in :-) I was asking whether it was better style to > use len() or not. It's not canonical Python to use len() in this case. From PEP 8: - For sequences, (strings, lists, tuples), use the fact that empty sequences are false. Yes: if not seq: if seq: No: if len(seq) if not len(seq) The whole reason that a sequence supports testing is exactly for this scenario. This is not an afterthought -- it's a fundamental design decision of the language. Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list
range() is not the best way to check range?
it seems that range() can be really slow: the following program will run, and the last line shows how long it ran for: import time startTime = time.time() a = 1.0 for i in range(0, 3): if i in range (0, 1): a += 1 if not i % 1000: print i print a, " ", round(time.time() - startTime, 1), "seconds" - the last line of output is - 10001.0 22.8 seconds so if i change the line if i in range (0, 1): to if i >= 0 and i < 1: the the last line is 10001.0 0.2 seconds so approximately, the program ran 100 times faster! or is there an alternative use of range() or something similar that can be as fast? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error? [correction]
Darren New wrote: > David Hopwood wrote: > >> public class LoopInitTest { >> public static String getString() { return "foo"; } >> >> public static void main(String[] args) { >> String line = getString(); >> boolean is_last = false; >> >> while (!is_last) { >> if (line.charAt(0) == 'q') { >> is_last = true; >> } >> >> // insert line into inputs (not important for analysis) >> >> if (!is_last) { >> line = getString(); >> } >> } >> } >> } >> >> which compiles without error, because is_last is definitely initialized. > > At what point do you think is_last or line would seem to not be > initialized? They're both set at the start of the function, and (given > that it's Java) nothing can unset them. > > At the start of the while loop, it's initialized. At the end of the > while loop, it's initialized. So the merge point of the while loop has > it marked as initialized. Apparently, Hermes (at least the version of it described in that paper) essentially forgets that is_last has been initialized at the top of the loop, and so when it does the merge, it is merging 'not necessarily initialized' with 'initialized'. This sounds like a pretty easy thing to fix to me (and maybe it was fixed later, since there are other papers on Hermes' typestate checking that I haven't read yet). -- David Hopwood <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a shell script from a python script
spec wrote: > Thanks, actually there are no args, is there something even simpler? > > Thanks > Frank you could try os.system() >From the docs: system(command) Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to posix.environ, sys.stdin, etc. are not reflected in the environment of the executed command. On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent. On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation. Availability: Macintosh, Unix, Windows. -- http://mail.python.org/mailman/listinfo/python-list
Re: solving equation system
TG wrote: > Sorry for the poor explanation. I'm trying to put it clear now. > > i've got A and B. I'm looking for X. I made a mistake in my equation > :-/ > > It's more like : > > A.X - B >= O > > Well, maybe it will be much more simple if I explain the underlying > problem : > > I have an array of N dimensions (generally 2). > - A first calculation gives me a set of integer coordinates inside this > array, which I will call the point W. > - After several other calculations, I've got a set of coordinates in > this N dimensional space that are floating values, and not bound to the > limits of my original N-array. This is the point L. > > What I want to do is to translate the point L along the vector LW in > order to get a point L' which coordinates are inside the original > N-dimensional array. Then it will be easy to get the closest integer > coordinates from L'. I see. You have a simple linear programming problem. These can be tricky in general. Because you only have one variable, it's probably ok to use brute force. Try this: given X, A, and B: E = A*X-B C = numpy.where(E<0,B/A,X) X = min(C) This assumes that you've designed the problem such that B/A would be less than X where A*X-B<0 (if the opposite were true then of course you'd need max(C)). Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
embedding python in a plugin
Hi, I'm developing a linux plugin to a CG package that embeds a Python interpreter. The plugin.so requires a companion plugin.sog file in its directory to allow module imports; imports fail without the .sog file. Can somebody please explain what the .sog file does and why it is needed? I can't find any mention of this in the extending/embedding docs or the CG package documentation. Or is this a linux thing? Thanks, Roger -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
tac-tics wrote: > I'm well aware that both of these snippets does the same thing. I'm > just spouting my opinion that lists and integers are not tests, ... No, but testing their Boolean nature _is_ a test. Aggregate objects in Python are true if they are non-empty, and false if they are empty. That is reasonable, not uncommon a convention, and quite useful for exactly the situations you were talking about. That convention exists _so that_ writing:: if aContainer: ... container is not empty ... is meaningful and convenient. So the answer to the original question was, "The first one." Feel free to write it the other way with an explicit test, but it's not Pythonic. -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Life is a toy made of glass; it appears to be of inestimable price, but in reality it is very cheap. -- Pietro Aretino, 1537 -- http://mail.python.org/mailman/listinfo/python-list
Piping external commands
What is the Python translation for this Bash statement: tar cf - "[EMAIL PROTECTED]" | bzip2 > "$file".tar.bz2 (Ignoring the fact that "tar cjf" also exists...) In other words, how does one pipe together arbitrary commands? -- http://mail.python.org/mailman/listinfo/python-list
Re: run a string as code?
py_genetic wrote: > py_genetic wrote: > >> [EMAIL PROTECTED] wrote: >> >>> py_genetic wrote: >>> How can you make python interpret a string (of py code) as code. For example if you want a py program to modify itself as it runs. I know this is an advantage of interpreted languages, how is this done in python. Thanks. >>> This might do it... >>> >>> >> print eval.__doc__ >> >>> eval(source[, globals[, locals]]) -> value >>> >>> Evaluate the source in the context of globals and locals. >>> The source may be a string representing a Python expression >>> or a code object as returned by compile(). >>> The globals must be a dictionary and locals can be any mappping, >>> defaulting to the current globals and locals. >>> If only globals is given, locals defaults to it. >>> >> For example each time this line is interpreted I would like to use the >> new value of the state var which is a global var. How can I force >> state to be identified and used in this string. >> >> r_table = h5file.root.state_raw_records.neg_records >> >> r_table = eval("h5file.root.state_raw_records.neg_records") ?? >> r_table = h5file.root.eval("state")_raw_records.neg_records ?? eval is >> not a part of root >> >> dont think either of these is very logical? Any ideas? Possibly the >> parser mod? >> > > Got it! > > tmp = "h5file.root."+state+"_raw_records.pos_records" > r_table = eval(tmp) > > works great thanks for the help! > Yes, it works, but this is not a good place to use eval. Now that we see how you want to use it, we can find a *much* better way to do it. If you want to lookup an attribute of an object, but the attribute name is a string in a variable, then use getattr to do the lookup. If in interpret your code correctly: attrname = state + "_raw_records" obj = getattr(h5file.root, attrname) r_table = obj.pos_records These, of course, could be combined into a single (but not necessarily clearer) line. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a shell script from a python script
On Mon, 2006-07-17 at 16:59 -0700, spec wrote: > Thanks, actually there are no args, is there something even simpler? > > Thanks > Frank > > > Thomas Nelson wrote: > > If your script is foo.sh and takes args: > > import subprocess > > subprocess.call(["foo.sh","args"],shell=True) > > Should work fine. check out > > http://www.python.org/dev/doc/maint24/lib/module-subprocess.html > > > > Enjoy, > > THN > > > > spec wrote: > > > Hi all, I know nothing about Python. What I need to do is to get a > > > Python script to execute a local shell script. I do not need any > > > output. What would be th eeasiest way to accomplish this? > > > > > > Thanks! > > -- > http://mail.python.org/mailman/listinfo/python-list > Check out os.popen4 or the commands module. -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
dwelch91 wrote: > tac-tics wrote: > > > > I'd say the second one. Empty lists are not false. They are empty. Long > > live dedicated boolean data types. > > > Uh, no, empty lists are False in a boolean context: > > http://docs.python.org/lib/truth.html > > -Don Perhaps I should have specified it like this: >>> empty_list = [] >>> empty_list is not False True I'm well aware that both of these snippets does the same thing. I'm just spouting my opinion that lists and integers are not tests, and in an ideal world (Java??? X-) if statements support only boolean types. DISCLAIMER: I do not promote the use of Java. -- http://mail.python.org/mailman/listinfo/python-list
Python 2.5b2 Windows binaries
Hello, since I tested Python 2.5b2 on my applications, I have rebuilt some extension modules I needed. It wasn't a very simple or fast task, so I thought I'd share the result of the efforts: http://www.develer.com/oss/Py25Bins this page contains the Windows binaries (installers) for the following packages: - NumPy 0.98 - Numeric 24.2 - PyOpenGL 2.0.2.01 (with Numeric 24.2) - Pyrex 0.9.4.1 (with a Python 2.5 compatibility patch posted in its mailing list) I plan to update this page later as I build more installers (but don't hold your breath). Hope this helps everybody! -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
Re: New SourceForge project: Diet Python!!!
"The Eternal Squire" <[EMAIL PROTECTED]> writes: > Diet Python is a flavor of Python with allegro, multiarray, umath, > calldll, npstruct and curses builtin, all else nonessential to language > ripped out. Total size < 3MB, 1% of PSF Python. Diet Python helps keep > clients thin :) PSF Python is 300 MB?! -- http://mail.python.org/mailman/listinfo/python-list
question about what lamda does
Hey there, i have been learning python for the past few months, but i can seem to get what exactly a lamda is for. What would i use a lamda for that i could not or would not use a def for ? Is there a notable difference ? I only ask because i see it in code samples on the internet and in books. thanks for any clarity sk -- http://mail.python.org/mailman/listinfo/python-list
New SourceForge project: Diet Python!!!
Diet Python is a flavor of Python with allegro, multiarray, umath, calldll, npstruct and curses builtin, all else nonessential to language ripped out. Total size < 3MB, 1% of PSF Python. Diet Python helps keep clients thin :) You'll find it in http://sourceforge.net/projects/dietpython -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a shell script from a python script
Thanks, actually there are no args, is there something even simpler? Thanks Frank Thomas Nelson wrote: > If your script is foo.sh and takes args: > import subprocess > subprocess.call(["foo.sh","args"],shell=True) > Should work fine. check out > http://www.python.org/dev/doc/maint24/lib/module-subprocess.html > > Enjoy, > THN > > spec wrote: > > Hi all, I know nothing about Python. What I need to do is to get a > > Python script to execute a local shell script. I do not need any > > output. What would be th eeasiest way to accomplish this? > > > > Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to lock files (the easiest/best way)?
Carl J. Van Arsdall wrote: > [EMAIL PROTECTED] wrote: > > > > f = open("/path/to/data/directory/lockfile","r") > > try: > > fcntl.flock(f.fileno(),fcntl.LOCK_EX) > > ...access data freely here... > > finally: > > f.close() > > > > Closing the file should release the lock (unless you have a truly > > horrible operating system). > > > > > I also find that fcntl has problems with NFS (or at least, *I* had > problems using the python fcntl module and nfs - could be that horrible > operating system, but doing things like that over nfs can be tricky). Ah, that's a tough one. Apparently, you could lock files on NFS if both the client OS and NFS server are up to the task (i.e., sufficiently recent), but good luck getting that to fly. And, with NFS, even some of the seemingly foolproof methods like "lock directories" aren't necessarily going to work. Cross your fingers and hope you have a solid NFS server and well-behaved clients. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: run a string as code?
py_genetic wrote: > [EMAIL PROTECTED] wrote: > > py_genetic wrote: > > > How can you make python interpret a string (of py code) as code. For > > > example if you want a py program to modify itself as it runs. I know > > > this is an advantage of interpreted languages, how is this done in > > > python. Thanks. > > > > This might do it... > > > > >>> print eval.__doc__ > > eval(source[, globals[, locals]]) -> value > > > > Evaluate the source in the context of globals and locals. > > The source may be a string representing a Python expression > > or a code object as returned by compile(). > > The globals must be a dictionary and locals can be any mappping, > > defaulting to the current globals and locals. > > If only globals is given, locals defaults to it. > > For example each time this line is interpreted I would like to use the > new value of the state var which is a global var. How can I force > state to be identified and used in this string. > > r_table = h5file.root.state_raw_records.neg_records > > r_table = eval("h5file.root.state_raw_records.neg_records") ?? > r_table = h5file.root.eval("state")_raw_records.neg_records ?? eval is > not a part of root > > dont think either of these is very logical? Any ideas? Possibly the > parser mod? Got it! tmp = "h5file.root."+state+"_raw_records.pos_records" r_table = eval(tmp) works great thanks for the help! -- http://mail.python.org/mailman/listinfo/python-list
Re: run a string as code?
[EMAIL PROTECTED] wrote: > py_genetic wrote: > > How can you make python interpret a string (of py code) as code. For > > example if you want a py program to modify itself as it runs. I know > > this is an advantage of interpreted languages, how is this done in > > python. Thanks. > > This might do it... > > >>> print eval.__doc__ > eval(source[, globals[, locals]]) -> value > > Evaluate the source in the context of globals and locals. > The source may be a string representing a Python expression > or a code object as returned by compile(). > The globals must be a dictionary and locals can be any mappping, > defaulting to the current globals and locals. > If only globals is given, locals defaults to it. For example each time this line is interpreted I would like to use the new value of the state var which is a global var. How can I force state to be identified and used in this string. r_table = h5file.root.state_raw_records.neg_records r_table = eval("h5file.root.state_raw_records.neg_records") ?? r_table = h5file.root.eval("state")_raw_records.neg_records ?? eval is not a part of root dont think either of these is very logical? Any ideas? Possibly the parser mod? -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib (in thread) never returns
Kingsley: >it just sits in either the urlopen() or read() forever. [...] >I would have thought that some urllib-internal timeout >would fix this?! Yes, but you'll need to enable it. See socket.setdefaulttimeout() : http://docs.python.org/lib/module-socket.html -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: use var to form name of object
Marc 'BlackJack' Rintsch wrote: > In <[EMAIL PROTECTED]>, gel wrote: > > > Yeah I am still getting my head around things... not exactly sure what > > you where saying about the globals, but this works > > > > > > global k > > k = 5 > > class foo: > > > > def wow(self, n): > > global k > > k += n > > return k > > > > > > f=foo() > > f.wow(55) > > The first ``global`` does nothing. ``global`` at module level makes no > sense. And the snippet could be easily written without assigning to > global names from within a function/method: > > k = 5 > class Foo: > def wow(self, n): > return k + n > > f = Foo() > k = f.wow(55) > > Ciao, > Marc 'BlackJack' Rintsch Ah yes, thanks for that Marc -- http://mail.python.org/mailman/listinfo/python-list
Re: run a string as code?
py_genetic wrote: > How can you make python interpret a string (of py code) as code. For > example if you want a py program to modify itself as it runs. I know > this is an advantage of interpreted languages, how is this done in > python. Thanks. This might do it... >>> print eval.__doc__ eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mappping, defaulting to the current globals and locals. If only globals is given, locals defaults to it. -- http://mail.python.org/mailman/listinfo/python-list
run a string as code?
How can you make python interpret a string (of py code) as code. For example if you want a py program to modify itself as it runs. I know this is an advantage of interpreted languages, how is this done in python. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: General Hash Functions In Python
On 17/07/2006 10:13 PM, Arash Partow wrote: > John Machin wrote: >> Who is likely to bother? In timbot we trust. Have you read the comments >> at the start of Objects/dictobject.c? >> > No I haven't probably wont be anytime soon, Perhaps you should, if you profess an interest in hashed lookup -- it gives some interesting commentary on the second aspect: collision handling. What matters is the *total* time to return an answer. > as far as time, well > people interested, as is how started my original port, would be more > than willing to try/assess the routines for sets of strings that they > wish to hash etc. > this site may help explain plus has some code > snippets that may help you understand what I mean. > > http://www.partow.net/programming/hashfunctions/index.html That JSHAsh allegedly written by "Justin Sobel": by coincidence, there's a Melbourne academic named Justin Zobel who has done something amazingly similar: http://goanna.cs.rmit.edu.au/~hugh/zhw-ipl.html Searching for "Justin Sobel" did lead me to a Russian website which apart from repeating your typo/reado/whatevero did propose (and test) some more hash functions. http://vak.ru/doku.php/proj/hash/efficiency-en In particular look at the "rot13" function which was right up near the front as far as number of collisions goes, and which would appear (my guess based on reading the source) to be very fast (with the right compiler (e.g. gcc 4)). > > >> A few more questions: >> >> Have you tested that these functions produce the same output (apart from >> the 31-bit thing) as the originals that you worked from? The reason for >> asking is that Python unlike C doesn't lose any bits in the << >> operation; if this is followed by a >> you may be shifting some unwanted >> 1-bits back in again. >> > > Some of them do others don't (not really important unless you are > trying to be compatible with other implementations which this is > not), I would have thought it important especially in the case of well-known functions whose properties have been discussed in the literature that you should not publish a version that gives a different answer, without noting that fact prominently. > I am aware of python not truncating/wrapping of values under > various operations, I believe its a nice little side effect from > python which gives more bits to play with as long as you don't > truncate them as I have. > > >> Talking about not losing bits: For your 36-byte example input, the >> SDBMHash (with its << 16) is up to about 566 bits before you truncate it >> to 31. A little over the top, perhaps. Maybe not the fastest way of >> doing it. >> > Possibly, do you have a better solution I'm very keen to learn... You can't avoid using Python longs if you want to simulate unsigned 32-bit arithmetic. However judicious truncation can be used to stop the longs becoming longer and slower. General rules: 1. Avoid exceeding 32 bits where possible. E.g. instead of hash <<= 8 do hash = (hash & 0xFF) << 8 2. Where unavoidable (e.g. hash *= constant), use hash &= 0x to chop back to 32 bits, once per iteration. > > >> What is the purpose of the calls to long() in PJWHash? >> > trying to cast to long, looking at it now its rather superfluous. > > >> And the $64K question: What is the quintessential difference between >> PJWHash and ELFHash? >> > Nothing, elf is essentially pjw, its just optimised for 32-bit systems > in that the calculation for th's etc are static where has pjw > required sizeof to calc the th's You've found a C compiler where sizeof(unsigned int) is not static i.e. calculated by the compiler at compile time??? > which i couldn't find a way of doing, > so i fudged it in the hope that maybe sometime in the future a work > around of sorts could be developed. Google is a wonderful thing: http://users.physik.tu-muenchen.de/gammel/matpack/html/LibDoc/Strings/strings.html """ Thanks to Josh Bloch ([EMAIL PROTECTED]) who also informed me about another fault that is found in Aho, Sethi and Ullman's book: The line with h ^= (g >> 28) now replaces the original h ^= (g >> 24). According to a correspondence of Josh Bloch with Ravi Sethi this correction will be made in the next edition of the book. Including these two changes this hash function is now comparable to Vo's, Torek's and WAIS's hash functions. """ (1) Whoops! (2) Vo? Torek? WAIS? Could these be possible additions to your website? http://www.math.columbia.edu/~bayer/annote/root/root.html """ Peter J. Weinberger hash function; see e.g. 21st Century Compilers, by Alfred V. Aho, Ravi Sethi, Monica Lam, Jeffrey D. Ullman, ISBN 0321131436. Hash unsigned X into H, using the temporary variable G. G and H are unsigned variables; X may be an expression. G is nonzero e.g. 92% of time, so a conditional expression would be slower. As noted by Josh Bloch, 28 is the correct replacement for the frequent misprint 24. #define HASH(G,H,X) ( H <<= 4, H += (X),
Re: Tkinter StringVar mystery
On Mon, 2006-07-17 at 15:00 -0600, Bob Greschke wrote: > First off I have this class (thanks to whoever came up with this way back > when): > > ## > # BEGIN: class Command > # LIB:Command():2006.110 > #Pass arguments to functions from button presses and menu selections, > #bind's. Nice! > #In your declaration: > #...command = Command(func, args,...) > class Command: > def __init__(self, func, *args, **kw): > self.func = func > self.args = args > self.kw = kw > def __call__(self, *args, **kw): > args = self.args+args > kw.update(self.kw) > apply(self.func, args, kw) > # END: class Command > > > Then in the setup part of an entry form I have: > > # CHBCBarcodeLastVar is the variable for an Entry() field > Button(SubFrame, text = "Print Barcode", \ > command = Command(test, "other", CHBCBarcodeLastVar.get(), \ > "CHBC")).pack(side = LEFT) > > > Then this is a/the test function: > > def test(What, BC, Where, e = None): > # Does print the correct value > print CHBCBarcodeLastVar.get() > # Does change the field on the form > CHBCBarcodeLastVar.set("5") > # BC is "" > print ":"+What+":", ":"+BC+":", ":"+Where+":" > return > > Everything works as it should, except when the Button is clicked BC is an > empty str in test(). How come? (I really have NO clue how that Command > class works, but I use it like crazy. Is it the problem?) The problem is when you are creating the "Print Barcode" button. Think about what the value of CHBCBarcodeLastVar.get() is when you create the button ? I bet it is an empty string. This value will always be passed to test, regardless of how it changes in the future. What you probably want is to pass the StringVar reference and then do a get in test. Eg: # CHBCBarcodeLastVar is the variable for an Entry() field Button(SubFrame, text = "Print Barcode", \ command = Command(test, "other", CHBCBarcodeLastVar, \ "CHBC")).pack(side = LEFT) def test(What, BC, Where, e = None): print ":"+What+":", ":"+BC.get()":", ":"+Where+":" return Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
Bob Greschke wrote: > <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > PTY wrote: > >> Which is better? > >> > >> lst = [1,2,3,4,5] > >> > >> while lst: > >> lst.pop() > >> > >> OR > >> > >> while len(lst) > 0: > >> lst.pop() > > > > A dozen posts, but nobody has posted the right > > answer yet, so I will :-) > > > > It doesn't matter -- use whichever you prefer (*) > > This is an angels on the head of a pin issue. > > > > (*) -- If your code is part of an existing body of > > code that uses one or the other style consistently, > > then you should do the same. > > > > I'd go even one step further. Turn it into English (or your favorite > non-computer language): > > 1. While list, pop. > > 2. While the length of the list is greater than 0, pop. > > Which one makes more sense? Guess which one I like. CPU cycles be damned. > :) > > Bob It looks like there are two crowds, terse and verbose. I thought terse is perl style and verbose is python style. BTW, lst = [] was not what I was interested in :-) I was asking whether it was better style to use len() or not. -- http://mail.python.org/mailman/listinfo/python-list
Re: solving equation system
TG wrote: > Hi there. > > Anyone knows how to use numpy / scipy in order to solve this ? > > * A is an array of shape (n,) > * X is a positive float number > * B is an array of shape (n,) > * O is an array of shape (n,) containing only zeros. > > A.X - B = O > min(X) > > thanks. Looks like an incorrectly specified degenerate linear least squares problem. The function numpy.linalg.linear_least_squares might be able to do what you want. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: How to lock files (the easiest/best way)?
[EMAIL PROTECTED] wrote: > >> ith a quick look. >> > > > f = open("/path/to/data/directory/lockfile","r") > try: > fcntl.flock(f.fileno(),fcntl.LOCK_EX) > ...access data freely here... > finally: > f.close() > > Closing the file should release the lock (unless you have a truly > horrible operating system). > > I also find that fcntl has problems with NFS (or at least, *I* had problems using the python fcntl module and nfs - could be that horrible operating system, but doing things like that over nfs can be tricky). -carl -- Carl J. Van Arsdall [EMAIL PROTECTED] Build and Release MontaVista Software -- http://mail.python.org/mailman/listinfo/python-list
Re: Cool Python Ebooks Site
[EMAIL PROTECTED] wrote: > If you think a simple script is going to fool adsense then you trully > need to read some books. If it happens a lot, Google will consider it an attempt of click fraud IMO. Doesn't matter if it's really high tech. I have heard too many stories from people who got kicked out of AdSense to even consider Google doing really smart stuff. Finally calling wget a simple script means that I have read more books then you, *and* can teach you from the ones you suggest I should read ;-) -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode html
> Hi, I've found lots of material on the net about unicode html > conversions, but still i'm having many problems converting unicode > characters to html entities. Is there any available function to solve > this issue? > As an example I would like to do this kind of conversion: > \uc3B4 => ô '%d;' % ord(u'\u0430') or '%x;' % ord(u'\u0430') > for all available html entities. -- damjan -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode html
Sybren Stuvel wrote: > Jim enlightened us with: > > Ah, but I cannot change it. It is not my machine and the folks who > > own the machine perceive that the charset line that they use is the > > right one for them. > > Well, _you_ are the one providing the content, aren't you? ? This site has many people operating off of it (it is sourceforge-like) and the operators (who are volunteers) are kind enough to let us use it in the first place. I presume that they think the charset line that they use is the one that most people want. Probably if they changed it then someone else would complain. > Sounds like they either don't know what they are talking about, or use > incompetent software. With Apache, it's very easy to give every > directory its own default character encoding header. I am operating under constraints. Asking the operators of the site has led to the understanding that I must work with the charset parameter that I have. That is, I have an environment in which I must work, and whether you or I think the people providing the service should do it differently doesn't matter. I replied originally because I thought I could give an example of HTML entities providing a way that I can solve the problem that is entirely under my control. > > Unfortunately, the tag idea also does not fly: see > > http://www.w3.org/TR/html4/charset.html in section 5.2.2 where it > > states that in a contest the charset parameter wins. > > I assume that with "the charset parameter" you mean "the HTTP header", > as the tag also has a "charset parameter". AIUI "charset parameter" is the language of the HTML standard that I referred to. For the meta tag, I at least would use "charset attribute". > > My only point is that things are complicated > > Call me thick, but from my point of view they aren't. ;-) Jim -- http://mail.python.org/mailman/listinfo/python-list
Re: solving equation system
On 2006-07-17, TG <[EMAIL PROTECTED]> wrote: > > Ben C wrote: >> On 2006-07-17, TG <[EMAIL PROTECTED]> wrote: >> > Hi there. >> > >> > Anyone knows how to use numpy / scipy in order to solve this ? >> > >> > * A is an array of shape (n,) >> > * X is a positive float number >> > * B is an array of shape (n,) >> > * O is an array of shape (n,) containing only zeros. >> > >> > A.X - B = O >> > min(X) >> >> Are we solving for A, B or X? And what do you mean by min(X)? >> >> If we're solving for X there will be many combinations of A and B for >> which there is no solution. > > Sorry for the poor explanation. I'm trying to put it clear now. > > i've got A and B. I'm looking for X. I made a mistake in my equation >:-/ > > It's more like : > > A.X - B >= O How about this: from random import * def solve(A, B): return reduce(max, (float(b) / a for a, b in zip(A, B))) def test(): A = [random() for i in range(4)] B = [random() for i in range(4)] x = solve(A, B) for a, b in zip(A, B): print a, b, a * x - b test() This only works if all elements of both A and B are positive. > Well, maybe it will be much more simple if I explain the underlying > problem : > > I have an array of N dimensions (generally 2). > - A first calculation gives me a set of integer coordinates inside this > array, which I will call the point W. Is this an array of points, or an array of values, that contains only one point? > - After several other calculations, I've got a set of coordinates in > this N dimensional space that are floating values, and not bound to the > limits of my original N-array. This is the point L. > > What I want to do is to translate the point L along the vector LW Do you mean the vector L - W? (LW is a scalar, assuming dot product). > in order to get a point L' which coordinates are inside the original > N-dimensional array. Then it will be easy to get the closest integer > coordinates from L'. > I'm not sure this is clear ... pretty hard to talk about maths in > english. Not very clear to me I'm afraid! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to lock files (the easiest/best way)?
Elmo Mäntynen wrote: > Is there something better than using fnctl? It seems a bit intimidating > with a quick look. Although fcntl is pretty opaque, it's quite easy to use if all you want is a simple exclusive lock for all your data. The thing to keep in mind is, you don't have to lock every file you want exclusive access to. In fact, doing that provides no added security (since it's an advisory lock and programs are free to ignore it). For simple cases, locking one file and only accessing your data if you have that lock works, and is very simple. What I usually do is touch an empty file (say, "lockfile") in my data directory. I don't access any files in that directory unless I have a lock to the lockfile. This is done simply with (untested): import fcntl f = open("/path/to/data/directory/lockfile","r") try: fcntl.flock(f.fileno(),fcntl.LOCK_EX) ...access data freely here... finally: f.close() Closing the file should release the lock (unless you have a truly horrible operating system). Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Marshall <[EMAIL PROTECTED]> wrote: > Yes, these *performance* issues make assignment prohibitive for > real-world use, at least if we are talking about data management > in the large. This is not the same thing as saying the resulting > language is a toy language, though; its semantics are quite > interesting and possibly a better choice for *defining* the semantics > of the imperative operations than directly modelling the imperative > operations. (Or maybe not.) In any event, it's worth thinking about, > even if performance considerations make it not worth implementing. My "toy language" comment was directed at a language that I mistakenly thought you were proposing, but that you really weren't. You can ignore it, and all the corresponding comments about assignment being less powerful, etc. I was apparently not skilled at communication when I tried to say that in the last message. It is, perhaps, worth thinking about. My assertion here (which I think I've backed up, but there's been enough confusion that I'm not surprised if it was missed) is that the underlying reasons that performance might be poor for this language are a superset of the performance problems caused by aliasing. Hence, when discussing the problems caused by aliasing for the performance of language implementations (which I believe was at some point the discussion here), this isn't a particularly useful example. It does, though, have the nice property of hiding the aliasing from the semantic model. That is interesting and worth considering, but is a different conversation; and I don't know how to start it. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > PTY wrote: >> Which is better? >> >> lst = [1,2,3,4,5] >> >> while lst: >> lst.pop() >> >> OR >> >> while len(lst) > 0: >> lst.pop() > > A dozen posts, but nobody has posted the right > answer yet, so I will :-) > > It doesn't matter -- use whichever you prefer (*) > This is an angels on the head of a pin issue. > > (*) -- If your code is part of an existing body of > code that uses one or the other style consistently, > then you should do the same. > I'd go even one step further. Turn it into English (or your favorite non-computer language): 1. While list, pop. 2. While the length of the list is greater than 0, pop. Which one makes more sense? Guess which one I like. CPU cycles be damned. :) Bob -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
Donn Cave wrote: > Tac-tics is right, an empty list is not False. But that's not what he said. He said it was "not false." That's wrong. It's false. It's just not False. -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The meaning of life is that it stops. -- Franz Kafka -- http://mail.python.org/mailman/listinfo/python-list
Re: Help!
> I have a problem with python. When I try to connect to > postgresql. It appears a message. > > ]$ python > > >>> from pg import DB > Traceback (most recent call last): > >File "", line 1, sn? > > ImportError: No module name pg > You need to install the pygresql module in order to use anything related to postgresql from python. You can get it from here: http://www.pygresql.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
In article <[EMAIL PROTECTED]>, Steve Holden <[EMAIL PROTECTED]> wrote: > tac-tics wrote: ... >> I'd say the second one. Empty lists are not false. They are empty. >> Long live dedicated boolean data types. > Take them off to where they belong! Tac-tics is right, an empty list is not False. Anyway, just for some variety, I think (2) is preferrable to (1), as is the following while 1: try: lst.pop() except IndexError: break Rather than blindly apply familiar patterns to our work, I think everyone would agree that coding style in matters like this should follow the underlying point of the code. In this case, the body of the test refers implicitly to the length of the list, since .pop() -> (list[a], list[:a]) where a is (len(list) - 1) It's therefore quite appropriate for the test to be length. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Free Advertisement!
www.get-free-advertisement.com www.have-bad-credit.com -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Chris Smith wrote: > Marshall <[EMAIL PROTECTED]> wrote: > > > If the relations are to > > > be considered opaque, then there's clearly no aliasing going on. > > > > Not certain I understand, but I think I agree. > > My condition, though, was that relations be opaque. Since you will be > violating that condition further on down, I just felt that it's useful > to point that out here. > > > No, such a language is entirely useful, since relational assignment > > is *more* expressive than insert/update/delete. > > Assignment is more powerful *as* assignment. However, it is less > powerful when the task at hand is deriving new relations from old ones. At the implementation level, it makes some things harder, however as a logical model, it is more powerful. While this is very much a real world issue, it is worth noting that it is a performance issue *merely* and not a semantic issue. > Assignment provides absolutely no tools for doing that. I thought you > were trying to remove those tools from the language entirely in order to > remove the corresponding aliasing problems. I guess I was wrong, since > you make it clear below that you intend to keep at least basic set > operations on relations in your hypothetical language. > > > Consider: > > > > i := i + 1; > > > > Note that the new value of i didn't just appear out of thin air; it was > > in fact based on the previous value of i. > > Right. That's exactly the kind of thing I thought you were trying to > avoid. I was under the impression tat Joachim, for example, did not consider "i+1" as an alias for i. > > So we can define insert, update and delete in terms of relational > > assignment, relational subtraction, and relational union. Type > > checking details omitted. > > Then the problem is in the step where you assign the new relation to the > old relational variable. You need to check that the new relation > conforms to the invariants that are expressed on that relational > variable. If you model this as assignment of relations (or relation > values... I'm unclear on the terminology at this point) then naively > this requires scanning through an entire set of relations in the > constraint, to verify that the invariant holds. You've may have avoided > "aliasing" in any conventional sense of the word by stretching the word > itself beyond breaking... but you've only done it by proactively > accepting its negative consequences. > > It remains non-trivial to scan through a 2 GB database table to verify > that some attribute of every tuple matches some attribute of another > table, even if you call the entire thing one relational variable. The > implementation, of course, isn't at all going to make a copy of the > entire (possibly several GB) relation and rewrite it all every time it > makes a change, and it isn't going to give up and rescan all possible > invariants every time every change is made. In other words, you've > risen to a layer of abstraction where the aliasing problem does not > exist. The implementation is still going to deal with the aliasing > problem, which will resurface once you pass over to the other side of > the abstraction boundary. Yes, these *performance* issues make assignment prohibitive for real-world use, at least if we are talking about data management in the large. This is not the same thing as saying the resulting language is a toy language, though; its semantics are quite interesting and possibly a better choice for *defining* the semantics of the imperative operations than directly modelling the imperative operations. (Or maybe not.) In any event, it's worth thinking about, even if performance considerations make it not worth implementing. Marshall -- http://mail.python.org/mailman/listinfo/python-list
Tkinter StringVar mystery
First off I have this class (thanks to whoever came up with this way back when): ## # BEGIN: class Command # LIB:Command():2006.110 #Pass arguments to functions from button presses and menu selections, #bind's. Nice! #In your declaration: #...command = Command(func, args,...) class Command: def __init__(self, func, *args, **kw): self.func = func self.args = args self.kw = kw def __call__(self, *args, **kw): args = self.args+args kw.update(self.kw) apply(self.func, args, kw) # END: class Command Then in the setup part of an entry form I have: # CHBCBarcodeLastVar is the variable for an Entry() field Button(SubFrame, text = "Print Barcode", \ command = Command(test, "other", CHBCBarcodeLastVar.get(), \ "CHBC")).pack(side = LEFT) Then this is a/the test function: def test(What, BC, Where, e = None): # Does print the correct value print CHBCBarcodeLastVar.get() # Does change the field on the form CHBCBarcodeLastVar.set("5") # BC is "" print ":"+What+":", ":"+BC+":", ":"+Where+":" return Everything works as it should, except when the Button is clicked BC is an empty str in test(). How come? (I really have NO clue how that Command class works, but I use it like crazy. Is it the problem?) Thanks! Bob -- http://mail.python.org/mailman/listinfo/python-list
Re: Track keyboard and mouse usage
dfaber schrieb: > So, how would I access /dev/input/ devices? > Can I just 'cat' them or read in those files? Yes, just read them. Which is what cat does, btw. If you cat your keyboard, you should see garbage appearing in the terminal when you type any key. Same is true for the mouse. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Track keyboard and mouse usage
So, how would I access /dev/input/ devices? Can I just 'cat' them or read in those files? Diez B. Roggisch wrote: > [EMAIL PROTECTED] schrieb: > > Diez> You could use the /dev/input/event* devices. > > > > On the only Linux system I have available (Mojam's CentOS-based web server), > > /dev/input/* are readable only by root. That doesn't seem like it would be > > very useful to tools like watch unless they were to run suid to root > > (creating other problems). > > You don't need to give it root access. A simple rule for the udev that > looks like this: > > KERNEL=="event[0-9]*",NAME="input/%k", MODE="0444" > > > will make the devices world readable. While I haven't thought about any > security implications that might have (and am not especially > knowledgeable in such things to be honest), I'm convinced it is way less > likely to introduce any exploitable holes than suid root would. > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Help!
Hi, my name’s felipe I have a problem with python. When I try to connect to postgresql. It appears a message. ]$ python >>> from pg import DB Traceback (most recent call last): File "", line 1, sn? ImportError: No module name pg Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a shell script from a python script
If your script is foo.sh and takes args: import subprocess subprocess.call(["foo.sh","args"],shell=True) Should work fine. check out http://www.python.org/dev/doc/maint24/lib/module-subprocess.html Enjoy, THN spec wrote: > Hi all, I know nothing about Python. What I need to do is to get a > Python script to execute a local shell script. I do not need any > output. What would be th eeasiest way to accomplish this? > > Thanks! -- http://mail.python.org/mailman/listinfo/python-list
XMLRPC Solution Code
[EMAIL PROTECTED] wrote: > Mind posting it for us lesser beings? ;) Not at all. I have yet to test it on networked computers, but it works fine when I run both scripts on my machine. The hard part now is getting the server code to run as a Windows service- argh!!! I can get it installed and started using modified code from: http://www.schooltool.org/products/schooltool-calendar/documentation/how-to/running-as-a-windows-service/schooltool-service.py/view but for some reason when the server is a service the client refuses to connect properly! Grrr... anybody know why? Here is the code for the server, the machine that will execute the commands: import SimpleXMLRPCServer, os server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000)) server.register_function(lambda command: os.popen4(command)[1].read(), "execute") server.serve_forever() And here's the code for the client, the computer that will tell the server what command to execute: import xmlrpclib server = xmlrpclib.Server("http://"; + raw_input("Enter the IP address of the server: ") + ":8000") output = server.execute(raw_input("Enter a command for the server to execute: ")) print output -- http://mail.python.org/mailman/listinfo/python-list
Re: Track keyboard and mouse usage
So, how would I access /dev/input/ devices? Can I just 'cat' them or read in those files? Diez B. Roggisch wrote: > [EMAIL PROTECTED] schrieb: > > Diez> You could use the /dev/input/event* devices. > > > > On the only Linux system I have available (Mojam's CentOS-based web server), > > /dev/input/* are readable only by root. That doesn't seem like it would be > > very useful to tools like watch unless they were to run suid to root > > (creating other problems). > > You don't need to give it root access. A simple rule for the udev that > looks like this: > > KERNEL=="event[0-9]*",NAME="input/%k", MODE="0444" > > > will make the devices world readable. While I haven't thought about any > security implications that might have (and am not especially > knowledgeable in such things to be honest), I'm convinced it is way less > likely to introduce any exploitable holes than suid root would. > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
PTY wrote: > Which is better? > > lst = [1,2,3,4,5] > > while lst: > lst.pop() > > OR > > while len(lst) > 0: > lst.pop() A dozen posts, but nobody has posted the right answer yet, so I will :-) It doesn't matter -- use whichever you prefer (*) This is an angels on the head of a pin issue. (*) -- If your code is part of an existing body of code that uses one or the other style consistently, then you should do the same. -- http://mail.python.org/mailman/listinfo/python-list
Python Developer required for a 6 months contract
My client based in the South West is looking for a Python Developer to join an existing project team for a 6-month contract. Suitable candidates will have commercial experience programming with Python and knowledge of Software Design Architecture. Ideally you will have Knowledge of QT, GTK, KDE or similar toolkits/technologies . Please do not hesitate to call me for further information.RegardsRakesh 01727 752000 [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Track keyboard and mouse usage
Hi! Look PyHook ( http://cheeseshop.python.org/pypi/pyHook/1.4 ) Ooooh!!! Sorry! It's for Windows... -- MCI -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for Embedded Systems?
J> Is there a Python packaging that is specifically for J> embedded systems? ie, very small and configurable so the J> user gets to select what modules to install? J> For Linux-based embedded systems in particular? J> I'm thinking of running it on the Linksys's Linux-based open J> source router WRT54G. It has 4MB flash and 16MB RAM. I think J> another model has 16MB flash. Any possibilities of running J> Python on these systems? You can run Python on the NSLU2 (Slug) http://www.nslu2-linux.org/ sw packages: http://www.nslu2-linux.org/wiki/Unslung/Packages the best (IMHO) firmware: http://www.nslu2-linux.org/wiki/DebianSlug/HomePage -- http://mail.python.org/mailman/listinfo/python-list
Re: Track keyboard and mouse usage
[EMAIL PROTECTED] schrieb: > Diez> You could use the /dev/input/event* devices. > > On the only Linux system I have available (Mojam's CentOS-based web server), > /dev/input/* are readable only by root. That doesn't seem like it would be > very useful to tools like watch unless they were to run suid to root > (creating other problems). You don't need to give it root access. A simple rule for the udev that looks like this: KERNEL=="event[0-9]*", NAME="input/%k", MODE="0444" will make the devices world readable. While I haven't thought about any security implications that might have (and am not especially knowledgeable in such things to be honest), I'm convinced it is way less likely to introduce any exploitable holes than suid root would. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with sub-classing
Bernard Lebel wrote: > Okay, that make sense. > > Now the question is: regarding the re-binding behavior, is this > actually problematic? By that I mean that is it good coding practice > to avoid this issue altogether as much as possible, or is it okay to > live with it if you use the __init__ argument trick you have shown? I suggested the "argument trick" for diagnosis only. One /good/ coding practice is to choose descriptive names for (toplevel) objects. Another is to avoid from module import * style imports which tend to be the most common source of name clashes. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error? [correction]
Darren New wrote: > Now, if the "insert line into inputs" actually unset "line", then yes, > you're right, Hermes would complain about this. Oh, I see. You translated from Hermes into Java, and Java doesn't have the "insert into" statement. Indeed, the line you commented out is *exactly* what's important for analysis, as it unsets line. Had it been insert copy of line into inputs then you would not have gotten any complaint from Hermes, as it would not have unset line there. In this case, it's equivalent to if (!is_line) line = getString(); if (!is_line) use line for something... except the second test is at the top of the loop instead of the bottom. -- Darren New / San Diego, CA, USA (PST) This octopus isn't tasty. Too many tentacles, not enough chops. -- http://mail.python.org/mailman/listinfo/python-list
Re: Track keyboard and mouse usage
Diez> You could use the /dev/input/event* devices. On the only Linux system I have available (Mojam's CentOS-based web server), /dev/input/* are readable only by root. That doesn't seem like it would be very useful to tools like watch unless they were to run suid to root (creating other problems). As the author of watch, I'm more than happy to incorporate "drivers" from other people into the code, however, I have very little access to Linux these days (and none on the desktop) and no Windows access. Skip -- http://mail.python.org/mailman/listinfo/python-list
execute a shell script from a python script
Hi all, I know nothing about Python. What I need to do is to get a Python script to execute a local shell script. I do not need any output. What would be th eeasiest way to accomplish this? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on RedHat AS 2.1?
All the stuff I've found personally are security patches for python 1.5.2... which seems to be baked into the OS.I don't choose to use this OS... it is mandated by our IT dept. I have no complaints other than this...Is there nobody in pythonland who has installed python 2.2 or higher on this OS?Anybody?JeremyFrom: Fredrik Lundh <[EMAIL PROTECTED]>To: python-list@python.orgDate: Sat, 15 Jul 2006 10:20:21 +0200Subject: Re: Python on RedHat AS 2.1? Jeremy Winters wrote:> Installable package?> > Any ideas?is RedHat no longer providing pre-built packages for their distributions ? Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1¢/min.-- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
Peter Otten wrote: > Steve Holden wrote: > > > I'll bet you still write > > > > if a>3 == True: > > > > don't you ;-) > > I'll second that. > > if (a>3) == True: > > is the correct way :-) > > Peter No, to be consistent you'll have to write if ((a>3) == True) == True: Oops, I mean, if (((a>3) == True) == True) == True: Umm, never mind. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to know if socket is still connected
ok, yeah, thats in my book. thanks, and no, it isn't enabled. thanks again for everything -sk Grant Edwards wrote: > On 2006-07-17, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > >> If the server _application_ crashes or exits, then the OS will > >> close the socket and recv() will return "". If somebody powers > >> down the server without warning, or if the server OS crashes, > >> or if the Ethernet cable between the Internet and the server is > >> cut, then the socket will not be closed, and recv() will wait > >> forever[1]. > > > > Ok, yes all of the above is what i mean. Actually I am not too > > concerned about a server os crash, or the cable being cut. But I have > > had them close the connection on me, after which i just reconnect > > (whenever i discover that its happened) > > > >>[1] Unless you've enabled the TCP Keepalive feature, in which > >>case the socket will timeout in a couple hours and recv() > >>will return "". > > > > if this is something that must be enabled, or is not enabled by > > default, then it is not enabled. > > On all OSes with which I'm familiar it's disabled by default. > You use a socket object's setsockopt method to enable it: > > s.setsockopt(socket.SOL_TCP,socket.SO_KEEPALIVE,True) > > -- > Grant Edwards grante Yow! Wow! Look!! A stray > at meatball!! Let's interview >visi.comit! -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error? [correction]
David Hopwood wrote: > > public class LoopInitTest { > public static String getString() { return "foo"; } > > public static void main(String[] args) { > String line = getString(); > boolean is_last = false; > > while (!is_last) { > if (line.charAt(0) == 'q') { > is_last = true; > } > > // insert line into inputs (not important for analysis) > > if (!is_last) { > line = getString(); > } > } > } > } > > which compiles without error, because is_last is definitely initialized. At what point do you think is_last or line would seem to not be initialized? They're both set at the start of the function, and (given that it's Java) nothing can unset them. At the start of the while loop, it's initialized. At the end of the while loop, it's initialized. So the merge point of the while loop has it marked as initialized. Now, if the "insert line into inputs" actually unset "line", then yes, you're right, Hermes would complain about this. Alternately, if you say if (x) v = 1; if (x) v += 1; then Hermes would complain when it wouldn't need to. However, that's more a limitation of the typestate checking algorithms than the concept itself; that is to say, clearly the typestate checker could be made sufficiently intelligent to track most simple versions of this problem and not complain, by carrying around conditionals in the typestate description. -- Darren New / San Diego, CA, USA (PST) This octopus isn't tasty. Too many tentacles, not enough chops. -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode html
Sybren Stuvel wrote: > Jim enlightened us with: > > For example, I am programming a script that makes html pages, but I > > do not have the ability to change the "Content-Type .. charset=.." > > line that is sent preceeding those pages. > > "line"? Are you talking about the HTTP header? If it is wrong, it > should be corrected. If you are in control of the content, you should > also be control of the Content-Type header. Otherwise, use a > tag that describes the content. Ah, but I cannot change it. It is not my machine and the folks who own the machine perceive that the charset line that they use is the right one for them. (Many people ship pages off this machine.) Unfortunately, the tag idea also does not fly: see http://www.w3.org/TR/html4/charset.html in section 5.2.2 where it states that in a contest the charset parameter wins. My only point is that things are complicated and that there are times when HTML entities are the answer (or anyway, an answer). Jim -- http://mail.python.org/mailman/listinfo/python-list