pycap piano roll drum machine system 1.0
Pycap piano/drum machine system is at 1.0. To install install the demo and then copy the latest file over it.. in this release fixed the save file. text to describe the colums is loaded from a text file that can be defined befour use. buttons are bigger. help file to do: cosmetic stuff like change the save togle button to a button link the help file to the main app text colour glitch http://dexrowem.blogspot.com/search?q=pycap+drum+machine -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
[ANN] OPy Meeting - April 23, 2009 at Noon in One Partner's Place
The next OPy meeting will be held in the Alpha Room in One Partner's Place (near the National Weather Center) on April 23, 2009 at noon. Ryan May will be giving an introduction to Python 3. We will be having a drawing for two prizes donated by the Pearson Education User Group Program. Since this meeting is at lunch time, we will have food and drinks. http://opy.sixquickrun.com/ -- Kevin D. Smith -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Can I import from a directory that starts with a dot (.) ?
On Apr 13, 5:51 pm, Matthew Wilson m...@tplus1.com wrote: I want to have .foo directory that contains some python code. I can't figure out how to import code from that .foo directory. Is this even possible? TIA Matt Yes, but it's not a particularly recommended thing to do as it is CRAZY. You can get to it from the imp module's functions: import imp # Loads a file/dir named .foo or .foo.py on the sys.path, giving it the overloaded name of foo in sys.modules imp.load_module('foo', *imp.find_module('.foo')) # Grab the module into the local namespace, it's been imported in the system but not here yet import foo Seriously. Crazy. It looks strange and hard because it is in no way a use case that anyone expects you to have. But it's possible. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I import from a directory that starts with a dot (.) ?
Matthew Wilson wrote: I want to have .foo directory that contains some python code. I can't figure out how to import code from that .foo directory. Is this even possible? TIA Matt -- http://mail.python.org/mailman/listinfo/python-list Python starts up with a list of directories to search when importing. You can append your directory to that list, and then import as you wish. import sys sys.path.append('/...path-to.../.foo') import someModule # would find and import .foo/someModule.py You may also enjoy printing the contents of sys.path to see the list of directories Python starts with. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: zProblem
En Mon, 13 Apr 2009 15:13:53 -0300, norseman norse...@hughes.net escribió: Gabriel Genellina wrote: Now, if ... summarizes your problem, I think you should use the place geometry manager, not grid (nor pack). The Tkinter documentation [1] is rather short but the Tcl docs [2] have more info. [1] http://effbot.org/tkinterbook/place.htm [2] http://www.tcl.tk/man/tcl8.4/TkCmd/place.htm Thanks for the links but I'm having the same problems as before. [...] I can't visualize that working properly in my current need. The mockup board is to be size inflexible and real estate jammed with specifically sized replaceable sections. The question is how to make it happen. Below there is an attempt to reproduce the layout you describe in the PDF: from Tkinter import * root = Tk() pane = Frame(root, width=400, height=300) pane.pack(fill=both, expand=1) w1 = Label(pane, text=1, bg=white) w1.place(relwidth=0.1, relheight=0.5) w2 = Label(pane, text=2, bg=yellow) w2.place(relwidth=0.25, relheight=0.3, relx=0.1) w3 = Label(pane, text=3, bg=red) w3.place(relwidth=0.2, relheight=0.2, relx=0.1, rely=0.3) w4 = Label(pane, text=4, bg=cyan) w4.place(relwidth=0.05, relheight=0.2, relx=0.3, rely=0.3) w5 = Label(pane, text=5, bg=blue) w5.place(relwidth=0.35, relheight=0.5, rely=0.5) w6 = Label(pane, text=X, bg=gray) w6.place(relwidth=0.25, relheight=1, relx=0.35) w7 = Label(pane, text='Rest of master control parceled as whatever', bg=white) w7.place(relwidth=0.40, relheight=1, relx=0.60) root.mainloop() The place geometry manager is the most powerful (least restricted) of all three standard managers; for each widget, you specify its size and position (in relative or absolute terms) without further restrictions. In this case, the same thing could be done using pack (requiring a few auxiliary frames) -- but this is not always the case. Like cutting a rectangular piece of wood with a linear saw: you can only make straight cuts from one side to the oposite one; you can't stop in the middle. Those are the kind of layouts pack is able to build. The grid manager has its own restrictions too, although it's easier to use when building dialog boxes or input forms. So the place manager is the only one that can provide the flexibility you apparently require. At least if you want a non-rectangular shape as the parcel example in the PDF (or overlapping widgets of any kind). Back to your question. Yes - there is a great need for dictionary adherence. Especially when language translations are probable. Also - The Military, the Engineering/Architectural, Building, Map Making and Graphic Arts and Printing communities have all been 'trained' to the concept of grid. Not to mention Pilots and Navagators. The average person and the Reality Companies all understand the concept of parcels. Grid points can be used without the need to fill the intervening. Take a look at the starts at night. ALL parcels must have one or more parcels between them if they are not contiguous. How else can one walk down the street? Cells in the grid geometry manager must be rectangular, all of them have four neighbourghs (except at the boundary), and adjacent grid cells must have the same dimension at its common side. Those are strong restrictions and I believe parcel is a more generic term than that (just from the dictionary definition -- I'm not a native English speaker). The only mismatch with your dictionary definition of grid would be the uniform part -- and from this Wikipedia article [1] you can see there are rectangular grids in addition to square grids (and triangular, and hexagonal, and...) so it's not just the idea of a crazy Tk designer... Are there any other GUI's that run Python code unchanged on Linux and Windows? Sure. I like wxPython. The question Which is the best GUI toolkit? arises about once per month in this group, see past messages... [1] http://en.wikipedia.org/wiki/Grid_(spatial_index) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: how to fit a gamma distribution
On Tue, Apr 14, 2009 at 6:51 AM, ning luwen ninglu...@gmail.com wrote: i already have tried. and try to use the module scipy.optimize.leastsq to fit, but neither get a good return or just break out like this. is there any other good way?or something wrong with my code? I suggest you try the scipy list. Google for Smart Questions before you do that, though. Also, when asking for help on a list, you need to mention what you've already tried. You've only wasted a day for a useless answer. Also, please keep responses on the list. Other people on the list are much smarter than I am. Traceback (most recent call last): File fitgamma.py, line 33, in lambda e = lambda v, x, y: (fp(v,x)-y) File fitgamma.py, line 26, in lambda fp = lambda v, x: x**(v[0]-1)/(v[1]**v[0]*gamma(v[0]))*exp(-x/v[1]) File mtrand.pyx, line 1236, in mtrand.RandomState.gamma ValueError: shape = 0 Traceback (most recent call last): File fitgamma.py, line 46, in module v, success = leastsq(e, v0, args=(xdata,ydata),maxfev=10) File /usr/lib/python2.6/dist-packages/scipy/optimize/minpack.py, line 270, in leastsq retval = _minpack._lmdif(func,x0,args,full_output,ftol,xtol,gtol,maxfev,epsfcn,factor,diag) minpack.error: Error occured while calling the Python function named lambda ps:the part code in fitting the distribution(xdata,ydata are vectors of the data need to fit. fp = lambda v, x: x**(v[0]-1)/(v[1]**v[0]*gamma(v[0]))*exp(-x/v[1]) e = lambda v, x, y: (fp(v,x)-y) v0 = [6, 3] v, success = leastsq(e, v0, args=(xdata,ydata),maxfev=10) On Mon, Apr 13, 2009 at 8:49 PM, Kushal Kumaran kushal.kuma...@gmail.com wrote: On Mon, Apr 13, 2009 at 1:40 PM, ning luwen ninglu...@gmail.com wrote: hi, i need to fit a gamma distribution, is there any module can do the job? Did you try google? Searching for python curve fitting returns some promising results. -- kushal -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Using Python after a few years of Ruby
Although I'm not 100% new to Python, most of my experience using high- level languages is with Ruby. I had a job doing Rails web development a little ways back and I really enjoyed it. At my current workplace though, we're looking at using Python and I'm trying to get back into the Python groove as it were. I've got plenty of materials to get me up to speed on the mechanics of the language, but I was wondering about the equivalent of some tools I was used to using in Ruby. If there's not anything that's a one-to-one equivalent I totally understand, I'm just looking for some pointers here to get me started. :) 1) Rake - is there an equivalent of Rake? I've seen a bit about SCons, and it looks really nice, but it seems geared towards being a Make replacement for C/C++ rather than something that's used to work with Python itself. Is there anything like a Python build tool? (Or do I even need something like that? I haven't worked with any large Python systems, just little things here and there.) 2) Gems - I've seen a bit about Eggs, but they don't seem to have anywhere near the official status gems do for Ruby. Are there any package management things like this for Python, or do you usually just grab the code you need as-is? 3) Web frameworks - yeah, I realize there are tons of these, but are TurboGears, Django, and Zope still the big ones? I've seen a lot about Pylons, is that a separate framework or is it a ... well, frame that other things are built on? (TG seems to be related to Pylons at a glance?) 4) Unit Test frameworks - If there's a behavioral test suite like RSpec that's be awesome, but I'd be happy to settle for a good, solid unit testing system. Thanks for any advice! -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python after a few years of Ruby
On Apr 14, 12:01 am, blahemailb...@gmail.com wrote: Although I'm not 100% new to Python, most of my experience using high- level languages is with Ruby. I had a job doing Rails web development a little ways back and I really enjoyed it. At my current workplace though, we're looking at using Python and I'm trying to get back into the Python groove as it were. I've got plenty of materials to get me up to speed on the mechanics of the language, but I was wondering about the equivalent of some tools I was used to using in Ruby. If there's not anything that's a one-to-one equivalent I totally understand, I'm just looking for some pointers here to get me started. :) 1) Rake - is there an equivalent of Rake? I've seen a bit about SCons, and it looks really nice, but it seems geared towards being a Make replacement for C/C++ rather than something that's used to work with Python itself. Is there anything like a Python build tool? (Or do I even need something like that? I haven't worked with any large Python systems, just little things here and there.) paver, virtualenv, zc.buildout 2) Gems - I've seen a bit about Eggs, but they don't seem to have anywhere near the official status gems do for Ruby. Are there any package management things like this for Python, or do you usually just grab the code you need as-is? easy_install or pip. Just like gems. 3) Web frameworks - yeah, I realize there are tons of these, but are TurboGears, Django, and Zope still the big ones? I've seen a lot about Pylons, is that a separate framework or is it a ... well, frame that other things are built on? (TG seems to be related to Pylons at a glance?) Pylons is sort of a large collection of software related to web development. Turbogears 2.0 builds on it. There is also CherryPy (Turbogears 1.0 uses that). Django's still the big dog though. 4) Unit Test frameworks - If there's a behavioral test suite like RSpec that's be awesome, but I'd be happy to settle for a good, solid unit testing system. nose, py.test Thanks for any advice! -- http://mail.python.org/mailman/listinfo/python-list
read file with multiple data per line
Hello all, I googled a lot but couldn't find anything that i could consider a possible solution (though i am fairly new to the language and i think this is the main cause of my failure). This is the beginning of the file i have to parse: Modified System 32728 2NHST1 C1 56 3.263 2.528 16.345 and this is the end: 3.65396.4644 20. This line has 7 formatted fields [5 digits integer, 5 digits character, 5 digits character, 5 digits integer, three %8.3f fields]: 2NHST1 C1 56 3.263 2.528 16.345 and this one has 3 %10.4f fields: 3.65396.4644 20. Those rules cannot be ignored or the programs i use to simulate and analyze the results wont work. This file describes the xyz coordinates and atom type of all the atoms of the system i wish to simulate but i must sort all groups of molecules together and that's what i planned to do with a python code. I tried to accomplish this task using fortran wich is my main coding skills, but it proved to be unstable so i decided to handle files using a more apropriate languange while maintaining the number crunching tasks written in fortran. Thanks in advance and i apologise for eventual typos. Eduardo Martins -- http://mail.python.org/mailman/listinfo/python-list
Re: read file with multiple data per line
On Tue, 14 Apr 2009 00:15:18 -0700, Eduardo wrote: Hello all, I googled a lot but couldn't find anything that i could consider a possible solution (though i am fairly new to the language and i think this is the main cause of my failure). You haven't actually said what the problem is. What are you having trouble doing? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
ctypes - random access to address space
Hi, I am currently doing a project in which I interface to a PCI card. To ease the prototyping, I call the API functions, which map the address space of the card to a process memory. I acquire the location in the process memory mapped to an address space using card API, resulting in a c structure, containing an integer field, being a location. The question is, if I can create a ctypes pointer to this location. Is that what i.e. POINTER(uint32).from_address() does? Jan Wicijowski -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes - random access to address space
janislaw schrieb: Hi, I am currently doing a project in which I interface to a PCI card. To ease the prototyping, I call the API functions, which map the address space of the card to a process memory. I acquire the location in the process memory mapped to an address space using card API, resulting in a c structure, containing an integer field, being a location. The question is, if I can create a ctypes pointer to this location. Is that what i.e. POINTER(uint32).from_address() does? Yes. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: sending and receiving ipv6 multicasts
On 13 Apr., 19:51, Martin v. Löwis mar...@v.loewis.de wrote: On the receiving side, you also need to set the IPV6_JOIN_GROUP socket option - else your kernel doesn't know you are interested in packets for that address. You need to bind to the multicast port, and optionally to the multicast address. If I do the following s , ifn = createSocket(eth0) maddr = (ff02::1, 10101) maddr = socket.getaddrinfo(maddr[0], maddr[1], socket.AF_INET6, socket.SOCK_DGRAM)[0][-1] group = socket.inet_pton(socket.AF_INET6, maddr[0]) + ifn #ifn is the interface index s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, group) s.bind(maddr) def createSocket(if=): sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, SO_REUSEPORT): sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1) sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, 224) ifn = if_nametoindex(if) ifn = struct.pack(I, ifn) sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, ifn) return sock, ifn I get the following error: socket.error: [Errno 22] Invalid argument. So it complains about the multicast address. -- http://mail.python.org/mailman/listinfo/python-list
Should we separate business logic and ORM mapping classes?
Hi, ( First, this is not a question about if we should use ORM. It's question for these who are already using it. ) Usually, I only use ORM, like sqlalchemy just as an abstraction layer of database. So these mapping objects I wrote only contains data but not behavior. For example, if I have a class User, I would write another class UserManager which with a methods like addUser, delUser. But recently I am thinking of moving these methods to User. That sounds more OO style. What's your opinion? What's the benefits and problems of this style? -- http://mail.python.org/mailman/listinfo/python-list
Re: sharing/swapping items between lists
On Apr 13, 11:52 pm, Aaron Brady castiro...@gmail.com wrote: On Apr 13, 10:04 am, Ross ross.j...@gmail.com wrote: On Apr 11, 1:10 pm, a...@pythoncraft.com (Aahz) wrote: In article 4fd78ac3-ba83-456b-b768-3a0043548...@f19g2000vbf.googlegroups.com, Ross ross.j...@gmail.com wrote: I'm trying to design an iterator that produces two lists. The first list will be a list of unique pairings and the second will be a list of items that weren't used in the first list. After each round, the items that weren't used in the round before will get put back in and the second list will be populated with unique items. How do you specify what goes into the first list? Based on your description, I would have expected that the output from the first iteration would be ( [(1,2),(3,4),(5,6)], [7,8] ) Regardless of the actual algorithm, if you are returning items one at a time and maintaining state in a computation, you probably want to use a generator. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? I'm sorry...my example was probably a bad one. A better example of output I would like would be something like [[1,2],[3,4],[5,6]] and then for the leftovers list [7,8,9,10 etc]. What I'm trying to do is produce some sort of round robin algorithm for tennis that is constrained by the number of courts available each week. So if there are only 3 courts available for a singles league and 10 people have signed up, 4 players will have a bye each week. I want my algorithm to produce unique matchups each week and also give each player the same angle? Take 3 people, 1 court. snip Then, you need to arrange it so the player with most court time has at most one more match than the player with the least court time, after each week. This is the difficult constraint to satisfy. Do you need to account for newcomers after the rotation has started, departers, favorites, skill, etc.? This problem was actually more difficult than I gave it credit for. The problem first shows up in 6 players 2 courts: abcd efac bd EF! Here, E and F are playing eachother twice in a row, although everyone is getting the right number of games as early as possible. It would take some clever foresight, backtracing, or recognition to mix it up better. attempted handoff -- http://mail.python.org/mailman/listinfo/python-list
Downloading folders from a server
Hi , I am trying to download folders using webDAV Protocol, I want to download the folders which in turn have many other folders. I am trying to read each and every folder and create the folder locally.How do I do this? If I have a folder structure like the following Folder1 | |_ Folder11(has some files also) | Folder111 | |_Folder21 | |_Folder211 If I have to download Folder1, how do I download this maintaining the folder and Files structure inside the sub folders. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Should we separate business logic and ORM mapping classes?
一首诗 wrote: Hi, ( First, this is not a question about if we should use ORM. It's question for these who are already using it. ) Usually, I only use ORM, like sqlalchemy just as an abstraction layer of database. So these mapping objects I wrote only contains data but not behavior. For example, if I have a class User, I would write another class UserManager which with a methods like addUser, delUser. But recently I am thinking of moving these methods to User. That sounds more OO style. What's your opinion? What's the benefits and problems of this style? We do that. Whatever behavior objects have that involves modifying or creating other entities is put into the objects themselves. Of course within reasonable limits. OTOH what we don't want in there are methods targeted at e.g. rendering the objects as HTML. For example, if a user-object has a mandatory email, but an optional name you want to display the name if it's there, otherwise the email. We use a generic function, view (abbreviated v) available in our templates to allow for this: v(user).display_name will work by decorating the user-object, delegating unknown calls to the user itself. The UserDecorator looks like this: class UserDecorator(Decorator): def __init__(self, user): self._delegate = user def __getattr__(self, name): return getattr(self._delegate, name) @property def display_name(self): u = self._delegate return u.name if u.name else u.email Diez -- http://mail.python.org/mailman/listinfo/python-list
Nicing a thread
Hi, I would like to spawn a thread (on Unix) with a lower priority (higher niceness) than the main thread (which should stay at nice 0). What I have done is something like: import threading, os class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): os.nice(19) a_useful_method() It seems to work but I am a bit sure whether I missed anything (I am not that familiar with threading). What do you experts say? Best regards, Jesper -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically generating arithmetic operations for a subclass
Arnaud Delobelle arno...@googlemail.com writes: binops = ['add', 'sub', 'mul', 'div', 'radd', 'rsub'] # etc unops = ['neg', 'abs', invert'] # etc Oops. There's a missing quote above. It should have been, of course: unops = ['neg', 'abs', 'invert'] # etc binop_meth = def __%s__(self, other): return type(self)(int.__%s__(self, other)) unop_meth = def __%s__(self): return type(self)(int.__%s__(self)) class MyInt(int): for op in binops: exec binop_meth % (op, op) for op in unops: exec unop_meth % (op, op) del op HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Python inside C++
AJ Mayorga wrote: Hello all, I am looking for a way to statically compile pythonxx.dll into my C++ application, so that I can use It as an internal scripting language and either run the native python code or take an ELF from py2exe/pyinstaller and run that. The machines that will have my C++ app running on them do not have python and I cannot install it as part of my application. Any Ideas? AJ -- http://mail.python.org/mailman/listinfo/python-list Sure, that's easy. http://www.python.org/doc/2.5.2/ext/embedding.html That should do what I think you want. Picky note: The phrase statically compile pythonxx.dll into my C++ application is not quite correct. A DLL is dynamically linked, not statically linked. All this means is that you ship pythonxx.dll with your application along with any other DLLs and pyd files you might need. But don't worry, you can do what you want. Terms: Embedding = Using python inside an application that is written in another language (usually C/C++). This is what you are asking about. Extending = Making your C/C++ code callable from python. (there are actually several alternatives available, but that is another topic). Enjoy, Ken -- http://mail.python.org/mailman/listinfo/python-list
Automatically generating arithmetic operations for a subclass
I have a subclass of int where I want all the standard arithmetic operators to return my subclass, but with no other differences: class MyInt(int): def __add__(self, other): return self.__class__(super(MyInt, self).__add__(other)) # and so on for __mul__, __sub__, etc. My quick-and-dirty count of the __magic__ methods that need to be over- ridden comes to about 30. That's a fair chunk of unexciting boilerplate. Is there a trick or Pythonic idiom to make arithmetic operations on a class return the same type, without having to manually specify each method? I'm using Python 2.5, so anything related to ABCs are not an option. Does anyone have any suggestions? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically generating arithmetic operations for a subclass
On Apr 14, 4:09 am, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: I have a subclass of int where I want all the standard arithmetic operators to return my subclass, but with no other differences: class MyInt(int): def __add__(self, other): return self.__class__(super(MyInt, self).__add__(other)) # and so on for __mul__, __sub__, etc. My quick-and-dirty count of the __magic__ methods that need to be over- ridden comes to about 30. That's a fair chunk of unexciting boilerplate. Something like this maybe? def takesOneArg(fn): try: fn(1) except TypeError: return False else: return True class MyInt(int): pass template = MyInt.__%s__ = lambda self, other: self.__class__(super (MyInt, self).__%s__(other)) fns = [fn for fn in dir(int) if fn.startswith('__') and takesOneArg (getattr(1,fn))] print fns for fn in fns: exec(template % (fn,fn)) Little harm in this usage of exec, since it is your own code that you are running. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python after a few years of Ruby
Hi, 1) Is there anything like a Python build tool? (Or do I even need something like that?) If you're going to run the python source code, you don't need anything. Python builds what it needs automagically. Some tools exist to build stand-alone executables though, if you'd like to do so (e.g. py2exe, http://www.py2exe.org) 3) Web frameworks I quite like the powerful and very intuitive and easy to use web2py (http://www.web2py.com). (not to be confused with the minimalist web framework web.py, http://webpy.org). Best regards, Stefaan. -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically generating arithmetic operations for a subclass
Steven D'Aprano wrote: I have a subclass of int where I want all the standard arithmetic operators to return my subclass, but with no other differences: class MyInt(int): def __add__(self, other): return self.__class__(super(MyInt, self).__add__(other)) # and so on for __mul__, __sub__, etc. Just an idea: def myint(meth): def mymeth(*args): return MyInt(meth(*args)) return mymeth class MyIntMeta(type): method_names = 'add sub mul neg'.split() def __new__(cls, name, bases, attrs): t = type.__new__(cls, name, bases, attrs) for name in MyIntMeta.method_names: name = '__%s__' % name meth = getattr(t, name) setattr(t, name, myint(meth)) return t class MyInt(int): __metaclass__ = MyIntMeta a = MyInt(3) b = MyInt(3000) print a print b c = a + b print c assert isinstance(c, MyInt) d = c * MyInt(4) print d e = c * 6 * a * b print e assert isinstance(e, MyInt) x = -e print x assert isinstance(x, MyInt) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python inside C++
Ken Seehart wrote: Picky note: The phrase statically compile pythonxx.dll into my C++ application is not quite correct. A DLL is dynamically linked, not statically linked. All this means is that you ship pythonxx.dll with your application along with any other DLLs and pyd files you might need. But don't worry, you can do what you want. The op could also compile Python and all necessary extensions as a static lib and link that lib into his application. It's fairly easy with the VS project files. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically generating arithmetic operations for a subclass
Arnaud Delobelle wrote: I do this: binops = ['add', 'sub', 'mul', 'div', 'radd', 'rsub'] # etc unops = ['neg', 'abs', invert'] # etc binop_meth = def __%s__(self, other): return type(self)(int.__%s__(self, other)) unop_meth = def __%s__(self): return type(self)(int.__%s__(self)) class MyInt(int): for op in binops: exec binop_meth % (op, op) for op in unops: exec unop_meth % (op, op) del op what's the del for? curious, andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyGUI 2.0
Terry Reedy wrote: Does it work with 3.0? As it stands, almost certainly not. But you're welcome to try running it through 2to3 and see what happens. Relevant libraries would have to be available for 3.0 as well -- not sure what the state of play is there. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
binary file compare...
I want to compare two binary files and see if they are the same. I see the filecmp.cmp function but I don't get a warm fuzzy feeling that it is doing a byte by byte comparison of two files to see if they are they same. What should I be using if not filecmp.cmp? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a virtual serial port?
Scott David Daniels wrote: I'ms confused by this statement. What physical connector does your serial port use to get the serial data to the Mac? I only have one 3-year old Mac laptop to look at, and I just don't see anything that I would call a serial port. USB *is* a serial port... that's what the S stands for. ;) -- JanC -- http://mail.python.org/mailman/listinfo/python-list
win32 wins settings
hello I don't understand why this doesn't woks. def setwins(self): from win32com.client import GetObject objWMIService = GetObject(winmgmts: {impersonationLevel=impersonate}!.\\root\\cimv2) colNicConfigs = objWMIService.ExecQuery (SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True) for nic in colNicConfigs: print nic.Description nic.SetWINSServer('','') it looks good http://msdn.microsoft.com/en-us/library/aa393624(VS.85).aspx someone got helps ? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically generating arithmetic operations for a subclass
andrew cooke wrote: Arnaud Delobelle wrote: I do this: binops = ['add', 'sub', 'mul', 'div', 'radd', 'rsub'] # etc unops = ['neg', 'abs', invert'] # etc binop_meth = def __%s__(self, other): return type(self)(int.__%s__(self, other)) unop_meth = def __%s__(self): return type(self)(int.__%s__(self)) class MyInt(int): for op in binops: exec binop_meth % (op, op) for op in unops: exec unop_meth % (op, op) del op what's the del for? To not pollute the namespace of MyInt - otherwise, you could do MyInt(10).op Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: read file with multiple data per line
Eduardo edumlo...@gmail.com (E) wrote: E Hello all, E I googled a lot but couldn't find anything that i could consider a E possible solution (though i am fairly new to the language and i think E this is the main cause of my failure). E This is the beginning of the file i have to parse: E Modified System E32728 E 2NHST1 C1 56 3.263 2.528 16.345 E and this is the end: E 3.65396.4644 20. E This line has 7 formatted fields [5 digits integer, 5 digits E character, 5 digits character, 5 digits integer, three %8.3f fields]: E 2NHST1 C1 56 3.263 2.528 16.345 E and this one has 3 %10.4f fields: E 3.65396.4644 20. E Those rules cannot be ignored or the programs i use to simulate and E analyze the results wont work. E This file describes the xyz coordinates and atom type of all the atoms E of the system i wish to simulate but i must sort all groups of E molecules together and that's what i planned to do with a python code. E I tried to accomplish this task using fortran wich is my main coding E skills, but it proved to be unstable so i decided to handle files E using a more apropriate languange while maintaining the number E crunching tasks written in fortran. I understand that the first two lines are special and that the third line, or the third and fourth lines are repeated. Something like this will parse the lines. After each line you can process the f* variables. inp = open('testinput', 'rt') line1 = inp.readline() line2 = inp.readline() for line in inp: line = line.rstrip('\n') if len(line) == 44: f1 = int(line[0:5]) f2 = line[5:10] f3 = line[10:15] f4 = int(line[15:20]) f5 = float(line[20:28]) f6 = float(line[28:36]) f7 = float(line[36:44]) print f1,f2,f3,f4,f5,f6,f7 elif len(line) == 30: f1 = float(line[0:10]) f2 = float(line[10:20]) f3 = float(line[20:30]) print f1,f2,f3 else: print(Sorry, I don't understand this format: %s % line) -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically generating arithmetic operations for a subclass
Steven D'Aprano ste...@remove.this.cybersource.com.au writes: I have a subclass of int where I want all the standard arithmetic operators to return my subclass, but with no other differences: class MyInt(int): def __add__(self, other): return self.__class__(super(MyInt, self).__add__(other)) # and so on for __mul__, __sub__, etc. My quick-and-dirty count of the __magic__ methods that need to be over- ridden comes to about 30. That's a fair chunk of unexciting boilerplate. Is there a trick or Pythonic idiom to make arithmetic operations on a class return the same type, without having to manually specify each method? I'm using Python 2.5, so anything related to ABCs are not an option. Does anyone have any suggestions? I do this: binops = ['add', 'sub', 'mul', 'div', 'radd', 'rsub'] # etc unops = ['neg', 'abs', invert'] # etc binop_meth = def __%s__(self, other): return type(self)(int.__%s__(self, other)) unop_meth = def __%s__(self): return type(self)(int.__%s__(self)) class MyInt(int): for op in binops: exec binop_meth % (op, op) for op in unops: exec unop_meth % (op, op) del op HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
Peter Pearson wrote: On Sun, 12 Apr 2009 06:53:24 -0500, Tim Chase wrote: From the docs: all(iterable) Return True if all elements of the iterable are true. Equivalent to: def all(iterable): for element in iterable: if not element: return False return True Then I'd say the comment is misleading. An empty list has no item that is true (or false), yet it returns true. The comment in the docs should read Return False if any element of the iterable is not true or Return True if all elements of the iterable are true or if the iterable is empty. How 'bout: Return True if no element of the iterable is not true? I still prefer Return False if any element of the iterable is not true or Return False if any element in the iterable is false because that describes exactly what the algorithm does. Granted, anybody with a mote of Python skills can tell that from the algorithm, but if you're going to go to the trouble of documenting, you might as well document what it does. The code in the docs do not check the truthiness of each element, it checks for the falseness (not-trueness) of each element. One might be able to defend it using logical manipulations, but since Python strives for clarity... -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: design question, metaclasses?
Darren Dale dsdal...@gmail.com (DD) wrote: DD On Apr 11, 2:15 pm, Darren Dale dsdal...@gmail.com wrote: I am working on a project that provides a high level interface to hdf5 files by implementing a thin wrapper around h5py. I would like to generalize the project so the same API can be used with other formats, like netcdf or ascii files. The format specific code exists in File, Group and Dataset classes, which I could reimplement for each format. But there are other classes deriving from Group and Dataset which do not contain any format-specific code, and I would like to find a way to implement the functionality once and apply uniformly across supported formats. This is really abstract, but I was thinking of something along the lines of: format1.Group # implementation of group in format1 format2.Group # ... Base.DerivedGroup # base implementation of DerivedGroup, not directly useful format1.DerivedGroup = Base.DerivedGroup(format1.Group) # useful format2.DerivedGroup = Base.DerivedGroup(format2.Group) # useful Could anyone please offer a comment, is this an appropriate use of metaclassing, or is there maybe an easier/better alternative? DD I don't fully understand metaclasses, but I think I have convinced DD myself that they are not what I was looking for. I think this will do DD what I want it to: DD class Group1(object): DD def origin(self): DD return Group1 DD class Group2(object): DD def origin(self): DD return Group2 DD def _SubGroup(superclass): DD class SubGroup(superclass): DD pass DD return SubGroup DD SubGroup = _SubGroup(Group2) What is the difference of this with: class SubGroup(Group2): pass ? DD sub_group = SubGroup() DD print sub_group.origin() From your description I find it very difficult to understand what you want. But I have some feeling that multiple inheritance may be something you could use. -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: path to executing .py file
tiefeng wu wrote: Hello everybody! I'm working on my code repository (svn) auto-backup script which get hotcopy of svn repository directory to a directory named by date in same location where script file is, it executed by a timer program every 00:00 clock. Everything works fine when I'm testing by double click it. But when auto execute it, I got unexpected behavior. The backup directory will be created under C:\Documents and settings\username. I create backup directory by this way: os.mkdir(os.getcwd() + arch_dir) is there some way to get path to my executing script, so I can replaced os.getcwd() in above line? The path of your script is given by __file__. And I have another question, I've tried remove a copy of svn repository by calling shutil.rmtree(svn_repos_copy_dir) I got error Access denied! Is that mean my script has no power to delete it? Is there some way to give the right to do that? -- http://mail.python.org/mailman/listinfo/python-list
how to know argument name with which a function of extended c called
Hi, i need to write a 'c extension function' in this function i need to change argument value with which this function called. ie, if a python code like import changeValue as c arg=old value c.changeValue(arg) print arg then it print new value i write code like this.. static PyObject *changeValue(PyObject *self,PyObject *args){ PyObject *sampleObj, *m ; char *argName; if (!PyArg_ParseTuple(args, O, sampleObj)){ return NULL; } m = PyImport_AddModule(__main__); PyObject_SetAttrString(m, argName, new value); return Py_BuildValue(); } But for this i need to know the argument name with which this function called . Is this possible to know argument name in extended c function? if yes, than how i can do it??? -- http://mail.python.org/mailman/listinfo/python-list
Re: sharing/swapping items between lists
In article f64c9de2-3285-4f74-adb8-2111c78b7...@37g2000yqp.googlegroups.com, Ross ross.j...@gmail.com wrote: On Apr 13, 9:08=A0am, a...@pythoncraft.com (Aahz) wrote: In article c569228f-f391-4317-83a2-08621c601...@r8g2000yql.googlegroups.= com, Ross =A0ross.j...@gmail.com wrote: I'm sorry...my example was probably a bad one. A better example of output I would like would be something like [[1,2],[3,4],[5,6]] and then for the leftovers list [7,8,9,10 etc]. What I'm trying to do is produce some sort of round robin algorithm for tennis that is constrained by the number of courts available each week. So if there are only 3 courts available for a singles league and 10 people have signed up, 4 players will have a bye each week. I want my algorithm to produce unique matchups each week and also give each player the same angle? How about Googling for round robin algorithm python? ;-) I have the basic algorithm and it works fine...I'm just having trouble adding another parameter to it that allows for court constraints and bye weeks. You'll need to give us more information, then. Why don't you start with the core algorithm you're using? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython question
On Apr 13, 9:12 pm, Clemens Anhuth blackw...@nexgo.de wrote: isam uraiqat wrote: I HATE VISTA!! it just needed to be installed on the site packages library, because it was installed by default on program files, hope this might help another poor vista user Hello. Can you explain? Does the installer default to the wrong directory (installer fault)? Does Vista mislead you to choose the wrong directory in the installer (user fault)? With best regards Clemens Anhuth I've not had any problems whatsoever installing wxPython or its demo on Vista. What are you doing exactly? Mike -- http://mail.python.org/mailman/listinfo/python-list
Modifying the value of a float-like object
Hello, Is there a way to easily build an object that behaves exactly like a float, but whose value can be changed? The goal is to maintain a list [x, y,…] of these float-like objects, and to modify their value on the fly (with something like x.value = 3.14) so that any expression like x +y uses the new value. I thought of two solutions, both of which I can't make to work: 1) Use a class that inherits from float. This takes care of the behave like float part. But is it possible to change the value of the float associated with an instance? That is, is it possible to do: x = MyFloat(1.23); x.change_value(3.14) so that x's float value becomes 3.14? 2) The other possibility I thought of was: use a class that defines a 'value' member (x.value). This takes care of the value can be changed part. But is it possible/easy to make it fully behave like a float (including when passed to functions like math.sin)? Alternatively, I'd be happy with a way of handling numerical uncertainties in Python calculations (such as in calculate the value and uncertainty of a*sin(b) knowing that a=3.0 +/- 0.1 and b=1.00 +/- 0.01). Any idea would be much appreciated! -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically generating arithmetic operations for a subclass
andrew cooke and...@acooke.org writes: Arnaud Delobelle wrote: I do this: binops = ['add', 'sub', 'mul', 'div', 'radd', 'rsub'] # etc unops = ['neg', 'abs', invert'] # etc binop_meth = def __%s__(self, other): return type(self)(int.__%s__(self, other)) unop_meth = def __%s__(self): return type(self)(int.__%s__(self)) class MyInt(int): for op in binops: exec binop_meth % (op, op) for op in unops: exec unop_meth % (op, op) del op what's the del for? Without it, 'op' would end up as a class attribute. curious, andrew -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: how to know argument name with which a function of extended c called
On Apr 14, 10:35 pm, rahul rahul03...@gmail.com wrote: Hi, i need to write a 'c extension function' in this function i need to change argument value with which this function called. The appropriate way for a function to give output is to return a value, or a tuple of values. example: def get_next_token(input_buffer, offset): get next lexical token, starting at offset return (the_token, new offset) length = find_len_of_token_somehow(input_buffer, offset) new_offset = offset + length return input_buffer[offset:new_offset], new_offset and you can call it by token, pos = get_next_token(buff, pos) return input ie, if a python code like import changeValue as c arg=old value c.changeValue(arg) print arg Fortunately, you can't construct such a thing in Python or in a C extension. Consider the following: print two, 2 c.changeValue(2) print two maybe, 2 What would you want to it to print the second time? two maybe new value? then it print new value i write code like this.. static PyObject *changeValue(PyObject *self,PyObject *args){ PyObject *sampleObj, *m ; char *argName; if (!PyArg_ParseTuple(args, O, sampleObj)){ return NULL; } m = PyImport_AddModule(__main__); This means you are assuming/hoping this function will be called only from the main script ... PyObject_SetAttrString(m, argName, new value); Even if you know the name, you have the problem that it is changing the __main__ module's globals ... but the arg could be local or it could be an expression ... return Py_BuildValue(); } But for this i need to know the argument name with which this function called . Is this possible to know argument name in extended c function? if yes, than how i can do it??? No, it's not possible to know the argument name (without help from the caller e.g. keyword args), it may not even have a name, it may have multiple names ... this is just another variation of the old what is the name of my object FAQ. Why don't you tell us what you are trying to achieve (a higher-level goal than I need to poke some value at/into some variable of doubtful name and unknowable location), and then we might be able to give you some ideas. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
Tim Chase python.l...@tim.thechases.com writes: Peter Pearson wrote: On Sun, 12 Apr 2009 06:53:24 -0500, Tim Chase wrote: From the docs: all(iterable) Return True if all elements of the iterable are true. Equivalent to: def all(iterable): for element in iterable: if not element: return False return True Then I'd say the comment is misleading. An empty list has no item that is true (or false), yet it returns true. The comment in the docs should read Return False if any element of the iterable is not true or Return True if all elements of the iterable are true or if the iterable is empty. How 'bout: Return True if no element of the iterable is not true? I still prefer Return False if any element of the iterable is not true or Return False if any element in the iterable is false because that describes exactly what the algorithm does. Granted, anybody with a mote of Python skills can tell that from the algorithm, but if you're going to go to the trouble of documenting, you might as well document what it does. The code in the docs do not check the truthiness of each element, it checks for the falseness (not-trueness) of each element. One might be able to defend it using logical manipulations, but since Python strives for clarity... -tkc In fact the doc is not just misleading, but plain wrong as the following shows: def alwaystrue(): ... while True: yield True ... all(alwaystrue()) [Python is stuck] The iterable alwaystrue() satisfies the property all elements of the iterable are true, but all(alwaystrue()) does not return. Instead one could describe all()'s behaviour as: Return False as soon as the first false element in the iterable is found. Otherwise return True when the iterable is exhausted. Unfortunately it makes it much less obvious what the function is for and the Python implementation is a clearer explanation IMHO. So in the end, I think the doc reaches a good compromise: a short easy to understand english description that gives a clear idea of what all() is for, and a sample implementation for those who need/want the exact behaviour. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: how to know argument name with which a function of extended c called
rahul rahul03...@gmail.com writes: Hi, i need to write a 'c extension function' in this function i need to change argument value with which this function called. ie, if a python code like import changeValue as c arg=old value c.changeValue(arg) print arg then it print new value i write code like this.. static PyObject *changeValue(PyObject *self,PyObject *args){ PyObject *sampleObj, *m ; char *argName; if (!PyArg_ParseTuple(args, O, sampleObj)){ return NULL; } m = PyImport_AddModule(__main__); PyObject_SetAttrString(m, argName, new value); return Py_BuildValue(); } But for this i need to know the argument name with which this function called . Is this possible to know argument name in extended c function? if yes, than how i can do it??? No, you can't and it's a good thing, because when reading your code you can find out very easily when a variable has been rebound: it's on those lines of the form name = expression Instead, make your 'changeValue function return the new value, then write: import changeValue as c arg = old value arg = c.changeValue(arg) print arg It'll work, with the added benefit that it'll be clearer that arg was changed. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: I/O operation on closed file
On Apr 14, 6:43 am, Dennis Lee Bieber wlfr...@ix.netcom.com wrote: On Mon, 13 Apr 2009 16:44:44 -0700 (PDT), dj d.a.aberna...@gmail.com And Dennis' revised script works for me on Python 2.6 and [after converting print x to print(x)] Python 3.0 (both ActivePython installations). Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
iPython help, Docstring [source file open failed]
I use iPython installed from macport. When I am in the iPython shell, I do the following: In [8]: from datetime import timedelta In [9]: timedelta?? Type: type Base Class: type 'type' String Form:type 'datetime.timedelta' Namespace: Interactive File: /opt/local/Library/Frameworks/Python.framework/ Versions/2.5/lib/python2.5/lib-dynload/datetime.so Docstring [source file open failed]: Difference between two datetime values. Lets say I want more information about timedelta right at the shell (as oppose lookup at Python Doc). Can I somehow link the actual Python source code to iPython so that it can be accessed in that way? I am using macport. Please help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically generating arithmetic operations for a subclass
Arnaud Delobelle wrote: andrew cooke and...@acooke.org writes: Arnaud Delobelle wrote: class MyInt(int): for op in binops: exec binop_meth % (op, op) for op in unops: exec unop_meth % (op, op) del op what's the del for? Without it, 'op' would end up as a class attribute. ah! ok, that makes sense, i guess. thanks. (i just tried it out and you're right, of course, but also if binops and unops are empty you get an error, although i guess that's no an issue here). andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
On Apr 12, 10:45 am, Tim Chase python.l...@tim.thechases.com wrote: That's why you ask Do you have any books called 'Robinson Crusoe'? rather than Are all your books called 'Robinson Crusoe'?. Mu. If I don't have any books...Have you stopped beating all your wives? The question makes the presumption that I have books (or that you've been beating your wife). A previous time we had this dicussion, I pointed out that natural language comparisons are questionable since in natural langauge you are not confined to two answers. The valid answer to the above question could be I don't have any books, neither yes nor no. The closest thing to that you can get in Python is to raise an exception. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] PEP 382: Namespace Packages
On 2009-04-07 19:46, P.J. Eby wrote: At 04:58 PM 4/7/2009 +0200, M.-A. Lemburg wrote: On 2009-04-07 16:05, P.J. Eby wrote: At 02:30 PM 4/7/2009 +0200, M.-A. Lemburg wrote: Wouldn't it be better to stick with a simpler approach and look for __pkg__.py files to detect namespace packages using that O(1) check ? Again - this wouldn't be O(1). More importantly, it breaks system packages, which now again have to deal with the conflicting file names if they want to install all portions into a single location. True, but since that means changing the package infrastructure, I think it's fair to ask distributors who want to use that approach to also take care of looking into the __pkg__.py files and merging them if necessary. Most of the time the __pkg__.py files will be empty, so that's not really much to ask for. This means your proposal actually doesn't add any benefit over the status quo, where you can have an __init__.py that does nothing but declare the package a namespace. We already have that now, and it doesn't need a new filename. Why would we expect OS vendors to start supporting it, just because we name it __pkg__.py instead of __init__.py? I lost you there. Since when do we support namespace packages in core Python without the need to add some form of magic support code to __init__.py ? My suggestion basically builds on the same idea as Martin's PEP, but uses a single __pkg__.py file as opposed to some non-Python file yaddayadda.pkg. Right... which completely obliterates the primary benefit of the original proposal compared to the status quo. That is, that the PEP 382 way is more compatible with system packaging tools. Without that benefit, there's zero gain in your proposal over having __init__.py files just call pkgutil.extend_path() (in the stdlib since 2.3, btw) or pkg_resources.declare_namespace() (similar functionality, but with zipfile support and some other niceties). IOW, your proposal doesn't actually improve the status quo in any way that I am able to determine, except that it calls for loading all the __pkg__.py modules, rather than just the first one. (And the setuptools implementation of namespace packages actually *does* load multiple __init__.py's, so that's still no change over the status quo for setuptools-using packages.) The purpose of the PEP is to create a standard for namespace packages. That's orthogonal to trying to enhance or change some existing techniques. I don't see the emphasis in the PEP on Linux distribution support and the remote possibility of them wanting to combine separate packages back into one package as good argument for adding yet another separate hierarchy of special files which Python scans during imports. That said, note that most distributions actually take the other route: they try to split up larger packages into smaller ones, so the argument becomes even weaker. It is much more important to standardize the approach than to try to extend some existing trickery and make them even more opaque than they already are by introducing yet another level of complexity. My alternative approach builds on existing methods and fits nicely with the __init__.py approach Python has already been using for more than a decade now. It's transparent, easy to understand and provides enough functionality to build upon - much like the original __init__.py idea. I've already laid out the arguments for and against it in my previous reply, so won't repeat them here. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 14 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ 2009-03-19: Released mxODBC.Connect 1.0.1 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
Tim Chase wrote: I still prefer Return False if any element of the iterable is not true or Return False if any element in the iterable is false because that describes exactly what the algorithm does. Granted, anybody with a mote of Python skills can tell that from the algorithm, but if you're going to go to the trouble of documenting, you might as well document what it does. The code in the docs do not check the truthiness of each element, it checks for the falseness (not-trueness) of each element. One might be able to defend it using logical manipulations, but since Python strives for clarity... Arnaud Delobelle wrote: Return False as soon as the first false element in the iterable is found. Otherwise return True when the iterable is exhausted. Unfortunately it makes it much less obvious what the function is for and the Python implementation is a clearer explanation IMHO. So in the end, I think the doc reaches a good compromise: a short easy to understand english description that gives a clear idea of what all() is for, and a sample implementation for those who need/want the exact behaviour. IMO, you can't get around the essential ambiguity of the words all, any, every, no, etc. in the plain-English realm. The only way around this is to have the definition focus on the *individual* element of the iterable, not on the *collection* of elements. So I think Arnaud is headed in the right direction. My own choice would be to ignore his (very reasonable) objection to a definition that makes it much less obvious what the function is for, and go with these: all(iterable) -- Return True if there does not exist an element in iterable that is False any(iterable) -- Return False if there does not exist an element in iterable that is True These definitions *imply* the functions' short-circuiting behavior, but aren't as good as Arnaud's definition, which makes the short-circuiting explicit. -John -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying the value of a float-like object
It looks like what is needed here are a kind of mutable float. Is there a simple way of creating such a type? I don't mind changing the value through x.value = 1.23 instead of x = 1.23... :) On Apr 14, 3:03 pm, eric.le.bi...@spectro.jussieu.fr wrote: Hello, Is there a way to easily build an object that behaves exactly like a float, but whose value can be changed? The goal is to maintain a list [x, y,…] of these float-like objects, and to modify their value on the fly (with something like x.value = 3.14) so that any expression like x +y uses the new value. I thought of two solutions, both of which I can't make to work: 1) Use a class that inherits from float. This takes care of the behave like float part. But is it possible to change the value of the float associated with an instance? That is, is it possible to do: x = MyFloat(1.23); x.change_value(3.14) so that x's float value becomes 3.14? 2) The other possibility I thought of was: use a class that defines a 'value' member (x.value). This takes care of the value can be changed part. But is it possible/easy to make it fully behave like a float (including when passed to functions like math.sin)? Alternatively, I'd be happy with a way of handling numerical uncertainties in Python calculations (such as in calculate the value and uncertainty of a*sin(b) knowing that a=3.0 +/- 0.1 and b=1.00 +/- 0.01). Any idea would be much appreciated! -- http://mail.python.org/mailman/listinfo/python-list
Help with run command + variable.
Hi everybody, I'm creating my first app (SixA @ http://www.launchpad/gsixaxis) and I have gtk.combobox to chose a profile. When a profile is chosen I save the profiles name as a variable, and now I want to combine a command with the variable. Lets say that the user choses th profile firefox. This should be exactly like running: 'sixa action profile firefox' So the command run by my python script should be something like: 'sixa action profile $profile' Where $profile is the chosen profile variable. Here is the code: def on_profile_switch_changed(self, box): model = box.get_model() index = box.get_active() if index: profile = model[index][0] os.system(sixa action profile $profile) prf = pynotify.Notification (SixA, Profile changed to $profile, sixa) prf.show () As you can see I also have a notifications on when the profile has been changed, which also shows the chosen profile. How do I do either of these? /Daniel Holm http://www.danielholm.se -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying the value of a float-like object
On Tue, Apr 14, 2009 at 9:03 AM, eric.le.bi...@spectro.jussieu.fr wrote: Hello, Is there a way to easily build an object that behaves exactly like a float, but whose value can be changed? The goal is to maintain a list [x, y,…] of these float-like objects, and to modify their value on the fly (with something like x.value = 3.14) so that any expression like x +y uses the new value. It's not clear what your requirement is. Why can't you just use floats? For your list, why can't you use a list of floats? Something is missing from your explanation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying the value of a float-like object
eric.le.bi...@spectro.jussieu.fr wrote: It looks like what is needed here are a kind of mutable float. Is there a simple way of creating such a type? I don't mind changing the value through x.value = 1.23 instead of x = 1.23... :) On Apr 14, 3:03 pm, eric.le.bi...@spectro.jussieu.fr wrote: Hello, Is there a way to easily build an object that behaves exactly like a float, but whose value can be changed? The goal is to maintain a list [x, y,…] of these float-like objects, and to modify their value on the fly (with something like x.value = 3.14) so that any expression like x +y uses the new value. I thought of two solutions, both of which I can't make to work: 1) Use a class that inherits from float. This takes care of the behave like float part. But is it possible to change the value of the float associated with an instance? That is, is it possible to do: x = MyFloat(1.23); x.change_value(3.14) so that x's float value becomes 3.14? 2) The other possibility I thought of was: use a class that defines a 'value' member (x.value). This takes care of the value can be changed part. But is it possible/easy to make it fully behave like a float (including when passed to functions like math.sin)? Alternatively, I'd be happy with a way of handling numerical uncertainties in Python calculations (such as in calculate the value and uncertainty of a*sin(b) knowing that a=3.0 +/- 0.1 and b=1.00 +/- 0.01). Any idea would be much appreciated! I think you'll have to describe your use case a little better. I don't see why you'd need a mutable float. As long as the reference x is visible to the other parts of your code, when that code uses x, it'll always get the right instance of a float object. --David -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying the value of a float-like object
eric.le.bi...@spectro.jussieu.fr wrote: Hello, Is there a way to easily build an object that behaves exactly like a float, but whose value can be changed? The goal is to maintain a list [x, y,…] of these float-like objects, and to modify their value on the fly (with something like x.value = 3.14) so that any expression like x +y uses the new value. Your approach doesn't follow the Python philosophy thus it's most likely to fail. It is possible to implement a mutable float like object -- Python doesn't stop you from shooting yourself in the knee -- but please don't harm yourself. Python has an easy way to archive an equal goal: data = [1.0, 2.0, -1.0, -7.0, 23.0] for idx, value in enumerate(data): if value 0.0: data[idx] = value**2 Important side note: It's ok to modify elements of a list while iterating over the same list. But you should not remove, append, insert or reorder the list while you are iterating over it. It will lead to surprising effects. Christian -- http://mail.python.org/mailman/listinfo/python-list
subprocess: reading from stdout hangs process termination, waiting for ENTER keyboard signal
Hello everyone. I'm trying to use subprocess module to launch a Windows console application. The application prints some results to standard output and then waits for the user to press any key to terminte. I can't control this behaviour, as the application is not mine... I'm stuck at the very first lines of my code. I'm trying to force process termination (even with proc.terminate()), and it works only if I don't read from stdout. If I do proc.stdout.read() the process hangs, and I have to manually press the keyboard to interrupt it. Probably it's due a low-level handle that is kept on the process stdout, waiting for the keypress event... How can I solve it? Giovanni --- Code excerpt--- proc = subprocess.Popen('the_app.exe', shell=True, stdout=subprocess.PIPE, ) #stdout_value = proc.communicate()[0] stdout_value = proc.stdout.read() PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, proc.pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) print stdout_value -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying the value of a float-like object
Christian Heimes wrote: eric.le.bi...@spectro.jussieu.fr wrote: Hello, Is there a way to easily build an object that behaves exactly like a float, but whose value can be changed? The goal is to maintain a list [x, y,…] of these float-like objects, and to modify their value on the fly (with something like x.value = 3.14) so that any expression like x +y uses the new value. Your approach doesn't follow the Python philosophy thus it's most likely to fail. It is possible to implement a mutable float like object -- Python doesn't stop you from shooting yourself in the knee -- but please don't harm yourself. [snip] The saying is actually shooting yourself in the foot, but then that's like what happens when you don't follow the Python philosophy! :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] PEP 382: Namespace Packages
At 05:02 PM 4/14/2009 +0200, M.-A. Lemburg wrote: I don't see the emphasis in the PEP on Linux distribution support and the remote possibility of them wanting to combine separate packages back into one package as good argument for adding yet another separate hierarchy of special files which Python scans during imports. That said, note that most distributions actually take the other route: they try to split up larger packages into smaller ones, so the argument becomes even weaker. I think you've misunderstood something about the use case. System packaging tools don't like separate packages to contain the *same file*. That means that they *can't* split a larger package up with your proposal, because every one of those packages would have to contain a __pkg__.py -- and thus be in conflict with each other. Either that, or they would have to make a separate system package containing *only* the __pkg__.py, and then make all packages using the namespace depend on it -- which is more work and requires greater co-ordination among packagers. Allowing each system package to contain its own .pkg or .nsp or whatever files, on the other hand, allows each system package to be built independently, without conflict between contents (i.e., having the same file), and without requiring a special pseudo-package to contain the additional file. Also, executing multiple __pkg__.py files means that when multiple system packages are installed to site-packages, only one of them could possibly be executed. (Note that, even though the system packages themselves are not combined, in practice they will all be installed to the same directory, i.e., site-packages or the platform equivalent thereof.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying the value of a float-like object
eric.le.bi...@spectro.jussieu.fr wrote: Alternatively, I'd be happy with a way of handling numerical uncertainties in Python calculations (such as in calculate the value and uncertainty of a*sin(b) knowing that a=3.0 +/- 0.1 and b=1.00 +/- 0.01). Naive no warranties implementation: from math import sin, sqrt class Value(object): def __init__(self, value, err): self.value = value self.err = err def __str__(self): return %s +- %s % (self.value, self.err) def derive(f, values, i, eps=1e-5): x1 = f(*values) values = list(values) values[i] += eps x2 = f(*values) return (x2-x1)/eps def calc(f, *args): values = [v.value for v in args] errs = [v.err for v in args] sigma = 0 for i, (v, e) in enumerate(zip(values, errs)): x = derive(f, values, i)*e sigma += x*x return Value(f(*values), sqrt(sigma)) a = Value(3.0, 0.1) b = Value(1.0, 0.01) def f(x, y): return x * sin(y) print a = %s % a print b = %s % b print c = %s % calc(f, a, b) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess: reading from stdout hangs process termination, waiting for ENTER keyboard signal
giohappy wrote: Hello everyone. I'm trying to use subprocess module to launch a Windows console application. The application prints some results to standard output and then waits for the user to press any key to terminte. I can't control this behaviour, as the application is not mine... I'm stuck at the very first lines of my code. I'm trying to force process termination (even with proc.terminate()), and it works only if I don't read from stdout. If I do proc.stdout.read() the process hangs, and I have to manually press the keyboard to interrupt it. Probably it's due a low-level handle that is kept on the process stdout, waiting for the keypress event... How can I solve it? Giovanni --- Code excerpt--- proc = subprocess.Popen('the_app.exe', shell=True, stdout=subprocess.PIPE, ) #stdout_value = proc.communicate()[0] stdout_value = proc.stdout.read() PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, proc.pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) print stdout_value Try this: proc = subprocess.Popen('the_app.exe', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) stdout_value = proc.communicate(\n)[0] -- http://mail.python.org/mailman/listinfo/python-list
Re: read file with multiple data per line
On Apr 14, 12:32 am, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Tue, 14 Apr 2009 00:15:18 -0700, Eduardo wrote: Hello all, I googled a lot but couldn't find anything that i could consider a possible solution (though i am fairly new to the language and i think this is the main cause of my failure). You haven't actually said what the problem is. What are you having trouble doing? -- Steven Sorry for that Steven, my main problem is to devise a way to read all the content of that file into a dictionary or other structure where i could group atoms by molecule name. On Apr 14, 4:49 am, Piet van Oostrum p...@cs.uu.nl wrote: Eduardo edumlo...@gmail.com (E) wrote: E Hello all, E I googled a lot but couldn't find anything that i could consider a E possible solution (though i am fairly new to the language and i think E this is the main cause of my failure). E This is the beginning of the file i have to parse: E Modified System E 32728 E 2NHST1 C1 56 3.263 2.528 16.345 E and this is the end: E 3.6539 6.4644 20. E This line has 7 formatted fields [5 digits integer, 5 digits E character, 5 digits character, 5 digits integer, three %8.3f fields]: E 2NHST1 C1 56 3.263 2.528 16.345 E and this one has 3 %10.4f fields: E 3.6539 6.4644 20. E Those rules cannot be ignored or the programs i use to simulate and E analyze the results wont work. E This file describes the xyz coordinates and atom type of all the atoms E of the system i wish to simulate but i must sort all groups of E molecules together and that's what i planned to do with a python code. E I tried to accomplish this task using fortran wich is my main coding E skills, but it proved to be unstable so i decided to handle files E using a more apropriate languange while maintaining the number E crunching tasks written in fortran. I understand that the first two lines are special and that the third line, or the third and fourth lines are repeated. Something like this will parse the lines. After each line you can process the f* variables. inp = open('testinput', 'rt') line1 = inp.readline() line2 = inp.readline() for line in inp: line = line.rstrip('\n') if len(line) == 44: f1 = int(line[0:5]) f2 = line[5:10] f3 = line[10:15] f4 = int(line[15:20]) f5 = float(line[20:28]) f6 = float(line[28:36]) f7 = float(line[36:44]) print f1,f2,f3,f4,f5,f6,f7 elif len(line) == 30: f1 = float(line[0:10]) f2 = float(line[10:20]) f3 = float(line[20:30]) print f1,f2,f3 else: print(Sorry, I don't understand this format: %s % line) -- Piet van Oostrum p...@cs.uu.nl URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org Thank you very much Piet, i will try your sugestion. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyGUI 2.0
greg wrote: Terry Reedy wrote: Does it work with 3.0? As it stands, almost certainly not. But you're welcome to try running it through 2to3 and see what happens. Relevant libraries would have to be available for 3.0 as well -- not sure what the state of play is there. Probably something is missing for at least one of the platforms. I expect library conversion will speed up after 3.1 is released. If you ever want to go for stdlib inclusion, you will almost certainly have to target 3.x. It certainly is an untapped 'market' at the moment. -- http://mail.python.org/mailman/listinfo/python-list
History of python syntax development?
Hi all, I'm doing some work in programming languages and I'm looking for a short history of python development, from the point of view of the initial development of the syntax. I know I can go through the mailing lists and news groups (and I am doing that at the moment), and the python history blog has some stuff, but is there anyone who can recommend a site/book that has a good description of how the syntax was chosen and the arguments for/against some of the basic syntax elements. I understand a lot of it was taken from ABC, so if anyone has the same info for that language, that would be great too! Any help would be much appreciated, in the mean time, I must return to churning through the mailing lists :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically generating arithmetic operations for a subclass
Steven D'Aprano – Dienstag, 14. April 2009 11:09 I have a subclass of int where I want all the standard arithmetic operators to return my subclass, but with no other differences: class MyInt(int): def __add__(self, other): return self.__class__(super(MyInt, self).__add__(other)) # and so on for __mul__, __sub__, etc. My quick-and-dirty count of the __magic__ methods that need to be over- ridden comes to about 30. That's a fair chunk of unexciting boilerplate. Is there a trick or Pythonic idiom to make arithmetic operations on a class return the same type, without having to manually specify each method? I'm using Python 2.5, so anything related to ABCs are not an option. Does anyone have any suggestions? Metaclasses can be used for this purpuse, see the example for a Roman number type [1] [1] http://paste.pocoo.org/show/97258/ -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -- http://mail.python.org/mailman/listinfo/python-list
Re: History of python syntax development?
I'm doing some work in programming languages and I'm looking for a short history of python development, from the point of view of the initial development of the syntax. I know I can go through the mailing lists and news groups (and I am doing that at the moment), and the python history blog has some stuff, but is there anyone who can recommend a site/book that has a good description of how the syntax was chosen and the arguments for/against some of the basic syntax elements. I understand a lot of it was taken from ABC, so if anyone has the same info for that language, that would be great too! I'm pretty sure you will find this useful: http://python-history.blogspot.com/ written by Guido. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
ANNOUNCING Tahoe-LAFS v1.4
ANNOUNCING Tahoe, the Least-Authority Filesystem, v1.4 The allmydata.org team is pleased to announce the release of version 1.4.1 of Tahoe, the Lightweight-Authorization Filesystem. This is the first release of Tahoe-LAFS which was created solely as a labor of love by volunteers -- it is no longer funded by allmydata.com (see [1] for details). Tahoe-LAFS is a secure, decentralized, fault-tolerant cloud storage system. All of the source code is publicly available under Free Software, Open Source licences. This filesystem is distributed over multiple servers in such a way the filesystem continues to operate correctly even when some of the servers are unavailable, malfunctioning, or malicious. Here is the one-page explanation of Tahoe's unique security and fault-tolerance properties: http://allmydata.org/source/tahoe/trunk/docs/about.html This is the successor to Tahoe-LAFS v1.3, which was released February 13, 2009 [2]. This is a major new release, adding garbage collection, improved diagnostics and error-reporting, and fixing a critical performance problem when downloading large (many GB) files. See the NEWS file [3] and the known_issues.txt file [4] for more information. Besides the Tahoe core, a crop of related projects have sprung up, including frontends for Windows and Macintosh, two front-ends written in JavaScript, a Ruby interface, a plugin for duplicity, a plugin for TiddlyWiki, a new backup tool named GridBackup, CIFS/SMB integration, an iPhone app, and three incomplete frontends for FUSE. See the Related Projects page on the wiki: [5]. COMPATIBILITY Tahoe v1.4 is fully compatible with the version 1 series of Tahoe. Files written by v1.4 clients can be read by clients of all versions back to v1.0. v1.4 clients can read files produced by clients of all versions since v1.0. v1.4 servers can serve clients of all versions back to v1.0 and v1.4 clients can use servers of all versions back to v1.0. This is the fifth release in the version 1 series. The version 1 series of Tahoe will be actively supported and maintained for the forseeable future, and future versions of Tahoe will retain the ability to read files and directories produced by Tahoe v1 for the forseeable future. The version 1 branch of Tahoe is the basis of the consumer backup product from Allmydata, Inc. -- http://allmydata.com . WHAT IS IT GOOD FOR? With Tahoe, you can distribute your filesystem across a set of servers, such that if some of them fail or even turn out to be malicious, the entire filesystem continues to be available. You can share your files with other users, using a simple and flexible access control scheme. Because this software is new, we do not categorically recommend it as the sole repository of data which is extremely confidential or precious. However, we believe that erasure coding, strong encryption, Free/Open Source Software and careful engineering make Tahoe safer than common alternatives, such as RAID, removable drive, tape, on-line storage or Cloud storage systems. This software comes with extensive tests, and there are no known security flaws which would compromise confidentiality or data integrity. (For all currently known issues please see the known_issues.txt file [3].) This release of Tahoe is suitable for the friendnet use case [6] -- it is easy to create a filesystem spread over the computers of you and your friends so that you can share disk space and files. LICENCE You may use this package under the GNU General Public License, version 2 or, at your option, any later version. See the file COPYING.GPL [7] for the terms of the GNU General Public License, version 2. You may use this package under the Transitive Grace Period Public Licence, version 1 or, at your option, any later version. (The Transitive Grace Period Public Licence has requirements similar to the GPL except that it allows you to wait for up to twelve months after you redistribute a derived work before releasing the source code of your derived work.) See the file COPYING.TGPPL.html [8] for the terms of the Transitive Grace Period Public Licence, version 1. (You may choose to use this package under the terms of either licence, at your option.) INSTALLATION Tahoe works on Linux, Mac OS X, Windows, Cygwin, and Solaris, and probably most other systems. Start with docs/install.html [9]. HACKING AND COMMUNITY Please join us on the mailing list [10]. Patches are gratefully accepted -- the RoadMap page [11] shows the next improvements that we plan to make and CREDITS [12] lists the names of people who've contributed to the project. The wiki Dev page [13] contains resources for hackers. SPONSORSHIP Tahoe was originally developed thanks to the sponsorship of Allmydata, Inc. [14], a provider of commercial backup services. Allmydata, Inc. created the Tahoe project, and contributed hardware, software, ideas, bug reports, suggestions, demands, and money (employing several Tahoe hackers and instructing them to
Re: sharing/swapping items between lists
On Apr 14, 5:57 am, a...@pythoncraft.com (Aahz) wrote: In article f64c9de2-3285-4f74-adb8-2111c78b7...@37g2000yqp.googlegroups.com, Ross ross.j...@gmail.com wrote: On Apr 13, 9:08=A0am, a...@pythoncraft.com (Aahz) wrote: In article c569228f-f391-4317-83a2-08621c601...@r8g2000yql.googlegroups.= com, Ross =A0ross.j...@gmail.com wrote: I'm sorry...my example was probably a bad one. A better example of output I would like would be something like [[1,2],[3,4],[5,6]] and then for the leftovers list [7,8,9,10 etc]. What I'm trying to do is produce some sort of round robin algorithm for tennis that is constrained by the number of courts available each week. So if there are only 3 courts available for a singles league and 10 people have signed up, 4 players will have a bye each week. I want my algorithm to produce unique matchups each week and also give each player the same angle? How about Googling for round robin algorithm python? ;-) I have the basic algorithm and it works fine...I'm just having trouble adding another parameter to it that allows for court constraints and bye weeks. You'll need to give us more information, then. Why don't you start with the core algorithm you're using? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? Here's the core algorithm I'm using: def round_robin(teams,rounds): if len(teams)%2: teams.append(None) mid = len(teams) //2 for i in range(rounds): yield zip(teams[:mid], teams[mid:]) teams = teams[0:1] + teams[mid:mid+1] + teams[1:mid-1]+teams[mid +1:]+teams[mid-1:mid] if __name__== '__main__': rounds = 15 teams = range(16) for round in round_robin(teams,rounds): print round -- http://mail.python.org/mailman/listinfo/python-list
Re: sharing/swapping items between lists
On Apr 14, 10:34 am, Ross ross.j...@gmail.com wrote: On Apr 14, 5:57 am, a...@pythoncraft.com (Aahz) wrote: In article f64c9de2-3285-4f74-adb8-2111c78b7...@37g2000yqp.googlegroups.com, Ross ross.j...@gmail.com wrote: On Apr 13, 9:08=A0am, a...@pythoncraft.com (Aahz) wrote: In article c569228f-f391-4317-83a2-08621c601...@r8g2000yql.googlegroups.= com, Ross =A0ross.j...@gmail.com wrote: I'm sorry...my example was probably a bad one. A better example of output I would like would be something like [[1,2],[3,4],[5,6]] and then for the leftovers list [7,8,9,10 etc]. What I'm trying to do is produce some sort of round robin algorithm for tennis that is constrained by the number of courts available each week. So if there are only 3 courts available for a singles league and 10 people have signed up, 4 players will have a bye each week. I want my algorithm to produce unique matchups each week and also give each player the same angle? How about Googling for round robin algorithm python? ;-) I have the basic algorithm and it works fine...I'm just having trouble adding another parameter to it that allows for court constraints and bye weeks. You'll need to give us more information, then. Why don't you start with the core algorithm you're using? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? Here's the core algorithm I'm using: def round_robin(teams,rounds): if len(teams)%2: teams.append(None) mid = len(teams) //2 for i in range(rounds): yield zip(teams[:mid], teams[mid:]) teams = teams[0:1] + teams[mid:mid+1] + teams[1:mid-1]+teams[mid +1:]+teams[mid-1:mid] if __name__== '__main__': rounds = 15 teams = range(16) for round in round_robin(teams,rounds): print round fyi rounds=15 and teams =range(16) was just test code I was playing around with...they could theoretically be anything. -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
On Tue, 14 Apr 2009, Carl Banks wrote: On Apr 12, 10:45 am, Tim Chase python.l...@tim.thechases.com wrote: That's why you ask Do you have any books called 'Robinson Crusoe'? rather than Are all your books called 'Robinson Crusoe'?. Mu. If I don't have any books...Have you stopped beating all your wives? The question makes the presumption that I have books (or that you've been beating your wife). A previous time we had this dicussion, I pointed out that natural language comparisons are questionable since in natural langauge you are not confined to two answers. The valid answer to the above question could be I don't have any books, neither yes nor no. The closest thing to that you can get in Python is to raise an exception. [...] Agreed; having absorbed the answers to my original question, I now understand why all('Robinson Crusoe' in books for books in []) - or with any object in place of the string, or indeed just all([]) - doesn't return False, but, vacuous truth notwithstanding (and it's apparently a not uncontroversial notion), it doesn't seem fair to return True without so much as a how's-your-father. ;) An exception, or at least a specific mention of the case of empty iterables in the docs (as Tim Chase suggested), would have baffled me less than my program telling me that the same items were both ubiquitous and entirely absent from a list of sets! Of course, it's possible people out there depend on the present behaviour. Regards, John -- http://mail.python.org/mailman/listinfo/python-list
show PDF in wxPython?
I would like to import a pdf in a wxPython widget, but didn't find any solution. The imported PDF should work like if it were open in IE or Mozilla... Sugestions? Solutions? P.S. I would like to thank Dennis Lee Bieber for the help about parallel ports... I forgot to do it :-( -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
Quoting John O'Hagan resea...@johnohagan.com: An exception, or at least a specific mention of the case of empty iterables in the docs (as Tim Chase suggested), would have baffled me less than my program telling me that the same items were both ubiquitous and entirely absent from a list of sets! Well, they _were_ both ubiquitous and entirely absent from your list of sets: both propositions are true. Vacuous truth doesn't mean that the answer is incorrect, just that it is meaningless. The problem was not in the answer, but in the question you asked. Of course, it's possible people out there depend on the present behaviour. It's more than that. Python's following the rules here. Maybe it could be documented better, for those without a background in logic/discrete mathematics, but not changed. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- Participe en Universidad 2010, del 8 al 12 de febrero de 2010 La Habana, Cuba http://www.universidad2010.cu -- http://mail.python.org/mailman/listinfo/python-list
Re: sending and receiving ipv6 multicasts
I get the following error: socket.error: [Errno 22] Invalid argument. So it complains about the multicast address. The fragment py import socket py s = socket.inet_pton(socket.AF_INET6, ff02::1) py sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) py sock.bind(('', 9090)) py sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, socket.inet_pton(socket.AF_INET6, ff02::1)+'\0'*4) works fine for me. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python after a few years of Ruby
Hi 1) Is there anything like a Python build tool? (Or do I even need something like that?) If you're going to run the python source code, you don't need anything. Python builds what it needs automagically. Some tools exist to build stand-alone executables though, if you'd like to do so (e.g. py2exe, http://www.py2exe.org) That's not what the gentleman is looking for. Rake is a ruby version of make. It lets you run tasks with dependencies. You use this for repetitive tasks, administration, etc. Very convenient. 3) Web frameworks I quite like the powerful and very intuitive and easy to use web2py (http://www.web2py.com). (not to be confused with the minimalist web framework web.py, http://webpy.org). Looks interesting. Cheers, Emm -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python after a few years of Ruby
Hi there, Ruby transfuge too. Although I'm not 100% new to Python, most of my experience using high- level languages is with Ruby. I had a job doing Rails web development a little ways back and I really enjoyed it. At my current workplace though, we're looking at using Python and I'm trying to get back into the Python groove as it were. I've got plenty of materials to get me up to speed on the mechanics of the language, but I was wondering about the equivalent of some tools I was used to using in Ruby. If there's not anything that's a one-to-one equivalent I totally understand, I'm just looking for some pointers here to get me started. :) 1) Rake - is there an equivalent of Rake? I've seen a bit about SCons, and it looks really nice, but it seems geared towards being a Make replacement for C/C++ rather than something that's used to work with Python itself. Is there anything like a Python build tool? (Or do I even need something like that? I haven't worked with any large Python systems, just little things here and there.) Zed Shaw (of Mongrel fame) apparently created a pythonic rake called Vellum. However, the website returns a 404, and the egg doesn't seem to work. Shame. 2) Gems - I've seen a bit about Eggs, but they don't seem to have anywhere near the official status gems do for Ruby. Are there any package management things like this for Python, or do you usually just grab the code you need as-is? Eggs looks like gems. Except that some of them have actual documentation. The Egg index is here: http://pypi.python.org/pypi. But I'll grant you that easy_install doesn't have quite the list of options gem has. 3) Web frameworks - yeah, I realize there are tons of these, but are TurboGears, Django, and Zope still the big ones? I've seen a lot about Pylons, is that a separate framework or is it a ... well, frame that other things are built on? (TG seems to be related to Pylons at a glance?) Django is kind of like the Rails of Python, while Pylons is kind of like Merb (it integrates different frameworks to get the job done). 4) Unit Test frameworks - If there's a behavioral test suite like RSpec that's be awesome, but I'd be happy to settle for a good, solid unit testing system. BDD doesn't seem to be a big focus of the Python community. No Cucumber either :(. Have a look at Nose, it looks decent. Cheers, Emm -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyGUI 2.0
On Tue, Apr 14, 2009 at 10:02 AM, Terry Reedy tjre...@udel.edu wrote: greg wrote: [...] fwiw, the following python script could be used, when run from the Tests directory, to selectively run the numbered tests: - runtests.py import glob import os import subprocess from GUI import Window, Menu, Label, application, stop_alert class TestWindow(Window): def setup_menus(self, m): m.new_cmd.enabled = 0 m.open_cmd.enabled = 0 m.runtest.enabled = 1 for ndx in range(len(runmenuitems)): if ndx in ranmenuitems: m.runtest[ndx].checked = True def runtest(self, i): try: filename = '%s.py' % runmenuitems[i] retcode = subprocess.call(python %s % (filename), shell=True) if retcode 0: stop_alert(Child was terminated by signal + -retcode) except OSError, e: stop_alert(Execution of %s failed: %s % (filename, str(e))) else: ranmenuitems.add(i) def getrunmenuitems(): filenames = glob.glob('./[0-9][0-9]-*.py') menuitems = [] for filename in filenames: menuitems.append(os.path.basename(filename)[:-3]) return sorted(menuitems) runmenuitems = getrunmenuitems() ranmenuitems = set() win = TestWindow(title=Run Tests, size=(240, 60)) win.menus = [Menu('Run', [(runmenuitems, 'runtest')])] win.add(Label(Select a test from the Run menu, position = (20, 20), width = 200)) win.show() application().run() -- -- http://mail.python.org/mailman/listinfo/python-list
Re: DVCSs wreck tkFileDialog
More info: URL:http://sourceforge.net/mailarchive/forum.php?thread_name=A46CBF978138744AAC019E6FF055EAB70F30AE%40apatlelsmail08.elsys.gtri.orgforum_name=tortoisehg-develop Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python after a few years of Ruby
On 4/14/2009 3:01 AM blahemailb...@gmail.com apparently wrote: 1) Rake - is there an equivalent of Rake? I've seen a bit about SCons, and it looks really nice, but it seems geared towards being a Make replacement for C/C++ rather than something that's used to work with Python itself. Is there anything like a Python build tool? (Or do I even need something like that? I haven't worked with any large Python systems, just little things here and there.) http://www.scons.org/wiki/SconsVsOtherBuildTools Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Modifying the value of a float-like object
eric.le.bi...@spectro.jussieu.fr wrote: It looks like what is needed here are a kind of mutable float. Is there a simple way of creating such a type? I don't mind changing the value through x.value =.23 instead of x = 1.23... :) On Apr 14, 3:03 pm, eric.le.bi...@spectro.jussieu.fr wrote: Hello, Is there a way to easily build an object that behaves exactly like a float, but whose value can be changed? The goal is to maintain a list [x, y,…] of these float-like objects, and to modify their value on the fly (with something like x.value =.14) so that any expression like x +y uses the new value. I thought of two solutions, both of which I can't make to work: 1) Use a class that inherits from float. This takes care of the behave like float part. But is it possible to change the value of the float associated with an instance? That is, is it possible to do: x =yFloat(1.23); x.change_value(3.14) so that x's float value becomes 3.14? 2) The other possibility I thought of was: use a class that defines a 'value' member (x.value). This takes care of the value can be changed part. But is it possible/easy to make it fully behave like a float (including when passed to functions like math.sin)? Alternatively, I'd be happy with a way of handling numerical uncertainties in Python calculations (such as in calculate the value and uncertainty of a*sin(b) knowing that a=0 +/- 0.1 and b=1.00 +/- 0.01). Any idea would be much appreciated! The answer to your original question is no. If the value can be changed, then it doesn't behave like a float. And that's not just a pedantic answer, it's a serious consideration. You have to decide what characteristics of a float you need to mimic, and which ones you don't care about, and which ones you want to change. Only after having a pretty good handle on those answers can you pick a best implementation. Let's call this new type a nfloat, and let's assume you have a function that returns one. That might be a constructor, but it may not, so we're keeping our options open. myval = newfunction(42.0) What do you want to happen when you execute b = myval ? Presumably you want them to be equal but in what sense? Suppose you then change one of them with your suggested attribute/method. myval.value = newfunction(aaa) is b the same as it was (like a float would be), or is b also changed? Do you need lots of functions to work on one of these nfloats, or could you use them as follows: sin( b.value ) Instead of using .value to change the underlying float, how about if you use [0] ? Just use a list of size 1. -- http://mail.python.org/mailman/listinfo/python-list
Re: History of python syntax development?
On Tue, Apr 14, 2009 at 10:01 AM, Ritwik rana@gmail.com wrote: Hi all, I'm doing some work in programming languages and I'm looking for a short history of python development, from the point of view of the initial development of the syntax. I know I can go through the mailing lists and news groups (and I am doing that at the moment), and the python history blog has some stuff, but is there anyone who can recommend a site/book that has a good description of how the syntax was chosen and the arguments for/against some of the basic syntax elements. I understand a lot of it was taken from ABC, so if anyone has the same info for that language, that would be great too! Any help would be much appreciated, in the mean time, I must return to churning through the mailing lists :) Most changes since the original basic syntax are documented as PEPs, which usually contain arguments and analyses of the proposed syntaxes and which were chosen in the end: http://www.python.org/dev/peps/ Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: show PDF in wxPython?
alejandro wrote: I would like to import a pdf in a wxPython widget, but didn't find any solution. The imported PDF should work like if it were open in IE or Mozilla... Sugestions? Solutions? wxPython has several options, all shown in the wxPython demo !! ( IE activeX, pdf-activeX ) btw there is a special wxPython mailing list ;-) wxpython-us...@lists.wxwidgets.org cheers, Stef P.S. I would like to thank Dennis Lee Bieber for the help about parallel ports... I forgot to do it :-( -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: iPython help, Docstring [source file open failed]
Kegan wrote: I use iPython installed from macport. When I am in the iPython shell, I do the following: In [8]: from datetime import timedelta In [9]: timedelta?? Type: type Base Class: type 'type' String Form:type 'datetime.timedelta' Namespace: Interactive File: /opt/local/Library/Frameworks/Python.framework/ Versions/2.5/lib/python2.5/lib-dynload/datetime.so Docstring [source file open failed]: Difference between two datetime values. Lets say I want more information about timedelta right at the shell (as oppose lookup at Python Doc). Can I somehow link the actual Python source code to iPython so that it can be accessed in that way? I am using macport. Please help. You may want to try: import pydoc b = pydoc.render_doc(timedelta) print b Study the pydoc.py lib file, should be of some help. Regards, P. Kaminski -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying the value of a float-like object
Thank you all for your input. It is not yet obvious how to achieve the goal/need that I had in mind in the original post. Basically, I would need to be able to calculate the derive() function of Peter, but without knowing what arguments are passed to the function f under study. Here is why: I'll give more details, as David S. and David R. were asking for. The code could look like this: import crystals my_crystal = crystals.Crystal(Quartz 111) which would set some attributes of my_crystal as floats with uncertainty FloatWithUncert, which behave exactly like floats in calculations (they return the central value of the confidence interval: x returns the value, as for floats, while, x.uncert returns the uncertainty). Now, I'd like to perform a calculation of some physical quantity associated to the crystal: print my_crystal.lattice_spacing(temperature = 273.15) setup = Experiment(my_crystal, my_mirror); print setup.bragg_angle () # An Experiment object also defines and uses FloatWithUncert objects Everything is fine up to now (I have a FloatWithUncert class which inherits from float). Now, I would like to get the uncertainty on the result, even though we have no idea of what quantities are used in lattice_spacing() for the calculation (it can be attribute that are floats, attributes that are FloatWithUncert, module globals defined as FloatWithUncert, etc.). The idea that prompted my initial post was as follows: perform the same calculation of lattice_spacing() many times, but each time change on of existing FloatWithUncert numbers (this is akin to the derive() function of Peter) and deduce the uncertainty on lattice_spacing() (as with the calc() function of Peter). So I thought that the FloatWithUncert class could keep a list createdNumbers of all created FloatWithUncert numbers, be instructed to change the float value of the n-th float to central value + uncertainty, and the calculation would then be performed again, but with a single updated number (as in calc() above): FloatWithUncert.shift_number(n = 3) # The 3rd FloatWithUncert ever created will return central value + uncertainty; others return the central value print my_crystal.lattice_spacing(temperature = 273.15) # This should give a new result The original post was essentially asking: is it possible to write shift_number() in Python? i.e., we have objects 'x' of type FloatWithUncert, which return a single float value when used in expressions such as 'x+1', which can be tracked in a list FloatWithUncert.createdNumbers (created by FloatWithUncert), and modified later (FloatWithUncert.createdNumbers[3].value = ...). In other words, as I was saying in my second post, a kind of mutable float would effectively be needed. Now, to respond to David S., David R. and Christian, it's not possible to use a simple list of floats [x, y,...] because this would not help making the result of x+y change when you change one of the floats _through the list_ (again, I have no other information on what variables, globals, instance attributes, etc. are used in the calculation whose uncertainty is being calculated). I would not like to write my numerous mathematical expressions as list_of_floats [0]+list_of_floats[1]*sin(...), etc. (This would be illegible, and would not be robust.) Peter's solution is nice when you call functions with explicit arguments. But my class methods perform calculations through instance attributes, globals, etc., and I don't want to modify all my calculation code in order to implement error propagation. I hope that the problem is clearer, now. :) A couple of ideas I had: 1) Define a FloatWithUncert object, but get instance values as x(), as in x()+y(). The code is relatively legible. 'x' is mutable. But formulas don't look so good, and you can't drop a float replacement for 'x', as floats are not callable. 2) Write all expressions that could contain FloatWithUncert objects with a 'float()' wrapper (float(x)+float(y)), after defining the FloatWithUncert.__float__() method. FloatWithUncert would be mutable. The code is a little bit heavy, but it is explicit. 'x' could be a pure float. Sorry for this long post. Any thought/idea/remark would be most welcome! -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python after a few years of Ruby
1) Rake - is there an equivalent of Rake? I've seen a bit about SCons, and it looks really nice, but it seems geared towards being a Make replacement for C/C++ rather than something that's used to work with Python itself. Is there anything like a Python build tool? Depends on what you want the build process to do. For Python packages themselves, distutils/setuptools should be sufficient (and it's extensible if you find it insufficient). It's the defacto standard - nearly every Python package comes with a setup.py. Use setup.py build, setup.py install, setup.py bdist_wininst, etc. 4) Unit Test frameworks - If there's a behavioral test suite like RSpec that's be awesome, but I'd be happy to settle for a good, solid unit testing system. The unittest module is in the standard library. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying the value of a float-like object
Thanks Dave for your thoughtful remarks, which you sent right when I was writing a response to the previous posts. I was wondering about a kind mutable float; so you're right, it's not fully a float, because it's mutable. I'd like to have an object that behaves like a float in numerical calculations. I understand that mutability would require to handle such objects with care, as in your example, but Python programmers are used to this with any mutable object. All my calculations use constants with an uncertainty (or regular floats). There are many such calculations in my code, and I'd like it to be very clean. The first idea I mentioned (using x()) is essentially what you propose with using x[0] in calculations. So, it looks like it's not possible to have float-like objects (calculation/formula-wise) that are mutable?! and it also looks like the price to pay for the mutability is to have to write heavier versions of any formula that uses these special floats (that carry an uncertainty): x[0]+y[0]*sin(...), x()+y(), float(x)+float (y),... which, by the way, essentially prevents any float-like object from being used as a float in formulas that you don't write yourself. This does not look good. Python is failing me!!! :/ I heard that this would be easy to do in Ruby (not confirmed, though)... More ideas and thoughts would still be most welcome! On Apr 14, 8:45 pm, Dave Angel da...@ieee.org wrote: eric.le.bi...@spectro.jussieu.fr wrote: It looks like what is needed here are a kind of mutable float. Is there a simple way of creating such a type? I don't mind changing the value through x.value =.23 instead of x = 1.23... :) On Apr 14, 3:03 pm, eric.le.bi...@spectro.jussieu.fr wrote: Hello, Is there a way to easily build an object that behaves exactly like a float, but whose value can be changed? The goal is to maintain a list [x, y,…] of these float-like objects, and to modify their value on the fly (with something like x.value =.14) so that any expression like x +y uses the new value. I thought of two solutions, both of which I can't make to work: 1) Use a class that inherits from float. This takes care of the behave like float part. But is it possible to change the value of the float associated with an instance? That is, is it possible to do: x =yFloat(1.23); x.change_value(3.14) so that x's float value becomes 3.14? 2) The other possibility I thought of was: use a class that defines a 'value' member (x.value). This takes care of the value can be changed part. But is it possible/easy to make it fully behave like a float (including when passed to functions like math.sin)? Alternatively, I'd be happy with a way of handling numerical uncertainties in Python calculations (such as in calculate the value and uncertainty of a*sin(b) knowing that a=0 +/- 0.1 and b=1.00 +/- 0.01). Any idea would be much appreciated! The answer to your original question is no. If the value can be changed, then it doesn't behave like a float. And that's not just a pedantic answer, it's a serious consideration. You have to decide what characteristics of a float you need to mimic, and which ones you don't care about, and which ones you want to change. Only after having a pretty good handle on those answers can you pick a best implementation. Let's call this new type a nfloat, and let's assume you have a function that returns one. That might be a constructor, but it may not, so we're keeping our options open. myval = newfunction(42.0) What do you want to happen when you execute b = myval ? Presumably you want them to be equal but in what sense? Suppose you then change one of them with your suggested attribute/method. myval.value = newfunction(aaa) is b the same as it was (like a float would be), or is b also changed? Do you need lots of functions to work on one of these nfloats, or could you use them as follows: sin( b.value ) Instead of using .value to change the underlying float, how about if you use [0] ? Just use a list of size 1. -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI Programming
On 2009-04-12, Gabriel dun...@dreams.sk wrote: I'm python newbie and i need to write gui for my school work in python. I need to write it really quick, because i haven't much time .) So question is, which of gui toolkits should i pick and learn? I heard PyGTK and Glade are best for quick gui programming? Is it good for beginner? Or is there something better? I have some experience with java swing, btw.. I find PyQt the most pleasant to work with. It has a consistent, well thought out, sophisticated API. WxPython I find the least pleasant to work with. I particularly dislike the way it does layout, and it has a hodge podge of APIs. But it's what I use professionally because of the liberal license. For those using PyGtk, I'd definitely recommend trying Kiwi. Dave Cook -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
On Apr 14, 7:21 pm, Luis Alberto Zarrabeitia Gomez ky...@uh.cu wrote: It's more than that. Python's following the rules here. Maybe it could be documented better, for those without a background in logic/discrete mathematics, but not changed. Agreed. I'd like to guess that in 93.7% of cases, when a programmer has used all(seq) without having thought in advance about what the right thing to do is when seq is empty, the current behaviour is already the right one. I tried to test this hypothesis, but a Google code search for uses of all() turned up very little besides definitions. For example: if all(t.already_filed() for t in my_tax_forms): go_to_bed_happy() else: file_for_extension() In the event that you didn't have any tax_forms, this does the right thing. The current definition also makes reasoning about programs and program transformations easier, thanks to invariants like: all(seq1 + seq2) === all(seq1) and all(seq2) and all(all(s) for s in seqs) === all(chain(*seqs)) and any(not s for s in seq) == not all(seq) These invariants wouldn't hold if all([]) were False, or raised an exception. IMO, the current behaviour meets both the practicality *and* the purity criteria. Mark -- http://mail.python.org/mailman/listinfo/python-list
Data Model - database load
Hello, I'm making a statistics tracking application and was wondering how my chosen data model design would affect performance. I'm not sure if I'm breaking up my objects into too granular a level in the interests of flexibility. class ParentStats Summary level groups of stats class ChildStats Detail level groups of stats. Sum of individual children stats x,y,z= individual parent stats x,y,z foreign key to ParentStats class StatLine A group of stats being tracked. foreign key to ChildStats class StatField a statistic object being tracked''' foreign key to StatLine statgroup (e.g. Temperature Related Stats, etc.) value name Today, I know that I will want to track stats Units Made and Units Consumed. In the future, I may want to start tracking Units Wasted or some other unknown statistic. Will I be placing too much of a burden on the database if the application is built for serving up relatively low volumes of Statlines (including parent level summaries) to high volumes of users? -- http://mail.python.org/mailman/listinfo/python-list
Network game using mysql
Good evening, I am making an online game that stores its data in a mysql database. The thing is that I can't allow the players to interact directly with the important tables of database (they could cheat if I give them access) so I only allow them to write on a table named commands and then a python program running on the server will interpreter that command and update the important tables. For example, a user that wants to build an house writes on the commands table 'build house', and then my python program takes the resources of the user and gives him an house. The thing is that I need to have a program reading the command list in a infinite while loop and I don't know if there is a better way to do this, I am afraid that if the command list gets to crowed my python program may not handle all the commands in time. And if I put two programs reading the same command list sometimes they handle the command twice.. Hope you can help me, Thanks. _ Invite your mail contacts to join your friends list with Windows Live Spaces. It's easy! http://spaces.live.com/spacesapi.aspx?wx_action=createwx_url=/friends.aspxmkt=en-us-- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] PEP 382: Namespace Packages
On 2009-04-14 18:27, P.J. Eby wrote: At 05:02 PM 4/14/2009 +0200, M.-A. Lemburg wrote: I don't see the emphasis in the PEP on Linux distribution support and the remote possibility of them wanting to combine separate packages back into one package as good argument for adding yet another separate hierarchy of special files which Python scans during imports. That said, note that most distributions actually take the other route: they try to split up larger packages into smaller ones, so the argument becomes even weaker. I think you've misunderstood something about the use case. System packaging tools don't like separate packages to contain the *same file*. That means that they *can't* split a larger package up with your proposal, because every one of those packages would have to contain a __pkg__.py -- and thus be in conflict with each other. Either that, or they would have to make a separate system package containing *only* the __pkg__.py, and then make all packages using the namespace depend on it -- which is more work and requires greater co-ordination among packagers. You are missing the point: When breaking up a large package that lives in site-packages into smaller distribution bundles, you don't need namespace packages at all, so the PEP doesn't apply. The way this works is by having a base distribution bundle that includes the needed __init__.py file and a set of extension bundles the add other files to the same directory (without including another copy of __init__.py). The extension bundles include a dependency on the base package to make sure that it always gets installed first. Debian has been using that approach for egenix-mx-base for years. Works great: http://packages.debian.org/source/lenny/egenix-mx-base eGenix has been using that approach for mx package add-ons as well - long before namespace packages where given that name :-) Please note that the PEP is about providing ways to have package parts live on sys.path that reintegrate themselves into a single package at import time. As such it's targeting Python developers that want to ship add-ons to existing packages, not Linux distributions (they usually have their own ideas about what goes where - something that's completely out-of- scope for the PEP). -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 14 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ 2009-03-19: Released mxODBC.Connect 1.0.1 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Network game using mysql
Hi, João Abrantes wrote: Good evening, I am making an online game that stores its data in a mysql database. The thing is that I can't allow the players to interact directly with the important tables of database (they could cheat if I give them access) so I only allow them to write on a table named commands and then a python program running on the server will interpreter that command and update the important tables. For example, a user that wants to build an house writes on the commands table 'build house', and then my python program takes the resources of the user and gives him an house. The thing is that I need to have a program reading the command list in a infinite while loop and I don't know if there is a better way to do this, I am afraid that if the command list gets to crowed my python program may not handle all the commands in time. And if I put two programs reading the same command list sometimes they handle the command twice.. You could use Postgres instead and write stored functions in python to access the tables. This would avoid your asynchrous approach alltogether. Regards Tino -- http://mail.python.org/mailman/listinfo/python-list
Play sound at wanted frequency
I need to playback a sound on a linux machine of a pre-determined frequency like, say, 440 Hz. How can I do that with python? I found the ossaudiodev package, but it says that the ossaudiodev.write() method accepts data as a raw string. It doesn't explain what the string should be like, and the oss documentation is mainly about C++. Do you have any tips to share? -- http://mail.python.org/mailman/listinfo/python-list
Re: Play sound at wanted frequency
Matteo schrieb: I need to playback a sound on a linux machine of a pre-determined frequency like, say, 440 Hz. How can I do that with python? I found the ossaudiodev package, but it says that the ossaudiodev.write() method accepts data as a raw string. It doesn't explain what the string should be like, and the oss documentation is mainly about C++. Do you have any tips to share? Try pygame. You can create samples with it, and play them. See e.g. this: http://www.pygame.org/docs/ref/sndarray.html Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: zProblem
Gabriel Genellina wrote: En Mon, 13 Apr 2009 15:13:53 -0300, norseman norse...@hughes.net escribió: Gabriel Genellina wrote: ...(snip) I can't visualize that working properly in my current need. The ...(snip) Below there is an attempt to reproduce the layout you describe in the PDF: from Tkinter import * root = Tk() pane = Frame(root, width=400, height=300) pane.pack(fill=both, expand=1) w1 = Label(pane, text=1, bg=white) w1.place(relwidth=0.1, relheight=0.5) w2 = Label(pane, text=2, bg=yellow) w2.place(relwidth=0.25, relheight=0.3, relx=0.1) w3 = Label(pane, text=3, bg=red) w3.place(relwidth=0.2, relheight=0.2, relx=0.1, rely=0.3) w4 = Label(pane, text=4, bg=cyan) w4.place(relwidth=0.05, relheight=0.2, relx=0.3, rely=0.3) w5 = Label(pane, text=5, bg=blue) w5.place(relwidth=0.35, relheight=0.5, rely=0.5) w6 = Label(pane, text=X, bg=gray) w6.place(relwidth=0.25, relheight=1, relx=0.35) w7 = Label(pane, text='Rest of master control parceled as whatever', bg=white) w7.place(relwidth=0.40, relheight=1, relx=0.60) root.mainloop() ...(snip) The only mismatch with your dictionary definition of grid would be the uniform part -- and from this Wikipedia article [1] you can see there are rectangular grids in addition to square grids (and triangular, and hexagonal, and...) so it's not just the idea of a crazy Tk designer... Grids are uniform! Same size, non-changing across whole backdrop. There is nothing in uniform that says X==Y. Units along axis need not be same. Corners don't even have to be 90degrees. (Spherical) But they must measure as same size cells across the board. Just like any grid paper. For those reading this that just said AH-Hah!, Spherical (Lat./Long.) is not measured in Cartesian (distance like feet or meter) but in angles (like 7 and 1/2 minute USGS Quads). 7.5minutes of Longitude at the equator does not have the same arc length as 7.5minutes at the poles. But both are 7.5minutes and thus form a (polar) grid. ENOUGH OF THIS - sorry for being long winded. Whoever wrote Tk was not crazy. Just didn't use a dictionary. :) Are there any other GUI's that run Python code unchanged on Linux and Windows? Sure. I like wxPython. The question Which is the best GUI toolkit? arises about once per month in this group, see past messages... I took a look before I wrote in. Based on initial words used I chose Tkinter. The upcomming PyGUI holds great promise. I think they used a dictionary. :) [1] http://en.wikipedia.org/wiki/Grid_(spatial_index) NOW - back to the program snippet Gabriel has so graciously provided. Anyone having the same problem I have had needs to copy/paste the effort and play with it a bit. WOW! - it's what I've been trying to do! (much more YES than not) One can substitute a Frame widget for the Label widget and see how it will work. Do take note that as you traverse away from the 0,0 (here assumed to be top left) point the prior (sum) of the prior widget(s) relwidth (to left) goes into the relx and the same addition to the prior relheight(s) (above) goes into the rely displacements of the current. Also take note of how the parcels flush out at logical places. Place is not a grid (it's parcelling) and it's based on units of % of Frame it is used in. That is: Place uses a % value rather than a finite distance. Thus, to have two different, but same screen size, frames, each in a differently fixed sized frame of it own, YOU WILL HAVE TO REDO THE MATH. Even if both are hooked at the 0,0 of their respective masters. A thought: If all frames are fixed size (at least at first) then the math is straight forward. Make sure any text is accounted for early on or it won't work and becomes, as another Gabriel has noted - ugly. Because when the text isn't fitting you will have some major refitting which means lots and lots of math to be redone. And that's the ugly. Gabriel - THANK YOU VERY MUCH! May not be politically correct but: Whatever your gender - Please give yourself a good hug for me. Steve -- http://mail.python.org/mailman/listinfo/python-list
segmentation fault while using ctypes
Hello All, I am dealing with this weird bug. I have a function in C and I have written python bindings for it using ctypes. I can call this function for couple of times and then suddenly it gives me seg fault. But I can call same function from a C code for any number of times. I cannot get what's going on. here is my code. /**/ /* C Function I am calling */ int get_hash(char *filename,int rate,int ch,unsigned char* hash, unsigned int* hash_size,short* avg_f,short* avg_d){ /* some variable declarations here */ fp = fopen(filename,rb); data = (signed short *)malloc(sizeof(signed short) * N_BLOCKS); whereami = WAVE_HEADER_SIZE; while((!feof(fp)) (fp_more == 1) !ferror(fp)){ fp_data_size = fread(data,sizeof(signed short),N_BLOCKS,fp); whereami += fp_data_size; fp_more = fp_feed_short(fooid,data,fp_data_size); // call to some library funtion } //end while /* some arithmetic calculations here */ n = my_fp_calculate(fooid,audio_length,fp_fingerprint,fit,dom); if (data != NULL) free(data) fclose(fp) return n; } /* END OF C FUNCTION */ Python code - from ctypes import * lib = cdll.LoadLibrary(/usr/lib/libclient.so) def my_func(filename,rate,ch): hash = (c_ubyte * 424)() hash_size = c_uint() avg_f = c_short(0) avg_d = c_short(0) n = lib.get_hash(filename,rate,ch,hash,byref(hash_size),byref (avg_f),byref(avg_d)) hash = None def main(): for filename in os.listdir(MY_DIR): print filename my_func(filename,100,10) print if __name__ == __main__: main() == END OF PYTHON CODE == Thank you in advance, sanket -- http://mail.python.org/mailman/listinfo/python-list
Re: segmentation fault while using ctypes
sanket schrieb: Hello All, I am dealing with this weird bug. I have a function in C and I have written python bindings for it using ctypes. I can call this function for couple of times and then suddenly it gives me seg fault. But I can call same function from a C code for any number of times. I cannot get what's going on. Try debugging it. While a python debug-build might help, I have been getting good results with a simple # gdb python $ set args testscript.py $ run then when the segfaults hit, get a backtrace. You can also of course set a berakpoint to the function in question. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: segmentation fault while using ctypes
sanket wrote: Hello All, I am dealing with this weird bug. I have a function in C and I have written python bindings for it using ctypes. I can call this function for couple of times and then suddenly it gives me seg fault. But I can call same function from a C code for any number of times. I cannot get what's going on. here is my code. /**/ /* C Function I am calling */ int get_hash(char *filename,int rate,int ch,unsigned char* hash, unsigned int* hash_size,short* avg_f,short* avg_d){ /* some variable declarations here */ fp = fopen(filename,rb); You should check the value of 'fp' here. data = (signed short *)malloc(sizeof(signed short) * N_BLOCKS); You should check the value of 'data' here. whereami = WAVE_HEADER_SIZE; What is 'whereami'? while((!feof(fp)) (fp_more == 1) !ferror(fp)){ fp_data_size = fread(data,sizeof(signed short),N_BLOCKS,fp); 'fp_data_size' will be the number of signed shorts read, not the number of bytes. Is this OK? whereami += fp_data_size; The final value of 'whereami' will be WAVE_HEADER_SIZE + the total number of signed shorts read. fp_more = fp_feed_short(fooid,data,fp_data_size); // call to some library funtion } //end while /* some arithmetic calculations here */ n = my_fp_calculate(fooid,audio_length,fp_fingerprint,fit,dom); if (data != NULL) free(data) I don't that 'free()' will complain if 'data' happens to be NULL, although you should've already checked whether 'data' is NULL when you malloc'ed! :-) fclose(fp) return n; } /* END OF C FUNCTION */ Python code - from ctypes import * lib = cdll.LoadLibrary(/usr/lib/libclient.so) def my_func(filename,rate,ch): hash = (c_ubyte * 424)() hash_size = c_uint() avg_f = c_short(0) avg_d = c_short(0) n = lib.get_hash(filename,rate,ch,hash,byref(hash_size),byref (avg_f),byref(avg_d)) hash = None def main(): for filename in os.listdir(MY_DIR): print filename my_func(filename,100,10) print if __name__ == __main__: main() == END OF PYTHON CODE == Thank you in advance, sanket -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: segmentation fault while using ctypes
On Apr 14, 4:00 pm, MRAB goo...@mrabarnett.plus.com wrote: sanket wrote: Hello All, I am dealing with this weird bug. I have a function in C and I have written python bindings for it using ctypes. I can call this function for couple of times and then suddenly it gives me seg fault. But I can call same function from a C code for any number of times. I cannot get what's going on. here is my code. /**/ /* C Function I am calling */ int get_hash(char *filename,int rate,int ch,unsigned char* hash, unsigned int* hash_size,short* avg_f,short* avg_d){ /* some variable declarations here */ fp = fopen(filename,rb); You should check the value of 'fp' here. data = (signed short *)malloc(sizeof(signed short) * N_BLOCKS); You should check the value of 'data' here. whereami = WAVE_HEADER_SIZE; What is 'whereami'? while((!feof(fp)) (fp_more == 1) !ferror(fp)){ fp_data_size = fread(data,sizeof(signed short),N_BLOCKS,fp); 'fp_data_size' will be the number of signed shorts read, not the number of bytes. Is this OK? whereami += fp_data_size; The final value of 'whereami' will be WAVE_HEADER_SIZE + the total number of signed shorts read. fp_more = fp_feed_short(fooid,data,fp_data_size); // call to some library funtion } //end while /* some arithmetic calculations here */ n = my_fp_calculate(fooid,audio_length,fp_fingerprint,fit,dom); if (data != NULL) free(data) I don't that 'free()' will complain if 'data' happens to be NULL, although you should've already checked whether 'data' is NULL when you malloc'ed! :-) fclose(fp) return n; } /* END OF C FUNCTION */ Python code - from ctypes import * lib = cdll.LoadLibrary(/usr/lib/libclient.so) def my_func(filename,rate,ch): hash = (c_ubyte * 424)() hash_size = c_uint() avg_f = c_short(0) avg_d = c_short(0) n = lib.get_hash(filename,rate,ch,hash,byref(hash_size),byref (avg_f),byref(avg_d)) hash = None def main(): for filename in os.listdir(MY_DIR): print filename my_func(filename,100,10) print if __name__ == __main__: main() == END OF PYTHON CODE == Thank you in advance, sanket -- http://mail.python.org/mailman/listinfo/python-list Thank you for your reply. I will make check for fp and data pointers. But my point is this function runs fine while calling it from a C code. it only breaks while calling from python. So I wonder if there can be anything wrong with ctypes module. Thanks, sanket -- http://mail.python.org/mailman/listinfo/python-list
Re: show PDF in wxPython?
alejandro wrote: I would like to import a pdf in a wxPython widget, but didn't find any solution. The imported PDF should work like if it were open in IE or Mozilla... Sugestions? Solutions? P.S. I would like to thank Dennis Lee Bieber for the help about parallel ports... I forgot to do it :-( -- http://mail.python.org/mailman/listinfo/python-list = work like if it were open in IE IE opens the Adobe reader. If that is what you want, look at lib.pdf section 14.1.2 popen3 After file is acquired by python, python can run the adobe reader on it. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: segmentation fault while using ctypes
On Apr 14, 3:56 pm, Diez B. Roggisch de...@nospam.web.de wrote: sanket schrieb: Hello All, I am dealing with this weird bug. I have a function in C and I have written python bindings for it using ctypes. I can call this function for couple of times and then suddenly it gives me seg fault. But I can call same function from a C code for any number of times. I cannot get what's going on. Try debugging it. While a python debug-build might help, I have been getting good results with a simple # gdb python $ set args testscript.py $ run then when the segfaults hit, get a backtrace. You can also of course set a berakpoint to the function in question. Diez Thanks Diez, I used the gdb but it just crashed and kicked my out of gdb prompt. how can I get a stack trace? Thanks, sanket -- http://mail.python.org/mailman/listinfo/python-list
Re: segmentation fault while using ctypes
sanket wrote: On Apr 14, 4:00 pm, MRAB goo...@mrabarnett.plus.com wrote: sanket wrote: Hello All, I am dealing with this weird bug. I have a function in C and I have written python bindings for it using ctypes. I can call this function for couple of times and then suddenly it gives me seg fault. But I can call same function from a C code for any number of times. I cannot get what's going on. here is my code. /**/ /* C Function I am calling */ int get_hash(char *filename,int rate,int ch,unsigned char* hash, unsigned int* hash_size,short* avg_f,short* avg_d){ /* some variable declarations here */ fp = fopen(filename,rb); You should check the value of 'fp' here. data = (signed short *)malloc(sizeof(signed short) * N_BLOCKS); You should check the value of 'data' here. whereami = WAVE_HEADER_SIZE; What is 'whereami'? while((!feof(fp)) (fp_more == 1) !ferror(fp)){ fp_data_size = fread(data,sizeof(signed short),N_BLOCKS,fp); 'fp_data_size' will be the number of signed shorts read, not the number of bytes. Is this OK? whereami += fp_data_size; The final value of 'whereami' will be WAVE_HEADER_SIZE + the total number of signed shorts read. fp_more = fp_feed_short(fooid,data,fp_data_size); // call to some library funtion } //end while /* some arithmetic calculations here */ n = my_fp_calculate(fooid,audio_length,fp_fingerprint,fit,dom); if (data != NULL) free(data) I don't that 'free()' will complain if 'data' happens to be NULL, although you should've already checked whether 'data' is NULL when you malloc'ed! :-) fclose(fp) return n; } /* END OF C FUNCTION */ Python code - from ctypes import * lib = cdll.LoadLibrary(/usr/lib/libclient.so) def my_func(filename,rate,ch): hash = (c_ubyte * 424)() hash_size = c_uint() avg_f = c_short(0) avg_d = c_short(0) n = lib.get_hash(filename,rate,ch,hash,byref(hash_size),byref (avg_f),byref(avg_d)) hash = None def main(): for filename in os.listdir(MY_DIR): print filename my_func(filename,100,10) print if __name__ == __main__: main() == END OF PYTHON CODE == Thank you in advance, sanket -- http://mail.python.org/mailman/listinfo/python-list Thank you for your reply. I will make check for fp and data pointers. But my point is this function runs fine while calling it from a C code. it only breaks while calling from python. So I wonder if there can be anything wrong with ctypes module. It's more likely that it's a bug in your code. -- http://mail.python.org/mailman/listinfo/python-list