Re: Midi manipulation
Massi wrote: On 16 Nov, 23:23, Tim Roberts [EMAIL PROTECTED] wrote: Massi [EMAIL PROTECTED] wrote: Hi everyone, I'm searching for something which allows me to write scripts which handle midi files. I'm totally a newbie in audio manipulation, therefore any suggestion or link related to this field is welcome. Thanks in advance. Google is much faster than this newsgroup. Search for python midi library and the first page gives you a number of good hits. However, there's a lot to manipulating MIDI. What kinds of things are you hoping to accomplish? MIDI, for example, is not a particularly good way to store music for composition. -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. I'm writing a script for didactic musical purpose. As first step I need something as simple as possible, for example a library of functions which are able to play a certain note, with a given instrument and a given length. I thought midi was good for this aim, am I wrong? Oh dear, I'm going to point you away from Python ... but I am not intending to start a flame war... The Apache Cocoon project (NOT the latest version 2.2 though) might appeal to you: http://cocoon.zones.apache.org/demos/release/samples/blocks/midi/ quote: The MIDI block currently gives you an XMidiGenerator to generate an XML representation of any MIDI file (called XMidi by its author Peter Loeb). There is also the XMidiSerializer to render XMidi back as a MIDI file. I have used XSLT to provide some basic musical manipulations such as transposition, and inversion. Retrograde is harder, but I shall see what I can come up with. Hopefully I shall also add some transformers to generate SVG visualisations of the XMidi, starting with normal western musical notation. MIDI Documentation - Documentation available on the Cocoon Wiki. -- http://mail.python.org/mailman/listinfo/python-list
Re: Midi manipulation
Ken Starks wrote: Massi wrote: On 16 Nov, 23:23, Tim Roberts [EMAIL PROTECTED] wrote: Massi [EMAIL PROTECTED] wrote: Hi everyone, I'm searching for something which allows me to write scripts which handle midi files. I'm totally a newbie in audio manipulation, therefore any suggestion or link related to this field is welcome. Thanks in advance. Google is much faster than this newsgroup. Search for python midi library and the first page gives you a number of good hits. However, there's a lot to manipulating MIDI. What kinds of things are you hoping to accomplish? MIDI, for example, is not a particularly good way to store music for composition. -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. I'm writing a script for didactic musical purpose. As first step I need something as simple as possible, for example a library of functions which are able to play a certain note, with a given instrument and a given length. I thought midi was good for this aim, am I wrong? Oh dear, I'm going to point you away from Python ... but I am not intending to start a flame war... The Apache Cocoon project (NOT the latest version 2.2 though) might appeal to you: http://cocoon.zones.apache.org/demos/release/samples/blocks/midi/ quote: The MIDI block currently gives you an XMidiGenerator to generate an XML representation of any MIDI file (called XMidi by its author Peter Loeb). There is also the XMidiSerializer to render XMidi back as a MIDI file. I have used XSLT to provide some basic musical manipulations such as transposition, and inversion. Retrograde is harder, but I shall see what I can come up with. Hopefully I shall also add some transformers to generate SVG visualisations of the XMidi, starting with normal western musical notation. MIDI Documentation - Documentation available on the Cocoon Wiki. The link to the wiki was dead when I tried it, so i expect it is dead. Try instead: http://wiki.apache.org/cocoon/MIDI -- http://mail.python.org/mailman/listinfo/python-list
Re: max(), sum(), next()
castironpi wrote: On Sep 5, 9:20 pm, Manu Hack [EMAIL PROTECTED] wrote: On Fri, Sep 5, 2008 at 1:04 PM, castironpi [EMAIL PROTECTED] wrote: On Sep 5, 3:28 am, Manu Hack [EMAIL PROTECTED] wrote: On Thu, Sep 4, 2008 at 4:25 PM, castironpi [EMAIL PROTECTED] wrote: On Sep 4, 2:42 pm, [EMAIL PROTECTED] wrote: David C. Ullrich: At least in mathematics, the sum of the elements of the empty set _is_ 0, while the maximum element of the empty set is undefined. What do you think about my idea of adding that 'default' argument to the max()/min() functions? Bye, bearophile For max and min, why can't you just add your argument to the set itself? The reason max([]) is undefined is that max( S ) is in S. It makes sense. The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. It doesn't make sense to me. What do you set x to? For all x. But then how can you conclude sum([]) = 0 from there? It's way far from obvious. You can define sum([a1,a2,...,aN]) recursively as sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) X, then subtract aN. sum([a1,a2,...a(N-1)])+aN=X sum([a1,a2,...a(N-1)])+aN-aN=X-aN For N=2, we have: sum([a1,a2])=X sum([a1,a2])-a2=X-a2 sum([a1,a2])-a2-a1=X-a2-a1 Since X= a1+ a2, replace X. sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 Or, sum([a1,a2])-a2-a1=0 Apply the recursive definition: sum([a1])+a2-a2-a1=0 And again: sum([])+a1+a2-a2-a1=0 And we have: sum([])=0. This is not necessarily so. The flaw is that you provide a recursive definition with no start value, which is to say it is not a recursive definition at all. A recursive definition should be (for lists where elements can be added, and ignoring pythonic negative indexing): Define 'sum(L)' by a. sum(L[0]) = L[0] b. sum(L[0:i]) = sum(L[0:i-1]) + L[i] ... if i 0 From this you can prove the reverse recursion sum{L[0:k]) = sum(L[0:k+1]) - L[k+1] __only__ if k = 0 It says nothing about the empty list. You could add, as part of the definition, that sum{[]) = 0, or any other value. A rather different approach, not quite simple recursion, would be to start with A. a slicing axiom, something like: for all non-negative integers, a,b,c with a =b = c: sum(L[a:c]) = sum(L[a:b]) + sum(L[b:c]) B. a singleton axiom: for all integers a where L[a] exists: sum(L[a:a]) = L[a] 2a. sum{ -- http://mail.python.org/mailman/listinfo/python-list
Re: max(), sum(), next()
castironpi wrote: On Sep 5, 9:20 pm, Manu Hack [EMAIL PROTECTED] wrote: On Fri, Sep 5, 2008 at 1:04 PM, castironpi [EMAIL PROTECTED] wrote: On Sep 5, 3:28 am, Manu Hack [EMAIL PROTECTED] wrote: On Thu, Sep 4, 2008 at 4:25 PM, castironpi [EMAIL PROTECTED] wrote: On Sep 4, 2:42 pm, [EMAIL PROTECTED] wrote: David C. Ullrich: At least in mathematics, the sum of the elements of the empty set _is_ 0, while the maximum element of the empty set is undefined. What do you think about my idea of adding that 'default' argument to the max()/min() functions? Bye, bearophile For max and min, why can't you just add your argument to the set itself? The reason max([]) is undefined is that max( S ) is in S. It makes sense. The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. It doesn't make sense to me. What do you set x to? For all x. But then how can you conclude sum([]) = 0 from there? It's way far from obvious. You can define sum([a1,a2,...,aN]) recursively as sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) X, then subtract aN. sum([a1,a2,...a(N-1)])+aN=X sum([a1,a2,...a(N-1)])+aN-aN=X-aN For N=2, we have: sum([a1,a2])=X sum([a1,a2])-a2=X-a2 sum([a1,a2])-a2-a1=X-a2-a1 Since X= a1+ a2, replace X. sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 Or, sum([a1,a2])-a2-a1=0 Apply the recursive definition: sum([a1])+a2-a2-a1=0 And again: sum([])+a1+a2-a2-a1=0 And we have: sum([])=0. This is not necessarily so. The flaw is that you provide a recursive definition with no start value, which is to say it is not a recursive definition at all. A recursive definition should be (for lists where elements can be added, and ignoring pythonic negative indexing): Define 'sum(L)' by a. sum(L[0:1]) = L[0] b. sum(L[0:i]) = sum(L[0:i-1]) + L[i] ... if i 1 From this you can prove the reverse recursion sum{L[0:k]) = sum(L[0:k+1]) - L[k+1] __only__ if k = 0 It says nothing about the empty list. You could add, as part of the definition, that sum{[]) = 0, or any other value. A rather different approach, not quite simple recursion, would be to start with A. a slicing axiom, something like: for all non-negative integers, a,b,c with a =b = c: sum(L[a:c]) = sum(L[a:b]) + sum(L[b:c]) B. a singleton axiom: for all integers a where L[a] exists: sum(L[a:a]) = L[a] 2a. sum{ -- http://mail.python.org/mailman/listinfo/python-list
Re: max(), sum(), next()
David C. Ullrich wrote: In article [EMAIL PROTECTED], Mensanator [EMAIL PROTECTED] wrote: On Sep 3, 2:18 pm, Laszlo Nagy [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Empty Python lists [] don't know the type of the items it will contain, so this sounds strange: sum([]) 0 Because that [] may be an empty sequence of someobject: You are right in that sum could be used to sum arbitrary objects. However, in 99.99% of the cases, you will be summing numerical values. When adding real numbers, the neutral element is zero. ( X + 0 = X) It is very logical to return zero for empty sequences. No it isn't. Nothing is not 0, check with MS-Access, for instance: Null + 1 returns Null. Any arithmetic expression involving a Null evaluates to Null. Adding something to an unknown returns an unknown, as it should. It is a logical fallacy to equate unknown with 0. Which has nothing to do with the right value for an empty sum. If they hear about what you said here in sci.math they're gonna kick you out - what do you imagine the universally accepted value of \sum_{j=1}^0 is? For example, the water table elevation in ft above Mean Sea Level is WTE = TopOfCasing - DepthToWater. TopOfCasing is usually known and constant (until resurveyed). But DepthToWater may or may not exist for a given event (well may be covered with fire ants, for example). Now, if you equate Null with 0, then the WTE calculation says the water table elevation is flush with the top of the well, falsely implying that the site is underwater. And, since this particular site is on the Mississippi River, it sometimes IS underwater, but this is NEVER determined by water table elevations, which, due to the CORRECT treatment of Nulls by Access, never returns FALSE calculations. sum([]) 0 is a bug, just as it's a bug in Excel to evaluate blank cells as 0. It should return None or throw an exception like sum([None,1]) does. Same way, if we would have a prod() function, it should return one for empty sequences because X*1 = X. The neutral element for this operation is one. Of course this is not good for summing other types of objects. But how clumsy would it be to use sum( L +[0] ) or if L: value = sum(L) else: value = 0 instead of sum(L). Once again, this is what sum() is used for in most cases, so this behavior is the expected one. Another argument to convince you: the sum() function in SQL for empty row sets returns zero in most relational databases. But of course it could have been implemented in a different way... I believe that there have been excessive discussions about this decision, and the current implementation is very good, if not the best. Best, Laszlo I suppose the following is accepted by statisticians. Here, for reference, here is the what the 'R' statistic package says on the subject 9if you type 'help(sum)' quote Sum of Vector Elements Description sum returns the sum of all the values present in its arguments. Usage sum(..., na.rm = FALSE) Arguments ... numeric or complex or logical vectors. na.rm logical. Should missing values be removed? Details This is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument. If na.rm is FALSE an NA value in any of the arguments will cause a value of NA to be returned, otherwise NA values are ignored. Logical true values are regarded as one, false values as zero. For historical reasons, NULL is accepted and treated as if it were integer(0). Value The sum. If all of ... are of type integer or logical, then the sum is integer, and in that case the result will be NA (with a warning) if integer overflow occurs. Otherwise it is a length-one numeric or complex vector. NB: the sum of an empty set is zero, by definition. References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth Brooks/Cole. -- http://mail.python.org/mailman/listinfo/python-list
Re: max(), sum(), next()
David C. Ullrich wrote: I don't see why you feel the two should act the same. At least in mathematics, the sum of the elements of the empty set _is_ 0, while the maximum element of the empty set is undefined. And both for good reason: (i) If A and B are disjoint sets we certainly want to have sum(A union B) = sum(A) + sum(B). This requires sum(empty set) = 0. (ii) If A is a subset of B then we should have max(A) = max(B). This requires that max(empty set) be something that's smaller than everything else. So we give up on that. Do we give up? Really ? From wikipedia: http://en.wikipedia.org/wiki/Empty_set (Uses wikipedia's LaTeX notation -- I hope those interested are OK with that ) quote Mathematics [edit] Extended real numbers Since the empty set has no members, when it is considered as a subset of any ordered set, then any member of that set will be an upper bound and lower bound for the empty set. For example, when considered as a subset of the real numbers, with its usual ordering, represented by the real number line, every real number is both an upper and lower bound for the empty set.[3] When considered as a subset of the extended reals formed by adding two numbers or points to the real numbers, namely negative infinity, denoted -\infty\!\,, which is defined to be less than every other extended real number, and positive infinity, denoted +\infty\!\,, which is defined to be greater than every other extended real number, then: \sup\varnothing=\min(\{-\infty, +\infty \} \cup \mathbb{R})=-\infty, and \inf\varnothing=\max(\{-\infty, +\infty \} \cup \mathbb{R})=+\infty. That is, the least upper bound (sup or supremum) of the empty set is negative infinity, while the greatest lower bound (inf or infimum) is positive infinity. By analogy with the above, in the domain of the extended reals, negative infinity is the identity element for the maximum and supremum operators, while positive infinity is the identity element for minimum and infimum. -- http://mail.python.org/mailman/listinfo/python-list
Re: max(), sum(), next()
David C. Ullrich wrote: In article [EMAIL PROTECTED], Ken Starks [EMAIL PROTECTED] wrote: David C. Ullrich wrote: I don't see why you feel the two should act the same. At least in mathematics, the sum of the elements of the empty set _is_ 0, while the maximum element of the empty set is undefined. And both for good reason: (i) If A and B are disjoint sets we certainly want to have sum(A union B) = sum(A) + sum(B). This requires sum(empty set) = 0. (ii) If A is a subset of B then we should have max(A) = max(B). This requires that max(empty set) be something that's smaller than everything else. So we give up on that. Do we give up? Really ? Erm, thanks. I was aware of all that below. If we're being technical what's below is talking about the sup and inf, which are not the same as max and min. More relevant to the present context, I didn't mention what's below because it doesn't seem likely that saying max([]) = -infinity and min([]) = +infinity is going to make the OP happy... Of course you were aware, I have seen enough of your posts to know that. And I agree that, whatever Wikipedia seems to imply, max and supremum should be distiguished. It was your prelude, At least in mathematics ... that made me prick up my ears. So I couldn't resist responding, without _any_ malice I assure you. Cheers, Ken. -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing to ms excel
John Machin wrote: On Aug 31, 11:32 am, Marin Brkic [EMAIL PROTECTED] wrote: Is there a way to access google groups through a similiar interface program as a newsreader. I don't know (question has never arisen before). Never used them before, and getting a lot of messages to my email every day does not sound very appealing to me. Either (1) you have not looked at the messages at the link that I gave you or (2) your idea of a lot of messages every day differs wildly from mine. Email alternatives are (a) one message per posting (b) daily digest (c) none (use your web browser). HTH, John I use thunderbird for private email, mailing lists and newsgroups. It is easy enough to set up filters to divert messages from specific mailing lists to their own directory. Is this adequate for your needs ? (You do get the whole message, not just the header ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing to ms excel
Marin Brkic wrote: snip ... lots Actually, that might work. What I was needing (aiming for) was a way to write to excel 2003 files. Formatting is not necessary, since what I'm trying to write is some tabular data; results from fortran-python simulation (I can explain, but the details seem irrelevant for this case). I'm trying to avoid the text file - import to excel - mechanism, since there is quite a lot of files written. Best regards Marin Again, not python ( hope I don't start a flame war, I've just joined the list John Machin suggested--it looks very interesting). I have used Apache Cocoon for this kind of task. Everything important happens server-side. Your raw data could be stored in a database, or a flat file, or not stored persistently at all--just be created as a virtual stream if you can use your python/fortran utility as a web service. It goes into the cocoon pileline, and is first turned into XML. Then it is turned into other XML (in this case most likely the gnumeric format). Lastly it is serialized into Excel format, given the appropriate Mime type, and sent to your browser. It is only when it gets to the Browser, that a decision is made as to what to do with it. You can set up your Browser to open it is MS Excel (whichever one you have), Open Office, Gnumeric, or whatever. Most of them will cope with it perfectly, and will be able to save it locally in their most up-to-the-minute variation, if that is what you want. Cheers, Ken. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check is something is a list or a dictionary or a string?
George Sakkis wrote: On Aug 29, 12:16 pm, [EMAIL PROTECTED] wrote: Hi, How to check if something is a list or a dictionary or just a string? Eg: for item in self.__libVerDict.itervalues(): self.cbAnalysisLibVersion(END, item) where __libVerDict is a dictionary that holds values as strings or lists. So now, when I iterate this dictionary I want to check whether the item is a list or just a string? if isinstance(item,basestring): # it's a string ... else: # it should be a list # typically you don't have to check it explicitly; # even if it's not a list, it will raise an exception later anyway if you call a list-specific method HTH, George For a bit more explanation see, for example, http://evanjones.ca/python-utf8.html (Quote) Working With Unicode Strings Thankfully, everything in Python is supposed to treat Unicode strings identically to byte strings. However, you need to be careful in your own code when testing to see if an object is a string. Do not do this: if isinstance( s, str ): # BAD: Not true for Unicode strings! Instead, use the generic string base class, basestring: if isinstance( s, basestring ): # True for both Unicode and byte strings -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check is something is a list or a dictionary or a string?
josh logan wrote: But this changes with Python 3, right? right! see http://docs.python.org/dev/3.0/whatsnew/3.0.html (quote) Strings and Bytes * There is only one string type; its name is str but its behavior and implementation are like unicode in 2.x. * The basestring superclass has been removed. The 2to3 tool replaces every occurrence of basestring with str. * PEP 3137: There is a new type, bytes, to represent binary data (and encoded text, which is treated as binary data until you decide to decode it). The str and bytes types cannot be mixed; you must always explicitly convert between them, using the str.encode() (str - bytes) or bytes.decode() (bytes - str) methods. * All backslashes in raw strings are interpreted literally. This means that Unicode escapes are not treated specially. * PEP 3112: Bytes literals, e.g. babc, create bytes instances. * PEP 3120: UTF-8 default source encoding. * PEP 3131: Non-ASCII identifiers. (However, the standard library remains ASCII-only with the exception of contributor names in comments.) * PEP 3116: New I/O Implementation. The API is nearly 100% backwards compatible, but completely reimplemented (currently mostly in Python). Also, binary files use bytes instead of strings. * The StringIO and cStringIO modules are gone. Instead, import io.StringIO or io.BytesIO. * '\U' and '\u' escapes in raw strings are not treated specially. On Aug 30, 7:15 am, Ken Starks [EMAIL PROTECTED] wrote: George Sakkis wrote: On Aug 29, 12:16 pm, [EMAIL PROTECTED] wrote: Hi, How to check if something is a list or a dictionary or just a string? Eg: for item in self.__libVerDict.itervalues(): self.cbAnalysisLibVersion(END, item) where __libVerDict is a dictionary that holds values as strings or lists. So now, when I iterate this dictionary I want to check whether the item is a list or just a string? if isinstance(item,basestring): # it's a string ... else: # it should be a list # typically you don't have to check it explicitly; # even if it's not a list, it will raise an exception later anyway if you call a list-specific method HTH, George For a bit more explanation see, for example, http://evanjones.ca/python-utf8.html (Quote) Working With Unicode Strings Thankfully, everything in Python is supposed to treat Unicode strings identically to byte strings. However, you need to be careful in your own code when testing to see if an object is a string. Do not do this: if isinstance( s, str ): # BAD: Not true for Unicode strings! Instead, use the generic string base class, basestring: if isinstance( s, basestring ): # True for both Unicode and byte strings -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing to ms excel
Marin Brkic wrote: Hello all, please, let me apologize in advance. English is not my first language (not even my second one), so excuse any errors with which I'm about to embarass myself in front of the general public. Second, I'm relatively new to python, so sorry if this seems like a stupid question. I'm trying to find a way to write data to excel cells (or to be more specific to an .xls file), let's say for the sake of argument, data readen from a file (although it will be calculated in the process). I've been searching, but couldn't find any examples which allows that. Do anyone knows of any ? All help is appreciated on this matter. Tutorials? Anything ... Best regards Marin Not specific to python, but if you have a recent version of excel, you could write to the Excel xml format (if not, you could consider the (or one of the) gnumeric xml formats. The Excel format is verbose, but you can copy and paste most of it. The critical bit you need your software to write looks something like this: Worksheet ss:Name=Sheet1 Table ss:ExpandedColumnCount=2 ss:ExpandedRowCount=5 x:FullColumns=1 x:FullRows=1 Row CellData ss:Type=Stringnumber/Data/Cell CellData ss:Type=Stringsquare/Data/Cell /Row Row CellData ss:Type=Number1/Data/Cell CellData ss:Type=Number1/Data/Cell /Row Row CellData ss:Type=Number2/Data/Cell CellData ss:Type=Number4/Data/Cell /Row Row CellData ss:Type=Number3/Data/Cell CellData ss:Type=Number9/Data/Cell /Row Row CellData ss:Type=Number4/Data/Cell CellData ss:Type=Number16/Data/Cell /Row /Table WorksheetOptions xmlns=urn:schemas-microsoft-com:office:excel Selected/ Panes Pane Number3/Number ActiveRow5/ActiveRow ActiveCol1/ActiveCol /Pane /Panes ProtectObjectsFalse/ProtectObjects ProtectScenariosFalse/ProtectScenarios /WorksheetOptions /Worksheet -- http://mail.python.org/mailman/listinfo/python-list
Re: [1,2,3] exactly same as [1,2,3,] ?
[EMAIL PROTECTED] wrote: x=[1,2,3] and x=[1,2,3,] are exactly the same, right? I'm generating some python data, and it's less error prone to not treat the last element specially, but I want to be sure I'm generating an equivalent data structure. Many TIA! Mark x=[1,2,3,] repr(x) [1,2,3] -- http://mail.python.org/mailman/listinfo/python-list
Re: class definition syntax
harryos wrote: hi i have seen some class definitions like class MyClass(object): def __init__(self): what does the object keyword inside the braces in MyClass() mean? Has it got any significance? thanks in advance harry It is a syntax used for 'new type' classes, not so new any more. If you google that phrase, you get many references. Here is a tutorial dating back to 2005. http://www.geocities.com/foetsch/python/new_style_classes.htm -- http://mail.python.org/mailman/listinfo/python-list
Re: [Q] How to ignore the first line of the text read from a file
[EMAIL PROTECTED] wrote: Hello, I am new to Python and have one simple question to which I cannot find a satisfactory solution. I want to read text line-by-line from a text file, but want to ignore only the first line. I know how to do it in Java (Java has been my primary language for the last couple of years) and following is what I have in Python, but I don't like it and want to learn the better way of doing it. file = open(fileName, 'r') lineNumber = 0 for line in file: if lineNumber == 0: lineNumber = lineNumber + 1 else: lineNumber = lineNumber + 1 print line Can anyone show me the better of doing this kind of task? Thanks in advance. LineList=open(filename,'r').readlines()[1,] for line in Linelist: blah blah -- http://mail.python.org/mailman/listinfo/python-list
Re: Private attribute
Steven D'Aprano wrote: snip def SomeClass(object): _gridsize = 0.8 The leading underscore tells callers that they change the attribute at their own risk. An even more Pythonic approach is to write your class that makes no assumptions about gridsize, and thus explicitly supports any reasonable grid size. The parent class, makes no assumption about grid-size, and I have put a great deal of functionality there. The methods of the derived class that depend on a gridsize of 8mm are mostly concerned with standard LaTeX glyphs (from a specific font) at standard LaTeX sizes. I am fitting a small subset of them into my grid by hand, in a way that I don't think could be easily automated even if I use the metric information. Not impossible, just too much hastle. The general rationale of the project is 'pen-and-ink' algorithms for arithmetic, on quadrille paper. It is to create figures that will be imported into LaTeX later. (By the way, it is perfectly easy to re-scale the figure after the digits, carry-figures, and other glyphs are placed. So long as you don't mind the font-size within the figure to be out of kilter with the font-size of the main run of LaTeX text.) I hope this explains why I have decided on a Read-only attribute, the first one ever, apart from a quick try-out when I started with Python. And that was when Guido was still in Amsterdam. -- http://mail.python.org/mailman/listinfo/python-list
Private attribute
I have a class with an attribute called 'gridsize' and I want a derived class to force and keep it at 0.8 (representing 8mm). Is this a correct, or the most pythonic approach? def __getattr__(self,attrname): if attrname == 'gridsize': return 0.8 def __setattr__(self,attrname,value): if attrname == 'gridsize': pass else: self.__dict__[attrname]=value # Cheers, Ken. -- http://mail.python.org/mailman/listinfo/python-list
Re: Private attribute
Ken Starks wrote: I have a class with an attribute called 'gridsize' and I want a derived class to force and keep it at 0.8 (representing 8mm). Is this a correct, or the most pythonic approach? def __getattr__(self,attrname): if attrname == 'gridsize': return 0.8 def __setattr__(self,attrname,value): if attrname == 'gridsize': pass else: self.__dict__[attrname]=value # Cheers, Ken. Perhaps I should mention the alternative I had in mind: ### class xyz: def __init__(self): self.__dict__['a'] = 123 self.b=456 def __setattr__(self,attrname,value): if attrname == 'a': pass else: self.__dict__[attrname]=value # __getattr__() not redefined. -- http://mail.python.org/mailman/listinfo/python-list
Re: Private attribute
André wrote: On Aug 25, 3:47 pm, Ken Starks [EMAIL PROTECTED] wrote: I have a class with an attribute called 'gridsize' and I want a derived class to force and keep it at 0.8 (representing 8mm). Is this a correct, or the most pythonic approach? def __getattr__(self,attrname): if attrname == 'gridsize': return 0.8 def __setattr__(self,attrname,value): if attrname == 'gridsize': pass else: self.__dict__[attrname]=value # Cheers, Ken. Why not make gridsize a property with no set method? André Thanks for the suggestion, André. I admit I haven't used properties, and had to look them up. Pretty cool indeed ! But an extra unnecessary level of complexity for my needs here, I feel. They are _certainly_ going to become part of my Python toolkit. Cheers, Ken. -- http://mail.python.org/mailman/listinfo/python-list
Re: Private attribute
Marc 'BlackJack' Rintsch wrote: On Mon, 25 Aug 2008 21:44:49 +0100, Ken Starks wrote: def __getattr__(self,attrname): if attrname == 'gridsize': return 0.8 def __setattr__(self,attrname,value): if attrname == 'gridsize': pass else: self.__dict__[attrname]=value […] I admit I haven't used properties, and had to look them up. Pretty cool indeed ! But an extra unnecessary level of complexity for my needs here, I feel. Compare this with your approach above and point out the extra complexity please: @property def gridsize(self): return 0.8 Ciao, Marc 'BlackJack' Rintsch mea culpa. As i mentioned, I haven't used them before. I have already changed my class Foo: to class Foo(object): and I'll do the rest tomorrow. -- http://mail.python.org/mailman/listinfo/python-list
Re: Filling in Degrees in a Circle (Astronomy)
tom wrote: Both scipy and matplotlib are not part of the standard Python distribution so they would need to be installed separately. Scipy is useful for scientific data analysis, and matplotlib is useful for making plots. For a review of a really nice looking wrapper around lots of open-source mathematical tools, look here: http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/ it is called SAGE and includes both of the above and lots more goodies. for sage itself: http://www.sagemath.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I organize my Python application code?
Fredrik Lundh wrote: Dudeja, Rajat wrote: And my problem is that I don't have an understanding of how the code in Python is generally organized, in case my code spans multiple files, modules, etc. I've been using C/C++ althrough my life on Linux and Visaul Studio, so the way their code is organized in a group of header files, source files, etc, I'm looking for a similar way in Python way or an approach to organize my python GUI application code? A Python program consists of a script file (the py file you run to start the program), and usually one or more additional module files (py files that you import). The latter can be organized in packages, where appropriate. There's also a search path (sys.path) that you can modify in various ways (including from within the program) if you want to fetch modules from different locations. That's all there is; there's no header files or declaration files or explicitly maintained object files etc; the program itself is just a bunch of Python files. To learn more about this, the modules section in the tutorial is a good start: http://docs.python.org/tut/node8.html Looking at the structure of a few existing projects might also be helpful. /F I would simply add that if your python script produces one or more output files (for example a text or graphic file) you might want to have an 'output' directory in your project. Some people use a 'src' directory, but that is not nearly as neccessary as in a complied language. In Eclipse, if you do produce output files, make them auto-refresh. -- http://mail.python.org/mailman/listinfo/python-list
Re: You advice please
Hussein B wrote: Hey, I'm a Java/Java EE developer and I'm playing with Python these days. I like the Python language so much and I like its communities and the Django framework. My friends are about to open a Ruby/Rails shop and they are asking me to join them. I don't know what, sure I'm not leaving Java, but they are asking me to stop learning Python and concentrate on Ruby/Rails. The sad fact (at least to me), Ruby is getting a lot of attention these days. Why Python isn't getting this attention although is a much more mature language and it is used by many big, big names? And do I dare to say it is much more charming? What do you think of Ruby/Rails? do they worth learning and working with? Any way, I'm not leaving Python and I will try to study it every time I get a chance... Thanks. On the whole, I think python gets more attention, but that doesn't not mean you should ignore Ruby, at least to a 'dabble-in' level. To me, the main reason for learning ruby is because it is the scripting language for Google sketchup. And now it looks as if I shall wish to learn another little language, at least to 'dabble-in' level: Lua, because it is going to srcipt a new variation in the TeX world. But neither has a cat-in-hell's chance of replacing python anytime soon, as far as I am concerned. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking out a module for Subversion
Dudeja, Rajat wrote: Hi, I'm new to Python. I only have read Byte of Python by Swaroop C H just to be familiar with sytax of python. I've installed Python 2.5 from Active State and using its PythonWin Editor / interpreter. This, unfortunaltely, does not help in debugging. I'm looking for an open source IDE / editor that has source level debugging. Please suggest some tool. I'm intending to write a testing tool that uses Subversion. Is there some module available for subversion, out of the box, that I can import in my script? Regards, Rajat I've recently started using Eclipse for my python projects, and I'm pretty happy with it. you can easily get: + syntax highlighting + code collapsing + code completion + breakpoints, etc + TODO: reminders + unit tests and, of course, you can also use subversion with Eclipse. + unit tests -- http://mail.python.org/mailman/listinfo/python-list
Re: Replace value of node using getElementsByTagName
Ouray Viney wrote: Xml ib8.4.27.5/ib python from xml.dom import minidom xmldoc = minidom.parse('C:\TestProfile.xml') xmldoc ibNodeList = xmldoc.getElementsByTagName(ib) firstChild = xmldoc.firstChild for node in xmldoc.getElementsByTagName('ib'): # visit every node ib print node.toxml() node.replaceChild(ib8.4.27.5/ib,node) Error Traceback (most recent call last): File C:\Python25\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py, line 310, in RunScript exec codeObject in __main__.__dict__ File C:\Documents and Settings\vineyo\Desktop\parseXml.py, line 17, in module node.firstChild.replaceChild(ib8.4.27.5/ib,node.firstChild) File C:\Python25\lib\xml\dom\minidom.py, line 899, in replaceChild self.nodeName + nodes do not have children) HierarchyRequestErr: #text nodes do not have children Question: Is there an easy way to replace the node value of ib? Perhaps I am trying to use the wrong python XML library? Any help would be greatly appreciated. I use 4suite myself. see section 3.2.1 of the manual: 3.2.1 What about getElementsByTagName()? The getElementsByTagName() method isn't supported, because there are better options. In particular, you can just use XPath: doc.xpath(u//tagname) For more possibilities, see getElementsByTagName Alternatives. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestions for creating a PDF table
Kirk Strauser wrote: Short question: Is there a good library for generating HTML-style tables with the equivalent of colspans, automatically sized columns, etc. that can render directly to PDF? Longer question: I'm re-doing a big chunk of locally-written code. I have a report-generating function that takes a list of lists of lists as input and returns either a PDF, an HTML table, or an Excel spreadsheet as requested. For example, input might look like: makereport('html', headers=['Invoice number', 'Customer', 'Price'], data=[ [['123', 'John Doe', '$50.00'], ['Ordered on 2008-01-01 via the website']], [['124', 'Peter Bilt', '$25.99'], ['Mail via African swallow']] ]) snip Now, I have a similar transformation to PDF via pdflatex. This works fairly well but requires a bunch of temp files and subprocesses, and I've never been 100% happy with the LaTeX output (you have to calculate your own column widths, for instance). Since I plan to re-write this anyway, I'd like to find a more widely used library if one was available. snip Short answer: LaTeX should be good. Use XML source; XSLT to TeXML; TeXML to LaTeX ( uses a python program); compile to PDF. Longer answer: Can you provide a minimal example of the kind of LaTeX source you would ideally like ? If not, your problem is with LaTeX itself, which has if anything __too_many__ ways of controlling tables rather than inadequate ways. If so, we may be able to help with the rather arcane transformation into TeXML format. As for all the temp files that LaTeX creates, they are easily dealt with using a makefile or whatever. Bye for now, Ken -- http://mail.python.org/mailman/listinfo/python-list
Re: Keg - A python web framework
Daniel Fetchinson wrote: I've been working on a python web framework which I think might be of interest to you. Details may be found at http://code.google.com/p/keg/wiki/Concept. All suggestions or comments will be greatly appreciated. I fail to see what the advantages of your framework are over django or turbogears. The description you give on the above url doesn't really help as all the goals you state for your project are solved by both django and turbogears. I wouldn't want to be too discouraging but it seems you are led by the NIH principle which is not a really useful one in the open source world. You can expect exactly 0 users and no appreciation for your efforts which will/can lead to frustration and bad health. Contributing to an already existing and mature framework like django and turbogears can/will be on the other hand rewarding. Cheers, Daniel The goal I would like for your webapp project is: Do in Python what 'Apache Cocoon' does in Java There is already a python cocoon project, in hibernation. Perhaps you could join it and wake it up! http://pypi.python.org/pypi/pycoon -- http://mail.python.org/mailman/listinfo/python-list
Re: Decimals not equalling themselves (e.g. 0.2 = 0.2000000001)
CNiall wrote: I am very new to Python (I started learning it just yesterday), but I have encountered a problem. I want to make a simple script that calculates the n-th root of a given number (e.g. 4th root of 625--obviously five, but it's just an example :P), and because there is no nth-root function in Python I will do this with something like x**(1/n). However, with some, but not all, decimals, they do not seem to 'equal themselves'. This is probably a bad way of expressing what I mean, so I'll give an example: 0.5 0.5 0.25 0.25 0.125 0.125 0.2 0.20001 0.33 0.33002 As you can see, the last two decimals are very slightly inaccurate. However, it appears that when n in 1/n is a power of two, the decimal does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 and not 0.20001? This discrepancy is very minor, but it makes the whole n-th root calculator inaccurate. :\ As everyone else has pointed out, this is likely to be a 'floating point' error. what they don't mention is that you don't actually have to use floating point at all. For example, some numbers, m, can be represented as the product of rational powers of primes. Its not that easy to add and subtract them, but multiplication, division, raising to the nth power and taking the nth root, are all easy. (m and n positive integers). There certainly are algorithms that will evaluate the 'fourth root of 625' as precisely 5. More generally, there are algorithms that will guarantee to return either + the exact answer as a float (if it is one) + the nearest or second nearest float to the actual answer depending on your choice of: - round towards zero - round away from zero - round towards positive infinity - round towards negative infinity - round depending on parity of next digit It is the representation of the numbers during the intermediate stages that is critical. You trade-off speed against accuracy. You may well find, if you do this, that the results returned by built-in mathematical functions DO NOT return either the nearest or the second nearest float to the actual answer. It depends on the underlying C library that was used, and its programmers' choices. So your home-rolled 'nth power' function would add a little something to the standard functionality of the language, and writing it would add to your understanding of the language too. -- http://mail.python.org/mailman/listinfo/python-list
Re: derivative in numpy
[EMAIL PROTECTED] wrote: Hi, I am looking to do a simple derivative. I would expect such a function to be available in numpy, but can't find it. I have written my own, but just curious if anybody knows of such function in numpy. Cheers, Kim numpy and much more are wrapped together in 'sage' and you should get the functionality you need there. For a review, see: http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/ -- http://mail.python.org/mailman/listinfo/python-list
Re: derivative in numpy
Ken Starks wrote: [EMAIL PROTECTED] wrote: Hi, I am looking to do a simple derivative. I would expect such a function to be available in numpy, but can't find it. I have written my own, but just curious if anybody knows of such function in numpy. Cheers, Kim numpy and much more are wrapped together in 'sage' and you should get the functionality you need there. For a review, see: http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/ Sorry, the review isn't very useful. for something more focused on your request, see: http://www.sagemath.org/doc/tut/node13.html -- http://mail.python.org/mailman/listinfo/python-list
Re: % sign in python?
Terry Reedy wrote: korean_dave wrote: What does this operator do? Specifically in this context test.log( [[Log level %d: %s]] % ( level, msg ), description ) (Tried googling and searching, but the % gets interpreted as an operation and distorts the search results) Having seen a number of comments like this over the years (about the difficulty of searching for symbol meanings), I just started, last night, a symbol index listing nearly all Python syntax uses of non-alpha-or-digit ascii symbols. When I finish and upload it somewhere, I will post an announcement with the link. tjr This will be excellent, Terry. For the present case, perhaps we should also point out that in python 3.0: Note The formatting operations described here are obsolete and may go away in future versions of Python. Use the new String Formatting in new code. (Taken from the provisional documentation at: http://docs.python.org/dev/3.0/library/stdtypes.html#old-string-formatting ) -- http://mail.python.org/mailman/listinfo/python-list
Eclipse, Pydev, question
I have a small project for further development in eclipse, using the pyDev plug-in. I am working on foo.py and bar.pyc is also in the directory. bar.py is not in the directory; it is someone else's (confidential) file, and I don't get the python source. Can I run bar.pyc from eclipse ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Measure class, precision, significant digits, and divmod()
Ethan Furman wrote: Hey all. snip As I have mentioned before, I am making this Measure class for two reasons: experience with unit testing, I like playing with numbers, I am unaware of anything like this having yet been done (okay, three reasons ;). snip Any and all feedback welcome, particularly from anyone who might actually use the Measure class. ;) ~Ethan I have been following this thread with interest, because i am doing something similar, namely writing python to provide myself with experience with unit tests and i like playing with numbers. In my case the numbers are 'long rationals' (infinite precision) and will include both floats, the decimal type, extended 'decimals' -- i.e. possibly with a repeating expansion (or in any base) -- and finite continued fractions as derived classes. I also hope to deal with repeating continued fractions later. +++ My principal interest in your work, however, is in the use of unit tests as a pedagogical method of teaching programming, whether self-taught or taught by an instructor. The students would be taught how to __run__ a unit test-suite at as early an opportunity as possible. I can't see why an eleven or twelve year old should not be able to cope with it in hour one or two of a carefully structured course. What is needed for such an approach is a copy--in a public place--of your unit tests for all methods that are really part of the funtionality; together with blanked-out definitions for them (i.e just the first line, any in-code documentation, and 'pass' ). You would not include any 'internal' methods that are merely the way __you__ happened to achieve the result. The programming 'exercise' would then be for the students, or groups of students, to roll their own version until their code passed all the unit tests. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary bidirectional
Dennis Lee Bieber wrote: On Sun, 13 Jul 2008 16:21:11 -0700 (PDT), Kless [EMAIL PROTECTED] declaimed the following in comp.lang.python: I need a dictionary where get the result from a 'key' (on left), but also from a 'value' (on right), how to get it? I know that dictionaries aren't bidirectional, but is there any way without use two dictionaries? Just out of curiosity... What do you expect to have returned from... aDict = { one : two, three : four, What? : two } when looking for the value two? In a dictionary, the /keys/ are unique... but the /values/ can be duplicates. I wonder if anyone has implemented an 'equivalence class' class (for finite sets) based on this. Obviously the relation defined by k1~k2 iff D[k1] == D[k2] does partition the set of all keys as an equivalence class. So ... as a kind of inverse you could return a set, a subset of the keys. How you would get a canonical representative of that set is a different matter, of course. Unless, as in the OP's case, it is a singleton set. It would seem more efficient to do this when a key-value pair is added or removed from the original dictionary rather than iterating over all the keys each time you used it. -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL: Transparent PNGs and im.paste: ValueError: bad transparency mask
Durand wrote: I posted this too soon. Converting the images to png with image magick's convert did the trick...However, I'm still not sure why I need to convert the images in the first place. Are there different types of PNGs? http://en.wikipedia.org/wiki/Portable_Network_Graphics#Transparency_of_image -- http://mail.python.org/mailman/listinfo/python-list
Re: sage vs enthought for sci computing
sturlamolden wrote: On 7 Jul, 22:35, [EMAIL PROTECTED] wrote: Hello, I have recently become interested in using python for scientific computing, and came across both sage and enthought. I am curious if anyone can tell me what the differences are between the two, since there seems to be a lot of overlap (from what I have seen). If my goal is to replace matlab (we do signal processing and stats on physiological data, with a lot of visualization), would sage or enthought get me going quicker? I realize that this is a pretty vague question, and I can probably accomplish the same with either, but what would lead me to choose one over the other? Thanks! I work in neuroscience, and use Python of signal processing. I've used Matlab before. Python is just better. I do not use either Sage or Enthought. Instead I have istalled a vanilla Python and the libraries I need. The most important parts are: - Python 2.5.2 - NumPy - SciPy - Matplotlib - wxPython - pywin32 - PIL - Cython - PyOpenGL - mpi4py - processing module - gfortran and gcc (not a Python library, but I need a C and Fortran compiler) Less important stuff I also have installed: - Twisted - PyGame - MySQL and mysqldb - Python for .NET (http://pythonnet.sourceforge.net) - VideoCapture I would add RPy for luck! The Rproject stats package seems to have attracted a lot of medical users, and this is a python interface. I'm not entirely sure what is the advantage of a python wrapper over R, (compared with the stand-alone Rproject language), but presumably it would be to combine its functionality with that of some of the python libraries above. Anyway, you get lots of graphics for exploratory data analysis, high quality stats, the ability to write scripts. The RPy is on sourceforge: http://rpy.sourceforge.net/ the Rproject itself is at: http://www.r-project.org/ and there is a whole CRAN (Comprehensive R archive network) -- http://mail.python.org/mailman/listinfo/python-list
Re: python beginner
cna wrote: Hi all and one, how may i learn python. is there any other website except python.org For several video series, follow the link from python.org to the ShowMeDo site. http://www.python.org/doc/av/5minutes/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting a path from a file object
Andrew Fong wrote: Newbie question: Let's say I open a new file for writing in a certain path. How do I get that path back? Example: f = open('/some/path/file.ext') some_function(f) '/some/path/file.ext' Does some_function(f) already exist? And if not, how would I define it? -- Andrew Read about f.name which is a kind of read-only attribute with caveats in the documentation: http://docs.python.org/lib/bltin-file-objects.html -- http://mail.python.org/mailman/listinfo/python-list
How do I unit-test a specific case of a home-rolled exception ?
I'm a bit new to both home-made exceptions and unit tests, so sorry if I'm just being stupid or doing it totally wrong. I have an exception class, and I want to check that a particular instance of it has been raised; or more accurately that one is raised that is equal to an instance I specify. In the example below, I can check that a 'LongRationalError' is raised, but I want to check that it is specifically a 'LongrationalError('1') or a 'LongRationalError('2') How do I do that? + The critical line is: self.assertRaises(LongRationalError, LongRational, 1, 7) and it doesn't work if i put: self.assertRaises(LongRationalError('2'), LongRational, 1, 7) +++ import unittest class LongRationalError(Exception): Message={} Message['1']=numerator must be an integer Message['2']=denominator must be an integer def __init__(self, code): self.code = str(code) def __str__(self): k = self.code if k in self.Message.keys(): v = self.Message[k] else: v = '...no description provided' return Long Rational error #%s: %s % (k,v) class LongRational(): import types allowed = [types.IntType,types.LongType] def __init__(self,a,b): if type(a) not in self.allowed: raise LongRationalError(1) if type(b) not in self.allowed: raise LongRationalError(2) if b == 0: raise ValueError(supplied denominator must be non-zero) if a == 0: b = 1 self.numerator=long(a) self.denominator=long(b) class TestLongRationals(unittest.TestCase): def test_init(self): # if the supplied denominator == zero, we should get a ValueError # if the supplied numerator or denominator is anything but an integer or a # long we should # raise a LongRational exception from types import LongType e = LongRational(123,456) self.assertRaises(ValueError, LongRational, 1, 0) self.assertRaises(LongRationalError, LongRational, 1.0, 2) self.assertRaises(LongRationalError, LongRational, 3, 4.0) self.assertRaises(LongRationalError, LongRational, 1, 7) self.assertEquals(e.numerator,123) self.assertEquals(e.denominator,456L) self.assertEquals(type(e.numerator),LongType) self.assertEquals(type(e.denominator),LongType) # special case: denominator of zero rational forced to unity. self.assertEquals(LongRational(0,24).denominator, 1L) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestLongRationals) unittest.TextTestRunner(verbosity=2).run(suite) -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I unit-test a specific case of a home-rolled exception ?
Peter Otten wrote: Ken Starks wrote: I have an exception class, and I want to check that a particular instance of it has been raised; or more accurately that one is raised that is equal to an instance I specify. In the example below, I can check that a 'LongRationalError' is raised, but I want to check that it is specifically a 'LongrationalError('1') or a 'LongRationalError('2') How do I do that? (all untested) try: LongRational(1, 7) except LongRationalError, e: self.assertEquals(e.code, 2) else: self.fail() Alternatively you can subclass LongRationalError... class LongRationalError(Exception): pass class LongRationalDenominatorError(LongRationalError): pass class LongRationalNumeratorError(LongRationalError): pass ...and then check for the specialized exception: self.assertRaises(LongRationalDenominatorError, LongRational, 1, 7) Personally, I'd probably throw a plain old TypeError for incompatible types of both numerator and denominator. Peter Thanks Peter, that answers my question nicely. I rather thought I would need a try .. except structure in my unit-test itself. -- http://mail.python.org/mailman/listinfo/python-list
Re: binary number format ? format character %b or similar.
Mensanator wrote: On Jun 22, 4:07�pm, Ken Starks [EMAIL PROTECTED] wrote: weheh wrote: I don't know if you found this example: http://www.daniweb.com/code/snippet285.html Thanks for that. The offerings are very similar to the algorithms I wrote myself. It wasn't the solution I was after,really; that's easy. It was whether anything had found its way into the standard library. Isn't that coming in Python 3.0? Thanks for the tip! following which, I found information at: http://docs.python.org/dev/3.0/library/string.html#formatstrings You could also use gmpy, which has a lot of other bit-functionality in addition to displaying them. Yes, that'll be useful. Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
binary number format ? format character %b or similar.
I'm was wanting to format a positive integer in binary, and not finding it--to my surprise--I rolled my own version. Is this already in python, or have I missed it somewhere? I have Googled around a bit, and found a few threads on the subject, but they all seem to fizzle out. (e.g. : INPUT 35, OUTPUT 100011 ) -- http://mail.python.org/mailman/listinfo/python-list
Re: binary number format ? format character %b or similar.
weheh wrote: I don't know if you found this example: http://www.daniweb.com/code/snippet285.html Thanks for that. The offerings are very similar to the algorithms I wrote myself. It wasn't the solution I was after,really; that's easy. It was whether anything had found its way into the standard library. -- http://mail.python.org/mailman/listinfo/python-list
Re: Most effective coding.. IDE question.
dave wrote: Hello everyone, I'm a beginning self-taught python student. Currently, I work out my code within IDLE then when I have a version that I like, or that's working, I move it over to a new window and save it. I've been playing w/ Komodo IDE lately, and while it's nice, what I don't like is the one line at a time (produced by hitting up-arrow) in the shell. In IDLE, ctrl-p can reproduce a whole function or class - opposed to only the last line in Komodo. Is my IDLE method common? Or am I simply creating more of a headache for myself? What do you recommend? I'm not that advanced and don't need anything fancy. I'm on OS X. Thanks! Dave For th simplest work, you could try skite as an editor; it takes you code in on window, and sends the output to another when you press F5. But--'not advanced' or not--I would suggest you look forward to the time when you will need version control, unit tests, and other utilities of a more comprehensive environment. Take a look at Eclipse, for example. For several sceencasts, python and eclipse included: http://showmedo.com/videos/programming_tools -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting Math Problem
BEES INC wrote: I've been awfully busy programming lately. My Django-based side project is coming along well and I hope to have it ready for use in a few weeks. Please don't ask more about it, that's really all I can say for now. Anyways, I came across an interesting little math problem today and was hoping some skilled programmers out there could come up with a more elegant solution than mine. Problem: Star Ratings People can rate cheeseburgers on my website with a star rating of 0-5 stars (whole stars only), 5 being mighty tasty and 0 being disgusting. I would like to show the average of everyone's ratings of a particular cheeseburger to the nearest half star. I have already calculated the average rating as a float (star_sum) and the total number of people that rated the particular cheeseburger (num_raters). The result should be stored as a float in a variable named stars. My Solution (in Python): # round to one decimal place and # separate into whole and fractional parts parts = str(round(star_sum/num_raters, 1)).split('.') whole = int(parts[0]) frac = int(parts[1]) if frac 3: ___frac = 0 elif frac 7: ___frac = 0 ___whole += 1 else: ___frac = 5 # recombine for a star rating rounded to the half stars = float(str(whole)+'.'+str(frac)) Mmmm… In-N-Out Burgers… Please reply if you've got a better solution. for raw in [0.05 * n for n in range (41)]: rounded = round(2.0*raw)/2.0 print %0.2f -- %0.2f % (raw,rounded) -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing HTML
[EMAIL PROTECTED] wrote: I've searched the standard library docs, and, while there are a couple options for *reading* HTML from Python, I didn't notice any for *writing* it. Does anyone have any recommendations (particularly ones not listed on PyPI)? Thanks My approach is usually to write the data-load in XML rather than directly in HTML, and then use XSLT to produce the (X)HTML. You can do the whole of this, or just the second part, using FourSuite. If the XML, later, needs to be changed, you can use FourSuite to drill down to somewhere using XPath and change that particular part. But none of this is really specific to Python, its the XML skill-set you really need. -- http://mail.python.org/mailman/listinfo/python-list
Re: simple way to touch a file if it does not exist
After os.path.exists, you need to check it _is_ a file, and not a directory. Giampaolo Rodola' wrote: On 22 Mag, 01:15, Nikhil [EMAIL PROTECTED] wrote: what are the simple ways? I could think of os.open(), os.exec(touch file) are there any simpler methods? Just use os.path.exists to check for file existence and open() as replacement for touch. import os if not os.path.exists('file'): ... open('file', 'w').close() ... --- Giampaolo http://code.google.com/p/pyftpdlib/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How do *you* use Python in non-GUI work?
John Salerno wrote: Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) Thanks. The vast majority of my Python work is Non-GUI. As an example, this weekend, I wrote a script to help in making a 'Lyrics' track in an audacity file, which is (more-or-less) an XML variety. In audacity, I created 'markers' in the file (as the song played) at the start of each line. The result was 'blank' markers at the correct times: labeltrack name=Lyrics numlabels=25 label t=18.50121034 t1=18.50121034 title=/ label t=24.34844390 t1=24.34844390 title=/ !-- Etc -- /labeltrackl My Python script took a text file, and inserted the words, as well as a title for the whole song. labeltrack name=Lyrics numlabels=26 label t=0.25 t1=0.25 title=Katie Melua. 'Nine million bicycles in Beijing' / label t=18.50121034 t1=18.50121034 title=There are nine million bicycles in Beijing,/ label t=24.34844390 t1=24.34844390 title=Thatapos;s a fact,/ label t=27.12436227 t1=27.12436227 title=Itapos;s a thing we canapos;t deny,/ !-- Etc -- /labeltrackl (The script used FourSuite) You can do this in FourSuite itself, but it can be error-prone if you miss out one. I can this in 'Scite' a text editor which puts your input in one window, and the output in another. Scite is a text editor that comes free with Ruby, by the way. -- http://mail.python.org/mailman/listinfo/python-list
Re: addendum Re: working with images (PIL ?)
I would still be concerned that you are checking against the percentage of the 768 bins returned by the histogram method. Two pixels of widely different colour end up in the same bin, so long as just ONE of the Red, Green, or Blue components is equal. So, for example, colours (2, 27, 200) and (200, 27, 2) are both in the bin for G=27. But they are very different colours. There are actualy 256 * 256 * 256 colours, but I don't suppose you want that many bins! What you want is a much smaller number of bins, with pixels of 'close' colours (whatever that means) put into the same bin. What 'close' means for colours, is quite a difficult thing, and the consensus is that using the three RGB coordinates is not as good as certain other colour spaces. You could use the ImageOps.posterize method to reduce the number of colours in the image, but whether 'close' colours end up together, I don't know. You might try the PIL special interest group (SIG) 'image-sig' http://mail.python.org/mailman/listinfo/image-sig (If you want to know exactly how many unique colours an image actually has, load the image into the 'GIMP' assuming you have it, and go to : Menubar -- Filters -- Colours -- Colourcube analysis... ) Poppy wrote: Thanks, since posting I figured out how to interpret the histogram results, which seems to be the consensus in responses. I wrote a check image program and have been periodically calling it against a folder where I make a copy of our images used for production. My method right now is to check what we send for errors, but is not preventive. Also I determined whitespace is not the only issue, any color that dominates. I'm considering rewriting this code below to setup bins, so if combined neighboring colors exceeds the threshold then reject the image. I have examples where half the image appears black, but actually varies throughout. Since my image is RGB I'm looping through a 768 element list. Zach- import Image, os def check_image(file): try: im = Image.open(file) except: return Can't open file %s % file imData = im.histogram() i = 0 for ea in imData: if ea ((im.size[0] * im.size[1]) / 4): ## 25% of image size return bad image %s - %s element num is %s % (file, ea, str(i)) i = i + 1 return good image %s, image size is %s % (file, im.size) def main(dir): data = try: files = os.listdir(dir) for ea in files: data = data + str(check_image(os.path.join(dir,ea))) + \n except: return Can't get files in %s % dir return data print main(host\\path\\to\\image_folder\\) -- http://mail.python.org/mailman/listinfo/python-list
Re: addendum Re: working with images (PIL ?)
Oops. I meant: WhiteArea=Result.histogram()[255] of course, not WhiteArea=Result.histogram()[0] Ken Starks wrote: As others have said, PIL has the 'histogram' method to do most of the work. However, as histogram works on each band separately, you have a bit of preliminary programming first to combine them. The ImageChops darker method is one easy-to-understand way (done twice), but there are lots of alternatives, I am sure. # import Image import ImageChops Im = Image.open(server\\vol\\temp\\image.jpg) R,G,B = Im.split() Result=ImageChops.darker(R,G) Result=ImageChops.darker(Result,B) Mistake here: WhiteArea=Result.histogram()[0] TotalArea=Im.size[0] * Im.size[1] PercentageWhite = (WhiteArea * 100.0)/TotalArea Poppy wrote: I've put together some code to demonstrate what my goal is though looping pixel by pixel it's rather slow. import Image def check_whitespace(): im = Image.open(server\\vol\\temp\\image.jpg) size = im.size i = 0 whitePixCount = 0 while i in range(size[1]): j = 0 while j in range(size[0]): p1 = im.getpixel((j,i)) if p1 == (255, 255, 255): whitePixCount = whitePixCount + 1 if whitePixCount = 492804: ## ((image dimensions 1404 x 1404) / 4) 25% return image no good j = j + 1 i = i + 1 print whitePixCount return image is good print check_whitespace() Poppy [EMAIL PROTECTED] wrote in message news:... I need to write a program to examine images (JPG) and determine how much area is whitespace. We need to throw a returned image out if too much of it is whitespace from the dataset we're working with. I've been examining the Python Image Library and can not determine if it offers the needed functionality. Does anyone have suggestions of other image libraries I should be looking at it, or if PIL can do what I need? -- http://mail.python.org/mailman/listinfo/python-list
Re: Write bits in file
You want your file considered as a sequence of bits rather than a sequence of 8-bit bytes, do you? is the 10-bit bit-pattern to be stored at an arbitrary bit-position in the file, or is the whole file regularly subdivided at 10-bit intervals? Monica Leko wrote: Hi I have a specific format and I need binary representation. Does Python have some built-in function which will, for instance, represent number 15 in exactly 10 bits? -- http://mail.python.org/mailman/listinfo/python-list
Re: Write bits in file
I admit that I was mostly just interested in getting your question clarified, rather than having any great experise. But a bit of Googling took me to the 'Bit vector' module, [I googled: 'python (bit array OR bit vector)'] which might be what you are after. I have no experience with it, myself: http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.4.1.html Monica Leko wrote: On May 18, 2:20 pm, Ken Starks [EMAIL PROTECTED] wrote: You want your file considered as a sequence of bits rather than a sequence of 8-bit bytes, do you? Yes. is the 10-bit bit-pattern to be stored at an arbitrary bit-position in the file Yes. I need arbitrary, 8bits, than 10 bits for something else, than sequence of bytes, than 10 bits again, etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: addendum Re: working with images (PIL ?)
As others have said, PIL has the 'histogram' method to do most of the work. However, as histogram works on each band separately, you have a bit of preliminary programming first to combine them. The ImageChops darker method is one easy-to-understand way (done twice), but there are lots of alternatives, I am sure. # import Image import ImageChops Im = Image.open(server\\vol\\temp\\image.jpg) R,G,B = Im.split() Result=ImageChops.darker(R,G) Result=ImageChops.darker(Result,B) WhiteArea=Result.histogram()[0] TotalArea=Im.size[0] * Im.size[1] PercentageWhite = (WhiteArea * 100.0)/TotalArea Poppy wrote: I've put together some code to demonstrate what my goal is though looping pixel by pixel it's rather slow. import Image def check_whitespace(): im = Image.open(server\\vol\\temp\\image.jpg) size = im.size i = 0 whitePixCount = 0 while i in range(size[1]): j = 0 while j in range(size[0]): p1 = im.getpixel((j,i)) if p1 == (255, 255, 255): whitePixCount = whitePixCount + 1 if whitePixCount = 492804: ## ((image dimensions 1404 x 1404) / 4) 25% return image no good j = j + 1 i = i + 1 print whitePixCount return image is good print check_whitespace() Poppy [EMAIL PROTECTED] wrote in message news:... I need to write a program to examine images (JPG) and determine how much area is whitespace. We need to throw a returned image out if too much of it is whitespace from the dataset we're working with. I've been examining the Python Image Library and can not determine if it offers the needed functionality. Does anyone have suggestions of other image libraries I should be looking at it, or if PIL can do what I need? -- http://mail.python.org/mailman/listinfo/python-list
Authoring SOAP and WSDL
I would like to write SOAP services in python, and have an environment that will then generate a matching WSDL for me automatically. Does such a thing exist in python? Thanks in advance. Ken. -- http://mail.python.org/mailman/listinfo/python-list
Re: Real Time Midi File Playback - Reading and Writing midi at the same time
Gilly wrote: Hi I am trying to create an application that uses some form of input to create a midi file. I would like for this to be a 'real time' process. In other words, I want to be able to begin playing the midi file before I finish writing it, and continue writing as it plays. I would really appreciate any help possible on this matter. Thanks!! Not python, but have you come across XMidi (http://www.palserv.com/XMidi/) ? It is used in the Apache Cocoon project, which has a Midi 'block'. This allows you to go from an XML file, or other source, to XMidi (an XML version of MIDI), and then to Quicktime, which you can listen to in your browser. I'm afraid I don't know whether the source can be streaming XML or whether you have to reach the end of the XML before it starts to play. If you can use streaming XML, you should be able to generate it from python. Foursuite has a streaming XML class, for example. A quick synopsis on the cocoon site says: What is the MIDI block? The MIDI block currently gives you an XMidiGenerator to generate an XML representation of any MIDI file (called XMidi by its author Peter Loeb). There is also the XMidiSerializer to render XMidi back as a MIDI file. I have used XSLT to provide some basic musical manipulations such as transposition, and inversion. Retrograde is harder, but I shall see what I can come up with. Hopefully I shall also add some transformers to generate SVG visualisations of the XMidi, starting with normal western musical notation. -- http://mail.python.org/mailman/listinfo/python-list
UK Ordnance survey coordinates and Geocoding anyone ?
Has anyone written a python wrapper around the (Windows) dll for converting between OSGB36 and ETRS89 coordinates ? The dll and an application are available from http://www.qgsl.co.uk as long as you register. Information, if you don't know what I'm taking about: - OSGB36 is the system system used on Ordnance survey maps, 'Eastings, Northings, and 'Height above sea level' (normally Newlyn). ETRS89 is the European variation of the standard Sat-Nav coordinates (GRS 1980) adjusted slightly to account for the continental drift of the European Plate away from the International average. You get 'Longitude' 'Latitude' and 'Height above the Ellipsoid. The Ordnance survey now __define__ OSGB36 in terms of ETRS89 and the algorithm implemented by the 'Grid Inquest' dll. Goodbye (most) Trig stations and Benchmarks! For an example of an OS map centered at a 1 metre accuracy gridpoint, (Buckingham Palace) go to: http://www.magic.gov.uk/website/magic/opener.htm?startTopic=maggbxygridref=529115,179711startScale=2500 -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate report containing pdf or ps figures?
Cameron Laird wrote: In article [EMAIL PROTECTED], Grant Edwards [EMAIL PROTECTED] wrote: I need to be able to generate a PDF report which consists mostly of vector images (which I can generate as encapsulated Postscript, PDF, or SVG). What I need is a way to combine these figures into a single PDF document. Right now the reports consist entire of these figures, so I just write the figures out to temp files and then use os.system() to run ghostscript with appropriate options to combine them into a single PDF file. I'd like to be able to add some text and/or place the figures in a manner other than one per page in the output document. I've looked at ReportLab's documentation, but although it appears to be able to use bitmap images (e.g jpeg) it doesn't appear to be able to use vector images (EPS/PDF/SVG). Is there a PDF generation library that can place EPS or PDF figures on a page? . . . You're stuck. snip I have also done quite a bit of work in this area, and keep coming back to LaTeX (pdfLaTeX). For automatic document production--if you have a good quantity of very similar documents--you can produce the LaTeX from XML, hence many other input formats. The graphics need to be converted into pdf format, and you need to be careful that the vector nature of the file is preserved during this conversion, as well as transparency. Unfortunately this is still uncommon for SVG. Also Adobe seem to have lost their one-time enthusiasm for SVG, since they acquired Flash and Friends. A rather new entry into the arena is 'Altsoft Xml2PDF Workstation' which is free for command-line use, but not for server use. Seems to produce PDF of reasonable quality and to use vector format, transparency and gradient fills. Another possibility is to wrap things up as SMIL. The latest versions of Acrobat reader can use them, using RealPlayer (for example) as the actual multimedia engine. There is at least one LaTeX package that can produce PDF that incorporates such multi-media. I've rather given up on ReportLab. Trying to extend it (the free part) to use graduated fills completely did my head in! -- http://mail.python.org/mailman/listinfo/python-list
Re: help developing an editor to view openoffice files.
krishnakant Mane wrote: hello, right now I am involved on doing a very important accessibility work. as many people may or may not know that I am a visually handicap person and work a lot on accessibility. the main issue at hand is to create an accessible editor for open office. there are a lot of things remaining on that front. so right now I am trying to find out a temporary work around by creating a simple accessible editor (with wxpython) for viewing and editing open office files. I know there must be python libraries that can open/ save .odt files because it is an open standard any ways. but I am trying to work out a kind of a program where those files can also be displayed in a text area with all the formatting. probably one way of doing it is to use some thing like a rich text editor and allow the file to be converted to rtf from odt for viewing and back again to odt when the user wishes to save it. another way I find is to actually find out if there is a odt text box that can display these files as they are. viewing the contents of the files in an editable way is most important. any suggestions? regards. Krishnakant. There is an O'Reilly Book about hacking the Open Office Format, and it is available free on line in both html and pdf. Open office files are a variation on 'Zipped' archives and many unzip tools can be used to open them, apart from ones that insist on a .zip extension. These include python tools. The one 'case study' in the book that uses python is actually for a spreadsheet, but that makes little difference to the 'unzipping' part. You can find it at: http://books.evc-cit.info/odbook/ch05.html#modify-spreadsheet-section Once you have the raw XML you should be able to convert it to any one of many more accessible XML formats, for screen readers, brail printers and so on. I don't know much about them, but hopefully you do! Don't re-invent the wheel! You will find quite a few ways on the Open Office Wiki for converting the format to other things. You can also daisy-tail the XSLT files; for example use one to convert to xhtml and a second that converts xhtml to text. Example (Display write files in the 'Firefox' browser). http://wiki.services.openoffice.org/wiki/Firefox_ODFReader_extension Don't forget that Open Office already has PDF export facilities, and Acrobat reader already has some accessibility ability for simple documents (i.e single column, 'start at the beginning, keep going until you get to the end, and then stop'). For adding structure to other PDF files you would need Acrobat Professional or software that can export 'tagged' PDFs. The case-study code is: import xml.dom import xml.dom.ext import xml.dom.minidom import xml.parsers.expat import sys import od_number from zipfile import * from StringIO import * if (len(sys.argv) == 4): # Open an existing OpenDocument file # inFile = ZipFile( sys.argv[1] ) # ...and a brand new output file # outFile = ZipFile( sys.argv[2], w, ZIP_DEFLATED ); getParameters( sys.argv[3] ) # # modify all appropriate currency styles # fixCurrency( styles.xml ) fixCurrency( content.xml ) # # copy the manifest # copyManifest( ) inFile.close outFile.close else: print Usage: + sys.argv[0] + inputfile outputfile parameterfile -- http://mail.python.org/mailman/listinfo/python-list
Re: List of files to be opened
yawgmoth7 wrote: Hello, I am currently writing a script that requires a few different files to be opened, and examined. What I need to be able to do is use something like: filelist = os.system(ls) Some way to open the file list and read each file one by one here I cannot think of a way to do this, I could put them in a list of something of the sort. But that still does not solve the problem of opening them one by one. Thanks for all the advice and help. -- gurusnetwork.org Gurus'Network - Are you a guru? os.walk is your friend. Its has wonderful functionality. The documentation is in the subsection 'Files and Directories' of the os module, and there are a couple of examples. Global Module index -- os -- 'Files and Directories' (Section 6.1.4) --Bottom of page -- http://mail.python.org/mailman/listinfo/python-list
Re: Loading a Python collection from an text-file
Ilias Lazaridis wrote: within a python script, I like to create a collection which I fill with values from an external text-file (user editable). How is this accomplished the easiest way (if possible without the need of libraries which are not part of the standard distribution)? something like: text-file: {peter, 16}, {anton, 21} - within code: users.load(text-file.txt) for user in users user.name user.age . What I do for this kind of work is to use a gnumeric spreadsheet which saves the data in a simple xml format. xml is much less error-prone than plain text. Google for, and study 'The gnumeric file format' by David Gilbert. You need to know how to unzip the file, and how to write a SAX parser. If you want to use a plain text format, keep it simple. I would separate the two fields with tab (thus permit a comma within a field) and allow 'comment' lines that start with a hash. You don't need the braces, or the end-of-line comma you included. # snip 'text-file.txt' # name and age on one line separated by tab Jonny 8 Mary87 Moses 449 # end-snip 'text-file.txt' Then: import string class user: def __init__(self,name,age): self.name=name self.age=int(age) # or a float, or a time-interval, or date-of-birth def show(self): print %s is aged %s % (self.name, self.age) if __name__==__main__: users=[] filename=text-file.txt fieldsep=\t F=open(filename,r) Lines=F.readlines() for L0 in Lines: L1=string.strip(L0) if not L1.startswith(#): Record=string.split(L1,fieldsep) # insert error handling/validation here users.append(user(Record[0],Record[1])) F.close() for user in users: user.show() -- http://mail.python.org/mailman/listinfo/python-list
Re: ideas for university project ??
Jon Hewer wrote: Hi I'm about to start my third, and final, year in computer science at cambridge uni, and i need to come up with an idea for a software project, but i'm really struggling for ideas, and i was wondering whether anyone here had any suggestions. I'd say i'm probably most experienced in Java, but I have started learning Python, and although i haven't got very far yet, I plan on doing some more in the next few weeks. Areas of interested include AI, distributed systems. Most of all i want something that is interesting, and actually useful (thats probably stating the obvious!) Cheers Jon I'd like you to write a Python-SOAP-based interface to data-loggers and interface boxes used in the UK at school level. For example, those produced by Phillip Harris, which are normally connected by way of a serial cable. The idea is to keep an old computer with the data-logger attached, and the SOAP server installed, in the field or lab. Am I correct in saying that Java is too security-bound for this role? Personally, I would feed the resulting XML into Cocoon, which already has SOAP input, and from there into dataframes in 'R' among other places. Once it has entered a Cocoon pipeline, it is already in a very flexible form, and Data analysis can be done anywhere that can reach the Cocoon server. You may wish to develop that end of the pipeline either using your Java skills, or by using XSLT to create Prolog facts or whatever. -- http://mail.python.org/mailman/listinfo/python-list