Call Java Code from python
Hi, I have a project coming up where i have to integrate our existing Python based web application with Java Programs. Basically i should be able to call Java programs which comes in the form of jars. Whats the best way to call these jars from python ? I looked at jpype and tried with small program and it works. Are there any other tools which can do the same or if any how are they compared to jpype ? -- B Gowda. -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On 8/17/2010 11:20 AM, Standish P wrote: On Aug 17, 1:17 am, torb...@diku.dk (Torben Ægidius Mogensen) wrote: Standish Pstnd...@gmail.com writes: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ? Because a stack has push and pop, it is able to release and allocate memory. We envisage an exogenous stack which has malloc() associated with a push and free() associated with a pop. See How many programmers have applied the ideas of these papers in their programming practice ? I paste the abstract for convenience http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.5498 Abstract: This paper describes a memory management discipline for programs that perform dynamic memory allocation and de-allocation. At runtime, all values are put into regions. The store consists of a stack of regions. All points of region allocation and deallocation are inferred automatically, using a type and effect based program analysis. The scheme does not assume the presence of a garbage collector. That's actually an interesting idea. If you can figure out object lifetimes at compile time, allocation can be made far more efficient. One of the basic questions is whether a function will ever keep an object. That is, will the function ever keep a reference to an object that outlives the return from the function? In many cases, one can easily determine at compile time that a function will never keep a passed object. In such a case, you don't have to do reference count updates on the object. Most math functions have this property, even vector and matrix math functions - they have no persistent state. Python could use a bit of this. If a function argument can be identified as non-kept, then the function doesn't need to do reference count updates on it. If a local variable in a function is used only by non-keep functions and operations, it can be created on the stack and released cheaply at block exit. One can go much further in lifetime inference than this, as the papers demonstrate. There's a big win in the simple optimization of identifying non-keep parameters, especially in mathematical work where they're very common. It's not clear that getting fancier than that is a win. Does Shed Skin have this optimization? It should. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Call Java Code from python
Hi Bidda, On 2010-08-18 09:19, Bidda Gowda wrote: I have a project coming up where i have to integrate our existing Python based web application with Java Programs. Basically i should be able to call Java programs which comes in the form of jars. Whats the best way to call these jars from python ? I looked at jpype and tried with small program and it works. Are there any other tools which can do the same or if any how are they compared to jpype ? Here are some slides from a talk by Andreas Schreiber, Mixing Python and Java, which might help: http://www.slideshare.net/onyame/mixing-python-and-java Personally, I've used JCC for accessing Lucene (a search engine framework implemented in Java). It was a bit rough in some places, but overall quite usable. Stefan -- http://mail.python.org/mailman/listinfo/python-list
use of gtk in a nautilus extension
Hi, I am having some trouble opening a simple message/dialog to the user from a natilus extension.. I have written a simple nautilus extension using python. It adds one MenuItem to the context menu. for testing I wanted to open a simple dialog when the user clicks this menuitem. (The code can be found - with some nice formatting here: http://stackoverflow.com/questions/3325772/use-gtk-in-a-nautilus-extension-using-python) The code is as follows: --- cut --- import gtk import nautilus import os def alert(message): A function to debug dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, message) dialog.run() dialog.destroy() class TestExtension(nautilus.MenuProvider): def __init__(self): pass def get_file_items(self, window, files): items = [] Called when the user selects a file in Nautilus. item = nautilus.MenuItem(NautilusPython::test_item, Test, Test) item.connect(activate, self.menu_activate_cb, files) items.append(item) return items def menu_activate_cb(self, menu, files): Called when the user selects the menu. for name in files: alert(name) --- cut --- When I click on the menuitem nothing happens... But when I replace def alert(message) like this: def alert(message): A function to debug easygui.msgbox(message) and obviously drop import gtk and add import easygui, The dialog does appear. Can someone tell me why this is ?? Yours, Nils -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
On 08/17/10 12:59, AK wrote: On 08/16/2010 10:42 PM, James Mills wrote: On Tue, Aug 17, 2010 at 12:35 PM, AKandrei@gmail.com wrote: As monitors are getting bigger, is there a general change in opinion on the 79 chars limit in source files? I've experimented with 98 characters per line and I find it quite a bit more comfortable to work with that length, even though sometimes I have to edit files in 80 width terminals, it's still easier to adapt to some inconvenience when that happens than the other way around, since about 95% of time or more, I do use wider editor window or terminal. Is going over 79 still a terrible thing to do? -andrei My personal opinion (despite monitors being wider) is the horizontal scrolling isn't worth it. Stick to a 80-char width. But.. why horizontal scrolling, isn't autowrap much better than that? Do you seriously use autowrapper when writing code? -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
In message i4e4o6$gc...@localhost.localdomain, Martin Gregorie wrote: 1) ssh terminal windows generally come up as 24 x 80 My terminal windows come up by default at something like 40 lines by 100 characters. 2) at 24 x 80 I can get more ssh terminal windows on the desktop with minimal overlap than I can do with longer/wider windows. I have 8 terminal windows open at once, they all fit fine, with room for an Emacs window and whatever else I might occasionally squeeze into there. Hint: I use tabs as well as windows. -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On 17 Aug, 18:34, Standish P stnd...@gmail.com wrote: On Aug 16, 11:09 am, Elizabeth D Rather erat...@forth.com wrote: On 8/15/10 10:33 PM, Standish P wrote: If Forth is a general processing language based on stack, is it possible to convert any and all algorithms to stack based ones and thus avoid memory leaks since a pop automatically releases memory when free is an intrinsic part of it. Forth uses two stacks. The data stack is used for passing parameters between subroutines (words) and is completely under the control of the programmer. Words expect parameters on this stack; they remove them, and leave only explicit results. The return stack is used primarily for return addresses when words are called, although it is also available for auxiliary uses under guidelines which respect the primary use for return addresses. Although implementations vary, in most Forths stacks grow from a fixed point (one for each stack) into otherwise-unused memory. The space involved is allocated when the program is launched, and is not managed as a heap and allocated or deallocated by any complicated mechanism. On multitasking Forth systems, each task has its own stacks. Where floating point is implemented (Forth's native arithmetic is integer-based), there is usually a separate stack for floats, to take advantage of hardware FP stacks. - is forth a general purpose language? Yes - are all algorithms stack based? No Does Forth uses stack for all algorithms ? Does it use pointers , ie indirect addressing ? If it can/must use stack then every algorithm could be made stack based. Forth uses its data stack for parameter passing and storage of temporary values. It is also possible to define variables, strings, and arrays in memory, in which case their addresses may be passed on the data stack. Forth is architecturally very simple. Memory allocations for variables, etc., are normally static, although some implementations include facilities for heaps as needed by applications. although some implementations include facilities for heaps as needed by applications. How are these heaps being implemented ? Is there some illustrative code or a book showing how to implement these heaps in C for example ? any book of algorithms I'd have thought http://en.wikipedia.org/wiki/Dynamic_memory_allocation http://www.flounder.com/inside_storage_allocation.htm I've no idea how good either of these is Are dictionaries of forth and postscript themselves stacks if we consider them as nested two column tables which lisp's lists are in essence, but only single row. Multiple rows would just be multiple instances of it at the same level inside parens. I can't make much sense of that. But you seem to see Lisp data structures in all sorts of strange places. I don't see that Lisp lists are nested two column tables we can peek into stacks which is like car. no. if it is not unusually costly computation, why not allow it ? there is no need to restrict to push and pop. some stacks have a top() operation. roll( stack_name, num) itself can give all those postfix permutations that push and pop cant generate with a single stack. Can we use dictionaries to generate multiple stacks inside one global stack ? I've no idea what you on about -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Developer - HFT Trading firm - Chicago, IL
Hi Rich, I think it's better for you to post the message here ( http://www.python.org/community/jobs/ ). Regards, On Tue, Aug 17, 2010 at 6:07 PM, Rich Moss moss.r...@gmail.com wrote: Python developer needed for math/trading applications and research at leading HFT firm. The person we are searching for will have a strong background with python programming and the ability to work with very large historical datasets. You should have a very strong math background as well. This can involve writing very complicated python scripts and programs! You will work very closely with traders and quantitative analysts in their equities trading group on state-of-the- art trading strategy and execution systems. Requires: Strong python programming experience developing applications and scripts using complex regular expressions Strong math knowledge and education Experience working with massive datatsets/historical data This company is a top-tier electronic, algorithmic trading firm, located in Chicago, IL. This firm is one of the most advanced high frequency electronic trading firms in the world and uses python throughout the company, as well as other languages. This firm has a culture that rewards creativity and hard work. No third parties, please. We will not consider candidates from outside the USA. No telecommuting. We offer very generous compensation (best in the industry), fantastic benefits and very generous relocation packages. Please contact me immediately with a resume! Send resumes to: Rich Moss r...@mossltd.com -- http://mail.python.org/mailman/listinfo/python-list -- Matteo Landi http://www.matteolandi.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
D'Arcy J.M. Cain wrote: On Tue, 17 Aug 2010 16:28:02 +0200 Stefan Schwarzer sschwar...@sschwarzer.net wrote: I'd probably reformat this to self.expiration_date = translate_date( find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') or even self.expiration_date = translate_date( find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') You can extend this if there are complicated sub-calls. Probably overkill for this example but here is the idea. self.expiration_date = translate_date( find( response, 'MPNExpirationDate', ).text, '%Y-%m-%d', '%m%d%Y' ) I also moved the closing brace down to align with the line that opened that block. If this is supposed to convice 80+ chars users, that's an epic failure :) This is exactly the kind of layout I'm happy to not use by not caring about the line width. At least, if you still want to stick with 79 chars, do something like text = find(response, 'MPNExpirationDate', ).text self.expiration_date = translate_date(text,'%Y-%m-%d', '%m%d%Y') JM -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On 17 Aug, 21:37, Elizabeth D Rather erat...@forth.com wrote: On 8/17/10 10:19 AM, Standish P wrote On Aug 17, 12:32 pm, John Passanitijohn.passan...@gmail.com wrote: It is true that the other languages such as F/PS also have borrowed lists from lisp in the name of nested-dictionaries and mathematica calls them nested-tables as its fundamental data structure. No. you are contradicting an earlier poster from forth who admitted the part on dicts. he's saying a forth dictionary isn't a lisp s-exp. Well it isn't. Not at all. A Forth dictionary is a simple linked list, not the complicated kind of nested structures you're referring to. You really seem addicted to very complex structures. I thought he had the opposite problem! I thought it was trying to knock in all his programming nails with same stack-based hammer. They really aren't necessary for general programming. whaever *that* is -- http://mail.python.org/mailman/listinfo/python-list
Re: String substitution VS proper mysql escaping
Στις 18/8/2010 7:31 πμ, ο/η Cameron Simpson έγραψε: On 17Aug2010 20:15, Νίκοςnikos.the.gr...@gmail.com wrote: | === | cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = | '%s' ORDER BY date DESC ''' % (page) ) | === | | Someone told me NOT to do string substitution (%) on SQL statements | and to let MySQLdb do it | for me, with proper escaping like the following | | === | cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s | ORDER BY date DESC''', (page,)) | === | | The difference is that if some external source can control page, | and | they put in a value like | 100 ; DELETE FROM visitors; SELECT * FROM visitors | i will be losing my database table data. That other difference is that the mysql dialect support knows how to correctly escape a string for insertion into an SQL statement. You may not, or may forget to pre-escape the string, etc. Using the MySQLdb stuff do it for you is reliable and robust. Can you please tell me what escaping means by giving me an example of what is escaped and whats isn't? Also hwo can i delete my data for testing purposes as? http://webville.gr/index.html?page=100 ; DELETE FROM visitors; SELECT * FROM visitors I get an error... | a) I wanted to ask what is proper escaping mean and why after variable | page syntax has a comma Because this: (page) means the same thing as: page i.e. the argument to the % operator is just the string in page. This: (page,) is a _tuple_ containing a single element, the page variable. A bit like: [page] which is a list containing a single element. The trailing comma is needed to tell python you want to use a tuple, not the bare string. The % operator has special knowledge that is it is passed as string instead of a list or tuple or other sequence then it should act _as_ _if_ it had been passed a single element tuple containing the string. %s and %d is behaving the same due to % expecting a string instead of an integer? Otherwise, because a string _is_ a sequence the % might want to treat the string foo as the sequence: (f, o, o) cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s ORDER BY date DESC''', page) But it alss might treat it an entity, i mean since 'page' is a variable containing a string why not just 'page' as it is expecting 'page' variable to give its value when asked? Run these three loops to see the difference: for s in foo: print s for s in (foo): print s for s in (foo,): print s Cheers, for s in nikos: print s n i k o s # this handles the string nikos as a series of chars right? for s in (nikos): print s n i k o s # this handles the string nikos as a series of chars too but what si the difference with the above in htis with the parentheses? is nikos is handles still as string here? for s in (nikos,): print s nikos # Here yes it handles nikos as the 1st item of a tuple nikos for s in [nikos]: print s nikos # Here? why is it behaving fifferent than the above (nikos) and is proccessign it all chars in one? for s in [nikos,]: print s nikos # Here it handles nikos as the 1st item of a list right? -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
Hi Lie, On 2010-08-18 12:02, Lie Ryan wrote: On 08/17/10 12:59, AK wrote: On 08/16/2010 10:42 PM, James Mills wrote: My personal opinion (despite monitors being wider) is the horizontal scrolling isn't worth it. Stick to a 80-char width. But.. why horizontal scrolling, isn't autowrap much better than that? Do you seriously use autowrapper when writing code? I think he means wrapping on the screen, not actually inserting line breaks. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Working with PDFs?
jyoun...@kc.rr.com writes: - Pull out text from each PDF page (to search for specific words) - Combine separate pdf documents into one document - Add bookmarks (with destination settings) PDF Shuffler is a Python app which does PDF merging and splitting very well. I don't think it does anything else, though, but maybe that's where your code comes in? -- http://mail.python.org/mailman/listinfo/python-list
Re: String substitution VS proper mysql escaping
On 18Aug2010 12:07, Nik Gr nikos.the.gr...@gmail.com wrote: | Στις 18/8/2010 7:31 πμ, ο/η Cameron Simpson έγραψε: | On 17Aug2010 20:15, Νίκοςnikos.the.gr...@gmail.com wrote: | | === | | cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = | | '%s' ORDER BY date DESC ''' % (page) ) | | === | | | | Someone told me NOT to do string substitution (%) on SQL statements | | and to let MySQLdb do it | | for me, with proper escaping like the following | | | | === | | cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s | | ORDER BY date DESC''', (page,)) | | === | | | | The difference is that if some external source can control page, | | and | | they put in a value like | | 100 ; DELETE FROM visitors; SELECT * FROM visitors | | i will be losing my database table data. | | That other difference is that the mysql dialect support knows how to | correctly escape a string for insertion into an SQL statement. You may | not, or may forget to pre-escape the string, etc. Using the MySQLdb | stuff do it for you is reliable and robust. | | Can you please tell me what escaping means by giving me an example | of what is escaped and whats isn't? In your plain substitution example above: cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page = '%s' ORDER BY date DESC ''' % (page) ) Supposing page is the string 100. This will produce the SQL statement: SELECT host, hits, date FROM visitors WHERE page = '100' ORDER BY date DESC which looks ok. But suppose page was the string: bill o'reilly Then your SQL statement looks like this: SELECT host, hits, date FROM visitors WHERE page = 'bill o'reilly' ORDER BY date DESC To the SQL engine this looks like the string bill o followed by an SQL instruction named reilly, and then the opening quote for another string. Invalid SQL. The procedure used to avoid this problem (to insert an _arbitrary_ string into the SQL statement) is to escape problematic characters in strings when placing them into SQL statements. In this case, the quote character in the string is the SQL end string character. Therefore the string must be modified in the SQL statement to be correctly expressed. IIRC, SQL uses the quote doubling convention for strings, so this: SELECT host, hits, date FROM visitors WHERE page = 'bill o''reilly' ORDER BY date DESC is how one would write the literal SQL for that. The MySQLdb library will do this and a host of other equivalent things automatically and correctly and consistently when you pass page as a parameter to the execute() method, needing no special attention or detailed syntactic knowledge on your part when you write your program. [...snip...] | The % operator has special knowledge that is it is passed as string instead | of a list or tuple or other sequence then it should act _as_ _if_ it had been | passed a single element tuple containing the string. | | %s and %d is behaving the same due to % expecting a string instead | of an integer? I haven't checked. I make a point of using the (page,) form (i.e. always use a tuple, even with just one argument) these days. That way there is no ambiguity. | Otherwise, because a string _is_ a sequence the % might want to treat | the string foo as the sequence: | |(f, o, o) | cursor.execute('''SELECT host, hits, date FROM visitors WHERE | page=%s ORDER BY date DESC''', page) | | But it alss might treat it an entity, i mean since 'page' is a | variable containing a string why not just 'page' as it is expecting | 'page' variable to give its value when asked? A string is also a sequence of characters. | Run these three loops to see the difference: | |for s in foo: | print s |for s in (foo): | print s |for s in (foo,): | print s | | Cheers, | for s in nikos: | print s | | | n | i | k | o | s | | # this handles the string nikos as a series of chars right? Yes. | for s in (nikos): | print s | | | n | i | k | o | s | | # this handles the string nikos as a series of chars too but what | si the difference with the above in htis with the parentheses? is | nikos is handles still as string here? It is exactly the same as the first loop. Just as: 1 + 3 is exactly the same as: (1) + (3) | for s in (nikos,): | print s | | nikos | | # Here yes it handles nikos as the 1st item of a tuple Yep. | for s in [nikos]: | print s | | nikos | | # Here? why is it behaving fifferent than the above (nikos) and is | proccessign it all chars in one? (nikos,) is a single element tuple. [nikos] is a single element list. [nikos,] is also a single element list, just written like the tuple. You don't see the [nikos,] form very often because [nikos] is not ambiguous. It is only because (nikos) gets reduced to plain nikos just like the arithmetic above that you see the (nikos,) form -
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On Aug 18, 1:21 am, Standish P stnd...@gmail.com wrote: Garbage collection doesn't use a stack. It uses a heap, which is in the abstract a collection of memory blocks of different lengths, divided into two lists, generally represented as linked lists: 1. A list of blocks that are free and may be used to store new data 2. A list of blocks that are in use, or haven't been freed (yet) Is this all that a heap is or is there more to it ? I have been looking for simple but complete explanation of heap for a while and not gotten to it. I think I am looking for a stack allocation on the same pattern. In a disk, a file is fragmented in many contiguous blocks and is accessed automatically. There is no way you could do memory management of all but the most trivial and fixed-length data chunks using a stack. Sure, you could reserve thousands of bytes on the stack for an array but suppose your language allows arrays to grow or shrink. To keep its property of being adjacent, you'd have to do something horrible such as move unrelated data allocated later, which raises all sorts of security issues, doesn't it. A stack, or something which works like a stack (that is, a stack) is a necessary but not sufficient condition for a working C runtime because C functions can call themselves recursively, whether directly or indirectly. If this last condition did not obtain, each function could give the functions it calls some of its own memory and the called function could save a fixed set of non-stacked general registers in that area; this was in fact the practice on IBM 370 and in assembler language at a time when many data processing managers though recursion was a Communist plot. However, data structures of variable size, or data structures that merely take up a lot of space, don't play nice with others on the stack, so, we place their address on the stack and store them in another place, which was named the heap, probably, as a sort of witticism. Gilbert and Sullivan: If anyone anything lacks He'll find it all ready in stacks This you might want to take this to the Forth people because they are marketing their language as a cure for all that plagues programming today. No, they're not. Stack based languages have seen better days and Forth (and the SL/1 language I supported with compilers at Bell-Northern Research) were last in fashion in the 1970s. Processors seldom could multitask, so it wasn't recognized that the stack could be a performance bottleneck, where stack operations cannot be pipelined or executed in parallel. John Hennessy of Stanford and MIPS made the stack must die case at ACM ASPLOS in 1987. Niklaus Wirth was also at this conference at which I was a fly on the wall, maintaining that the stack was good for reliability and verifiability of software. Forth had a snowball's chance because it forces ordinary programmers to think in Reverse Polish notation and is for the above reasons hard to pipeline, although of course it can be pipelined. was wrong, and needs to be brought up to date: You cannot do everything in a stack Unless you code an almighty hack If you're a coding Knight who says, Neep, You'll probably need to implement a heap A pile a heap of benefits you'll reap If only my advice in your brain you'll keep And avoid memory leaks from which data doth seep By using a well-implemented, well structured, and well-documented Heap! [Chorus of Sailors] We will to heart your advice take, and always use a heap! [Soloist] Oh thank you do To this be true And always my sage advice do keep That you always need to use a heap!- Hide quoted text - - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
Roy Smith r...@panix.com wrote in message news:roy-319e47.09055017082...@news.panix.com... In article i4deqq$4e...@lust.ihug.co.nz, Lawrence D'Oliveiro l...@geek-central.gen.new_zealand wrote: In message mailman.2212.1282012525.1673.python-l...@python.org, AK wrote: As monitors are getting bigger, is there a general change in opinion on the 79 chars limit in source files? WHAT 79-character limit in source files? I currently have my Emacs windows set at 100 characters wide, and Iâ?Tm thinking of going wider. Remember, the old hardcopy terminals used to produce 132-character-wide listings. Those of you who think old hardcopy terminals did 132 wide obviously don't remember the ASR-33 :-) ASR33s I think might have been 72 columns wide (and punched cards had a similar restriction). However, lineprinter output was more likely to be 132 columns. -- bartc -- http://mail.python.org/mailman/listinfo/python-list
Re: String substitution VS proper mysql escaping
On 08/18/10 04:50, Cameron Simpson wrote: (nikos,) is a single element tuple. [nikos] is a single element list. [nikos,] is also a single element list, just written like the tuple. You don't see the [nikos,] form very often because [nikos] is not ambiguous. I most frequently see/use the trailing comma in a one-item list when I expect additional items will be accrued later, so it makes my version-control diffs tidier: items = [ nikos, ] Then a month later, I add items = [ nikos, cameron, ] My diff is just items = [ nikos, + cameron, ] which is quite easy to understand. However if my original was items = [ nikos ] and I later want to make it items = [ nikos, cameron ] the diff then becomes items = [ - nikos + nikos, + cameron ] which isn't nearly as easy to read understand because I now have to notice the inter-linear differences (did something more than the new-comma happen?). -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
In message 4c6a9c72.4040...@sschwarzer.net, Stefan Schwarzer wrote: self.expiration_date = translate_date( find(response, 'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y') Might I suggest (guessing at the argument keywords here) : self.expiration_date = translate_date \ ( TheText = find(response, 'MPNExpirationDate').text, ToFormat ='%Y-%m-%d', FromFormat ='%m%d%Y' ) Presumably FromFormat should be localizable, rather than hard-coded. See, that’s the kind of thing you notice when you think about the code in this way. -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On 08/17/2010 11:44 PM, Baba wrote: On Aug 16, 6:28 pm, cbr...@cbrownsystems.com cbr...@cbrownsystems.com wrote: First, suppose d = gcd(x, y, z); then for some x', y', z' we have that x = d*x', y = d*y', z = d*z'; and so for any a, b, c: could you explain the notation? what is the difference btw x and x' ? what is x = d*x', y supposed to say? gcd(x,y,z) determines the greates number by which all three numbers can be devided. 2,4,6 for example are all divided by 2 thus d=2 now you dived x,y,z by d and call them x' , y' , z' The point is if x,y,z have a gcd grater than one, then you know for sure, that you will never be able to find the a finit greates amount, which cannot be bought if xmymz are all divisible by d, then any combination will also be dividible by d thas any number not dividible by d ( for d 1) for example n*d + 1 can not be bought -- http://mail.python.org/mailman/listinfo/python-list
Python 2.7 support for PyWin32
Hi everyone, does anyone know when PyWin is going to support Python 2.7? I tried to look for information, but to no avail. Thanks in advance, Paulo -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
In article qkoao.53872$gq5.12...@hurricane, BartC ba...@freeuk.com wrote: Remember, the old hardcopy terminals used to produce 132-character-wide listings. Those of you who think old hardcopy terminals did 132 wide obviously don't remember the ASR-33 :-) ASR33s I think might have been 72 columns wide (and punched cards had a similar restriction). Yeah, I was trying to remember if it was 72 or 80. Hmmm, looks like you're right, it *is* 72 (http://www.pdp8.net/asr33/asr33.shtml). Punched cards (at least the common ones used by an 029 or 129 punch machine) were 80 columns. The 72 column restriction was an artificial one imposed by some programming languages such as Fortran. Columns 73-80 could be used to punch a sequence number, so that if you dropped your deck, you could re-assemble it by running it through a card sorter. However, lineprinter output was more likely to be 132 columns. Yeah, but I wouldn't call a line printer a terminal. -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
In article 4c6b9...@dnews.tpgi.com.au, Lie Ryan lie.1...@gmail.com wrote: On 08/17/10 12:59, AK wrote: On 08/16/2010 10:42 PM, James Mills wrote: On Tue, Aug 17, 2010 at 12:35 PM, AKandrei@gmail.com wrote: As monitors are getting bigger, is there a general change in opinion on the 79 chars limit in source files? I've experimented with 98 characters per line and I find it quite a bit more comfortable to work with that length, even though sometimes I have to edit files in 80 width terminals, it's still easier to adapt to some inconvenience when that happens than the other way around, since about 95% of time or more, I do use wider editor window or terminal. Is going over 79 still a terrible thing to do? -andrei My personal opinion (despite monitors being wider) is the horizontal scrolling isn't worth it. Stick to a 80-char width. But.. why horizontal scrolling, isn't autowrap much better than that? Do you seriously use autowrapper when writing code? I absolutely use auto-indent, parenthesis matching, and syntax coloring. From time to time, I turn on auto-wrap, but generally find it more annoying than useful and turn it back off again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 support for PyWin32
On 18/08/2010 12:54, paulo.jpi...@gmail.com wrote: Hi everyone, does anyone know when PyWin is going to support Python 2.7? I tried to look for information, but to no avail. Thanks in advance, Paulo It was created on 2009-07-08!!! See:- http://sourceforge.net/projects/pywin32/files/pywin32/ Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray'
Although I'm sure somewhere this issue is discussed in this (great) group, I didn't know the proper search words for it (although I tried). I'm using python (2.6) scientifically mostly, and created a simple class to store time series (my 'Signal' class). I need this class to have a possibility to get multiplied by an array, but pre and post multiplication have different mathematical outcomes ( basically A* B != B*A ) . Post multiplication by an array works fine defining __mul__ in the Signal class, but pre multiplication does not. It keeps trying to multiply all elements separately instead to send this array to my __rmul__ function. How can I fix this without the need for a separate 'multiplysignal(A,B)' function? To make things easy I've made a small example: [code] import numpy as np class Signal(object): def __init__(self,data,dt): self.data=data self.dt=dt def Nch(self): return self.data.shape[0] def __mul__(self,other): print 'mul called! ',other if isinstance(other,type(np.array([1,2]))): #it's an array: use dot product: return Signal(np.dot(self.data,other),self.dt) if other.__class__.__name__=='Signal': # do something pass def __rmul__(self,other): print 'rmul called! ',other if isinstance(other,type(np.array([1,2]))): #it's an array: use dot product: return Signal(np.dot(other,self.data),self.dt) if other.__class__.__name__=='Signal': # do something pass mySignal=Signal(np.array([[1.,2],[4,5]]),1.) myArray=np.array([[1.,2.],[4.,3.]]) result_mul = mySignal*myArray result_rmul = myArray*mySignal #called 4 times for all members once! #result: #mul called! [[ 1. 2.] # [ 4. 3.]] #rmul called! 1.0 #rmul called! 2.0 #rmul called! 4.0 #rmul called! 3.0 [/code] -- http://mail.python.org/mailman/listinfo/python-list
error Compile libxml2 from python 2.6.4
Hi!. Have the next error on install libxml2. python/bin/python setup.py install failed to find headers for libxml2: update includes_dir This my version of python == /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python/bin/python Python 2.6.5 (r265:79063, Jul 21 2010, 13:05:40) [C] on hp-ux11 Type help, copyright, credits or license for more information. I'm Installing libxml2 for python 2.6.5, and this error break the install. The python path prefix is /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python, and i don't privileges of root. The configuration to be personalized, in prefix path. My compile line is: ./configure --with-python=/bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python \ --prefix=/bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml \ --with-libxml-include-prefix=/bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/pythonPruebas/libxml2/libxml2-INC/usr/local/include/libxml2/libxml This is the output when finalize compiling this is message: Enabled Schemas/Relax-NG support configure: creating ./config.status config.status: creating libxml2.spec config.status: creating Makefile config.status: creating include/Makefile config.status: creating include/libxml/Makefile config.status: creating doc/Makefile config.status: creating doc/examples/Makefile config.status: creating example/Makefile config.status: creating python/Makefile config.status: creating python/tests/Makefile config.status: creating include/libxml/xmlversion.h config.status: creating xml2-config config.status: creating libxml-2.0.pc config.status: creating libxml-2.0-uninstalled.pc config.status: creating xml2Conf.sh config.status: creating python/setup.py config.status: creating config.h config.status: config.h is unchanged config.status: executing depfiles commands And this is output of make install: Libraries have been installed in: /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/python/lib/python2.6/site-packages If you ever happen to want to link against installed libraries in a given directory, LIBDIR, you must either use libtool, and specify the full pathname of the library, or use the `-LLIBDIR' flag during linking and do at least one of the following: - add LIBDIR to the `LD_LIBRARY_PATH' environment variable during execution - use the `-LLIBDIR' linker flag See any operating system documentation about shared libraries for more information, such as the ld(1) and ld.so(8) manual pages. Making install in tests No suffix list. No suffix list. /bin/sh ../../mkinstalldirs /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml/share/doc/libxml2-python-2.6.4/examples mkdir -p -- /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml/share/doc/libxml2-python-2.6.4/examples (for test in build.pyattribs.py tst.py tstxpath.py xpathext.py push.py pushSAX.py pushSAXhtml.py error.pyserialize.py validate.py tstURI.py cutnpaste.py xpathret.pyxpath.py outbuf.py inbuf.pyresolver.py regexp.py reader.py reader2.py reader3.py reader4.py reader5.py reader6.py reader7.py walker.py ctxterror.py readererr.py relaxng.pythread2.py tst.xml valid.xml invalid.xml; \ do ../.././install-sh -c -m 0644 ./$test /bscs/bscs/prod/523/WORK/MP/NORTEL/IN/MEXICO/CDRS/ATS/MONITOREO/reportes_Milton/libxml/share/doc/libxml2-python-2.6.4/examples ; done) This an issue?, or bug? Greetings. -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
Roy Smith r...@panix.com wrote in message news:roy-181632.07571818082...@news.panix.com... In article qkoao.53872$gq5.12...@hurricane, BartC ba...@freeuk.com wrote: Remember, the old hardcopy terminals used to produce 132-character-wide listings. Those of you who think old hardcopy terminals did 132 wide obviously don't remember the ASR-33 :-) ASR33s I think might have been 72 columns wide (and punched cards had a similar restriction). Yeah, I was trying to remember if it was 72 or 80. Hmmm, looks like you're right, it *is* 72 (http://www.pdp8.net/asr33/asr33.shtml). Punched cards (at least the common ones used by an 029 or 129 punch machine) were 80 columns. The 72 column restriction was an artificial one imposed by some programming languages such as Fortran. Columns 73-80 could be used to punch a sequence number, so that if you dropped your deck, you could re-assemble it by running it through a card sorter. I'm sure there was a continuation column too. That would mean long lines had to be split up, but if the width was longer, that would not be necessary. However, lineprinter output was more likely to be 132 columns. Yeah, but I wouldn't call a line printer a terminal. Source code tended to be perused and marked up on a printout, then corrected at a terminal. So the terminal's width was less important, until fast VDUs came in then printouts were used less, and it made sense to adjust to common 25x80 displays. (I tend to use 60x100 now, sometimes even wider; editing using 25x80 now is like doing keyhole surgery...) -- bartc -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen calling httpd reload never finishes
On Aug 17, 8:14 pm, Albert Hopkins mar...@letterboxes.org wrote: On Tue, 2010-08-17 at 12:55 -0700, Nan wrote: Hi folks -- I have a Python script running under Apache/mod_wsgi that needs to reload Apache configs as part of its operation. The script continues to execute after the subprocess.Popen call. The communicate() method returns the correct text (Reloading httpd: [ OK ]), and I get a returncode of 0. But the python script (Django) that calls Popen never seems to complete (by returning an HTTP response. Any other Popen call I've tried exits properly. Here's some sample code: args = ['sudo /etc/init.d/httpd reload'] proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, close_fds=True) (stdout_txt, stderr_txt) = proc.communicate() proc.wait() logging.debug('%d %shr /%s' % (proc.returncode, stdout_txt, stderr_txt)) logging.debug('still executing') return HttpResponse('done') The logging statements are output, but the script doesn't exit. If you substitute sudo ls -l or sudo /etc/init.d/httpd configtest for sudo /etc/init.d/httpd reload, the exits properly. Any idea what I might be doing wrong? Thanks! Django runs inside apache. It's kinda weird to have an apache process restart itself and expect it to return to the caller. If the init script does like mine, reload executes apachectl -k graceful What that instructs apache to do is to restart, but only kill the process(es) when there are no more connections. So apache is waiting for your connection to close, but you are inside an HTTP request waiting for apache to restart. So you have a race condition here. It's not advisable to have apache kill itself and expect it to send a status back to you telling you it's dead. See the apache docs[1] for a better explanation. http://httpd.apache.org/docs/2.0/stopping.html#graceful Ah, I'd been told that there would be no conflict, and that this was just reloading the configuration, not restarting Apache. I do need the web app to instruct Apache to reload because just before this it's creating new VirtualHosts that need to be recognized. Is there a better way to do this (e.g. to say start doing this once I'm finished)? I'm getting a status code and output from the call before the Django script stops executing... Is there a way to stop waiting for the process to complete once I have those? -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
On 08/18/2010 05:11 AM, Stefan Schwarzer wrote: Hi Lie, On 2010-08-18 12:02, Lie Ryan wrote: On 08/17/10 12:59, AK wrote: On 08/16/2010 10:42 PM, James Mills wrote: My personal opinion (despite monitors being wider) is the horizontal scrolling isn't worth it. Stick to a 80-char width. But.. why horizontal scrolling, isn't autowrap much better than that? Do you seriously use autowrapper when writing code? I think he means wrapping on the screen, not actually inserting line breaks. Stefan Yes, exactly (:set wrap in Vim). -andrei -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Problem but tough for me if i want it in linear time
On Mon, 2010-08-16 at 23:17 +, Steven D'Aprano wrote: On Mon, 16 Aug 2010 20:40:52 +0200, Frederic Rentsch wrote: How about [obj for obj in dataList if obj.number == 100] That should create a list of all objects whose .number is 100. No need to cycle through a loop. What do you think the list comprehension does, if not cycle through a loop? -- Steven What I think is that list comprehensions cycle through a loop a lot faster than a coded loop (for n in ...:). As at the time of my post only coded loops had been proposed and the OP was concerned about speed, I thought I'd propose a list comprehension. I guess my explanation was poorly phrased. Thanks for the reminder. Frederic -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 support for PyWin32
On 18/08/2010 12:54, paulo.jpi...@gmail.com wrote: Hi everyone, does anyone know when PyWin is going to support Python 2.7? I tried to look for information, but to no avail. Thanks in advance, Paulo It already does and has done for a while: http://sourceforge.net/projects/pywin32/files/ TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
On Wed, 18 Aug 2010 23:18:06 +1200 Lawrence D'Oliveiro l...@geek-central.gen.new_zealand wrote: Might I suggest (guessing at the argument keywords here) : self.expiration_date = translate_date \ ( TheText = find(response, 'MPNExpirationDate').text, ToFormat ='%Y-%m-%d', FromFormat ='%m%d%Y' ) I sometimes use a backslash continuation but it always feels like a failure to me. It's an irrational reaction and I'm not sure why I feel like that. However, if you are going to do it in order to line up the parenthese I would prefer this style. self.expiration_date = translate_date \ ( TheText = find(response, 'MPNExpirationDate').text, ToFormat ='%Y-%m-%d', FromFormat ='%m%d%Y' ) This way you can see not only the block structure at a glance but also the block starter that it is part of. Presumably FromFormat should be localizable, rather than hard-coded. See, that’s the kind of thing you notice when you think about the code in this way. The other thing that jumps out at me is having the input format different than the output format. In any case you need a better date input function. There's no reason in this day and age to force users into a particular input form. You should think about creating a utility function that converts any date that is unambiguous. My scripts generally accept all of the following. Sep 1 2010 september 1, 2010 2010-9-1 (I have never seen Y/D/M format) 2010/9/1 2010 9 1 12/25/2010 25/12/2010 2010/12/25 It fails on the following. sep 31 2010 (impossible) 2010/25/12 (impossible - Y/D/M never happens) 9/1/2010 (ambiguous - there is no consistiency when year is last field) foo (not a date) -- D'Arcy J.M. Cain da...@druid.net | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
On Wed, 18 Aug 2010 10:57:00 +0200 Jean-Michel Pichavant jeanmic...@sequans.com wrote: D'Arcy J.M. Cain wrote: You can extend this if there are complicated sub-calls. Probably overkill for this example but here is the idea. self.expiration_date = translate_date( find( response, 'MPNExpirationDate', ).text, '%Y-%m-%d', '%m%d%Y' ) I also moved the closing brace down to align with the line that opened that block. If this is supposed to convice 80+ chars users, that's an epic failure :) This is exactly the kind of layout I'm happy to not use by not caring about the line width. As I said above, this was overkill designed to show the idea. Of course I would never split up short calls like that in real code. -- D'Arcy J.M. Cain da...@druid.net | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Required Buy Palm Jumeirah aprt AND Springs villa, 050-8320722
Dear I have a client who is looking to buy apartment and Villa : 1. the palm jumeirah 3 bed + maid room sea view only (any building) 2. springs type 3E 3. springs type 3M 4. springs type 4E Please send me your direct availabilities, or call me, viewing tomorrow, thank you! Peter Wong F.H 王福兴 (个人注册RERA BRN: 8866) Mob 手提 : +971 50 83 20 722 Fax传真 : +971 4 32 30 895 E-mail 电邮 : peterwfh2...@gmail.com Company 公司 : Pinky Real Estate Broker冰奇房地产 (公司注册RERA ORN: 1866) Website: http://groups.google.com/group/dubai-property-club -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 support for PyWin32
Thanks for the heads up. My error was to only look for the green download button. There you still get 2.6 as default download. -- Paulo On Aug 18, 4:28 pm, Tim Golden m...@timgolden.me.uk wrote: On 18/08/2010 12:54, paulo.jpi...@gmail.com wrote: Hi everyone, does anyone know when PyWin is going to support Python 2.7? I tried to look for information, but to no avail. Thanks in advance, Paulo It already does and has done for a while: http://sourceforge.net/projects/pywin32/files/ TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen calling httpd reload never finishes
On Wed, 2010-08-18 at 06:58 -0700, Nan wrote: Ah, I'd been told that there would be no conflict, and that this was just reloading the configuration, not restarting Apache. I do need the web app to instruct Apache to reload because just before this it's creating new VirtualHosts that need to be recognized. Is there a better way to do this (e.g. to say start doing this once I'm finished)? I'm getting a status code and output from the call before the Django script stops executing... Is there a way to stop waiting for the process to complete once I have those? I have a wireless router with a built in web server. Sometimes it needs to reload it's config. Basically what it's doing is rebooting the entire router (I can see this if I'm actuall watching the router). All it is doing, I'm pretty sure, is calling some program that forks another process and then exits the main program. The forked process then reboots the router. Meanwhile before that happens the web server sends a response. Basically in the response it sends an HTTP Refresh with x number of seconds. Presumably x is longer than the time it requires for the router to reboot. The router reboots, the browser refreshes and viola. You probably need to so something similar in that your request calls a program that forks off and restarts apaches. It should probably not do so immediately so that your request has time to send a response with a refresh header (but that shouldn't take long). After a second or so, apache will have restarted and the browser will have refreshed. so (untested): def reload(request): subprocess.call(['my_apache_reloader']) # this should fork and exit response = HttpResponse() response['Refresh']='3; url=%s' % reverse(home) # chk back in 3 secs return response BTW There is a Django mailing list where this might be more appropriate to discuss. -a -- http://mail.python.org/mailman/listinfo/python-list
Problem Creating NewLines in PDF
Hello I am generating a PDF in web2py but its ignoring my line breaks. randname = random.randrange(1, 10001) styles = getSampleStyleSheet() title = My Title doc = SimpleDocTemplate(primer.pdf) story = [] story.append(Paragraph(strftime(%a, %d %b %Y %H:%M:%S, gmtime()),styles[Heading2])) para = ParagraphStyle(name=output, fontName='Helvetica', fontSize=12) story.append(Paragraph(str(result_list), para)) doc.build(story) response.headers['Content-Type']='application/pdf' response.headers['Content-Disposition'] = 'attachment;filename='+str(randname)+'-.pdf' return response.stream(open(primer.pdf, 'rb')) result_list is a generated list. The pdf ignores line breaks and outputs it as a list so [' '] are included also. Any idea how I can create line breaks and get rid of the [' '] *cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem Creating NewLines in PDF
Andrew Evans wrote: Hello I am generating a PDF in web2py but its ignoring my line breaks. randname = random.randrange(1, 10001) styles = getSampleStyleSheet() title = My Title doc = SimpleDocTemplate(primer.pdf) story = [] story.append(Paragraph(strftime(%a, %d %b %Y %H:%M:%S, gmtime()),styles[Heading2])) para = ParagraphStyle(name=output, fontName='Helvetica', fontSize=12) story.append(Paragraph(str(result_list), para)) str(result_list) is converting the list into a string. Did you mean to do that? doc.build(story) response.headers['Content-Type']='application/pdf' response.headers['Content-Disposition'] = 'attachment;filename='+str(randname)+'-.pdf' return response.stream(open(primer.pdf, 'rb')) result_list is a generated list. The pdf ignores line breaks and outputs it as a list so [' '] are included also. Any idea how I can create line breaks and get rid of the [' '] -- http://mail.python.org/mailman/listinfo/python-list
Using re.sub with %s
Having trouble using %s with re.sub test = '/my/word/whats/wrong' re.sub('(/)word(/)', r'\1\%s\2'%'1000', test) return is /my/@0/whats/wrong however if I cast a value with letters as opposed to numbers re.sub('(/)word(/)', r'\1\%s\2'%'gosh', test) return is /my/gosh/whats/wrong Any help would be good. I've tried passing the value as an int, or recasting that value as something else, passing it as a raw string, removing the r and just double escaping the groups. Brandon L. Harris -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
On 2010-08-18, D'Arcy J.M. Cain da...@druid.net wrote: The other thing that jumps out at me is having the input format different than the output format. In any case you need a better date input function. There's no reason in this day and age to force users into a particular input form. You should think about creating a utility function that converts any date that is unambiguous. My scripts generally accept all of the following. Under the hood, translate_date just use strptime and strftime, so the formats are whatever those functions support. Moreover, I'm converting one known format (the one in the XML) to another required format (the one required by another program). There's no need to guess the format. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 17, 2:44 pm, Baba raoul...@gmail.com wrote: On Aug 16, 6:28 pm, cbr...@cbrownsystems.com cbr...@cbrownsystems.com wrote: First, suppose d = gcd(x, y, z); then for some x', y', z' we have that x = d*x', y = d*y', z = d*z'; and so for any a, b, c: could you explain the notation? what is the difference btw x and x' ? what is x = d*x', y supposed to say? x', y', z' are names for three natural numbers; I could have chosen r, s, t. x=d*x' above simply notes that since x is divisible by d, it can be written as the product of d and some other natural number, and the same is true for both y and z. therefore sums of multiples of x, y and z are always divisible by d. To go the other way, if d = 1, then there exists integers (not neccessarily positive) such that a*x + b*y + c*z = 1 what's the link with 6*a+9*b+20*c=n except the similarity? The link is that it shows that if we have some u, v, and w with 6*u + 9*v + 20*w = n, and we can find some a, b, and c which satisfy 6*a + 9*b + 20*c = 1 then if we let r = u + a, s = v + b, and t = w + c, we get that 6*r + 9*s + 20*t = n+1 although r, s, and t are not neccessarily positive numbers (as they must be to solve your original problem). However, if u, v, and w are sufficiently large compared to a, b, and c, then r, s and t WILL all be positive. But we can only find such an a,b, and c because the gcd of 6, 9, and 20 is equal to 1; that is why you can't solve this problem for nugget pack sizes 6, 12, and 21. Note that if there is one solution (a,b,c) to the gcd equation, there infinitely many tuples (a,b,c) which satisfy the gcd equation, for example: 6*0+ 9*9+ 20*(-4) = 1 6*(-5) + 9*(-1) + 20*2= 1 6*2+ 9*1+ 20*(-1) = 1 So the proof I gave regarded the /existence/ of a largest unobtainable, not an algorithm for obtaining one. However from the last of those three examples, we can see (details are in my original proof) that the largest unobtainable must be less than 6*0+ 9*0+ 20*(1*5) = 100 so it is potentially helpful for finding an upper bound to the problem. furthermore i came across this: For k = 3, efficient algorithms have been given by Greenberg and Davison ; if x1 x2 x3, these algorithms run in time bounded by a polynomial in log x3. Kannan gave a very complicated algorithm that runs in polynomial time in log xk if k is fixed, but is wildly exponential in k. However, Ram´ırez Alfons´ın proved that the general problem is NP-hard, under Turing reductions, by reducing from the integer knapsack problem. So it seems very likely that there is no simple formula for computing g(x1, x2, . . . , xk) for arbitrary k. source:http://arxiv.org/PS_cache/arxiv/pdf/0708/0708.3224v1.pdf i would be interested in the answer to problem 3: explain in English why the theorem is true I haven't looked at the link; but to be honest it's unlikely you would understand it if you are having trouble with the much simpler question regarding solutions in the case of 6, 12, and 21. Cheers - Chas -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem Creating NewLines in PDF
Hello yes This line doesn't seem to want to accept a list for some strange reason story.append(Paragraph(str(result_list), para)) *cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi Chas Thanks for that and i agree on your last remark :) re the number of required consecutive passes required: The number of required consecutive passes is equal to the smallest number because after that you can get any amount of nuggets by just adding the smallest nugget pack to some other number. This is only true if gcd(a,b,c)=1. Thanks to all for the help in getting to the bottom of the exercise. I have truly enjoyed this and most importantly i have learned some new things. Hadn't really done any mathematics in a long time and only starting programming so this was good to get up to speed. kind regards to everyone! Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: Using re.sub with %s
On Wednesday 18 August 2010, it occurred to Brandon Harris to exclaim: Having trouble using %s with re.sub test = '/my/word/whats/wrong' re.sub('(/)word(/)', r'\1\%s\2'%'1000', test) return is /my/@0/whats/wrong This has nothing to do with %, of course: re.sub('(/)word(/)', r'\1\%d\2'%1000, test) '/my/@0/whats/wrong' re.sub('(/)word(/)', r'\1\1000\2', test) '/my/@0/whats/wrong' let's see if we can get rid of that zero: re.sub('(/)word(/)', r'\1\100\2', test) '/my/@/whats/wrong' so '\100' appears to be getting replaced with '@'. Why? '\100' '@' This is Python's way of escaping characters using octal numbers. chr(int('100', 8)) '@' How to avoid this? Well, if you wanted the literal backslash, you'll need to escape it properly: print(re.sub('(/)word(/)', r'\1\\1000\2', test)) /my/\1000/whats/wrong If you didn't want the backslash, then why on earth did you put it there? You have to be careful with backslashes, they bite ;-) Anyway, you can simply do the formatting after the match. re.sub('(/)word(/)', r'\1%d\2', test) % 1000 '/my/1000/whats/wrong' Or work with match objects to construct the resulting string by hand. - Thomas -- http://mail.python.org/mailman/listinfo/python-list
expression in an if statement
Hi, In this code: if set(a).union(b) == set(a): pass Does Python compute set(a) twice? Thanks in advance. Ernest -- http://mail.python.org/mailman/listinfo/python-list
Re: expression in an if statement
ernest wrote: In this code: if set(a).union(b) == set(a): pass Does Python compute set(a) twice? a = abc b = def _set = set def set(x): ... print computing set(%r) % x ... return _set(x) ... if set(a).union(b) == set(a): pass ... computing set('abc') computing set('abc') So yes, set(a) is computed twice. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 18, 10:52 am, Baba raoul...@gmail.com wrote: Hi Chas Thanks for that and i agree on your last remark :) re the number of required consecutive passes required: The number of required consecutive passes is equal to the smallest number because after that you can get any amount of nuggets by just adding the smallest nugget pack to some other number. This is only true if gcd(a,b,c)=1. Thanks to all for the help in getting to the bottom of the exercise. I have truly enjoyed this and most importantly i have learned some new things. Hadn't really done any mathematics in a long time and only starting programming so this was good to get up to speed. kind regards to everyone! Baba Happy to be of service! Cheers - Chas -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On 18 Aug, 11:09, spinoza spinoza1...@yahoo.com wrote: On Aug 18, 1:21 am, Standish P stnd...@gmail.com wrote: This you might want to take this to the Forth people because they are marketing their language as a cure for all that plagues programming today. No, they're not. That I agree with. Stack based languages have seen better days and Forth (and the SL/1 language I supported with compilers at Bell-Northern Research) were last in fashion in the 1970s. Processors seldom could multitask, so it wasn't recognized that the stack could be a performance bottleneck, where stack operations cannot be pipelined or executed in parallel. John Hennessy of Stanford and MIPS made the stack must die case at ACM ASPLOS in 1987. Niklaus Wirth was also at this conference at which I was a fly on the wall, maintaining that the stack was good for reliability and verifiability of software. Forth had a snowball's chance because it forces ordinary programmers to think in Reverse Polish notation and is for the above reasons hard to pipeline, although of course it can be pipelined. I really don't understand much of what you're saying here; Forth can be implemented on processors that have several hardware assisted stacks, 1 stack or even no stack at all. Multitasking? Why's that a problem? And why is it hard to pipeline? Are you thinking of a specific processor? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using re.sub with %s
Thomas Jollans wrote: On Wednesday 18 August 2010, it occurred to Brandon Harris to exclaim: Having trouble using %s with re.sub test = '/my/word/whats/wrong' re.sub('(/)word(/)', r'\1\%s\2'%'1000', test) return is /my/@0/whats/wrong This has nothing to do with %, of course: re.sub('(/)word(/)', r'\1\%d\2'%1000, test) '/my/@0/whats/wrong' re.sub('(/)word(/)', r'\1\1000\2', test) '/my/@0/whats/wrong' let's see if we can get rid of that zero: re.sub('(/)word(/)', r'\1\100\2', test) '/my/@/whats/wrong' so '\100' appears to be getting replaced with '@'. Why? '\100' '@' This is Python's way of escaping characters using octal numbers. chr(int('100', 8)) '@' How to avoid this? Well, if you wanted the literal backslash, you'll need to escape it properly: print(re.sub('(/)word(/)', r'\1\\1000\2', test)) /my/\1000/whats/wrong If you didn't want the backslash, then why on earth did you put it there? You have to be careful with backslashes, they bite ;-) Anyway, you can simply do the formatting after the match. re.sub('(/)word(/)', r'\1%d\2', test) % 1000 '/my/1000/whats/wrong' Or work with match objects to construct the resulting string by hand. You can stop group references which are followed by digits from turning into octal escapes in the replacement template by using \gn instead: print r'\1%s' % '00' \100 print r'\g1%s' % '00' \g100 -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On 8/18/2010 1:38 PM, cbr...@cbrownsystems.com wrote: To go the other way, if d = 1, then there exists integers (not neccessarily positive) such that a*x + b*y + c*z = 1 That fact is non-trivial, although the proof isn't *too* hard [1]. I found it interesting to demonstrate the simpler case (a*x + b*y = 1) by instrumenting the classic Python implementation of Euclid's Algorithm: def show_gcd(a,b): find GCD of two integers, showing intermediate steps in both remainder and linear-combination forms while b: if a%b 0: rem_form = %d == %d*(%d), rem %d % (a, b, a/b, a%b) equ_form = %d == %d*(1) + %d*(-%d) % (a%b, a, b, a/b) print %3d %3d %-30s %s % (a,b, rem_form, equ_form) a,b = b, a%b print \nGCD is, a show_gcd(124, 39) 124 39 124 == 39*(3), rem 7 7 == 124*(1) + 39*(-3) 39 7 39 == 7*(5), rem 4 4 == 39*(1) + 7*(-5) 7 4 7 == 4*(1), rem 3 3 == 7*(1) + 4*(-1) 4 3 4 == 3*(1), rem 1 1 == 4*(1) + 3*(-1) Performing successive substitutions, bottom to top, using the equations in the right-hand column: 1 == 4*(1) + 3*(-1) == 4*(1) + (7*(1) + 4*(-1))*(-1) == 4*(2) + 7*(-1) == (39*(1) + 7*(-5))*(2) + 7*(-1) == 39*(2) + 7*(-11) == 39*(2) + (124*(1) + 39*(-3))*(-11) == 39*(35) + 124*(-11) What could be simpler! :-) -John [1] http://math453fall2008.wikidot.com/lecture-3 (GCD as a linear combonation [sic]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem Creating NewLines in PDF
Andrew Evans wrote: Hello yes This line doesn't seem to want to accept a list for some strange reason story.append(Paragraph(str(result_list), para)) From the documentation it appears that you need to pass a string. You're just passing the result of str(result_list), which isn't giving you what you want: result_list = ['hello', 'world'] print str(result_list) ['hello', 'world'] But what do you want? Do you just want to concatenate the entries into a single string (assuming they're all strings)? print .join(result_list) helloworld Or with some kind of separator between them? print .join(result_list) hello world -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem Creating NewLines in PDF
Hello ty for the fast replies This is the string I am using for the PDF I was able to create new lines using the HTML br tag which is what I wanted a method to create new lines search_str=Position: (%d) - Keyword: (%s) - Domain (%s) br /br / % (idx+1, target_keyword, session.target_domain) result_list.append(search_str) however it maintains these characters in the text of the generated PDF [' ', ' '] with the string in between those I just want to be able to out put the string with no extra characters I assume these characters are there because its a list .. From the documentation it appears that you need to pass a string. You're just passing the result of str(result_list), which isn't giving you what you want: -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 support for PyWin32
On 8/18/2010 8:33 AM, Mark Lawrence wrote: On 18/08/2010 12:54, paulo.jpi...@gmail.com wrote: Hi everyone, does anyone know when PyWin is going to support Python 2.7? I tried to look for information, but to no avail. Thanks in advance, Paulo It was created on 2009-07-08!!! See:- http://sourceforge.net/projects/pywin32/files/pywin32/ Considering that that is months before the first alpha release and a year before the final of 2.7, truly amazing. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem Creating NewLines in PDF
Andrew Evans wrote: Hello ty for the fast replies This is the string I am using for the PDF I was able to create new lines using the HTML br tag which is what I wanted a method to create new lines search_str=Position: (%d) - Keyword: (%s) - Domain (%s) br /br / % (idx+1, target_keyword, session.target_domain) result_list.append(search_str) however it maintains these characters in the text of the generated PDF [' ', ' '] with the string in between those I just want to be able to out put the string with no extra characters I assume these characters are there because its a list As I said, if you just want to join a list of strings into one string, then use .join(result_list): story.append(Paragraph(.join(result_list), para)) -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On 8/18/10 12:09 AM, spinoza wrote: On Aug 18, 1:21 am, Standish Pstnd...@gmail.com wrote: Garbage collection doesn't use a stack. It uses a heap, which is in the abstract a collection of memory blocks of different lengths, divided into two lists, generally represented as linked lists: 1. A list of blocks that are free and may be used to store new data 2. A list of blocks that are in use, or haven't been freed (yet) Is this all that a heap is or is there more to it ? I have been looking for simple but complete explanation of heap for a while and not gotten to it. I think I am looking for a stack allocation on the same pattern. In a disk, a file is fragmented in many contiguous blocks and is accessed automatically. Stacks (at least as far as Forth uses them) and heaps are fundamentally different things. ... However, data structures of variable size, or data structures that merely take up a lot of space, don't play nice with others on the stack, so, we place their address on the stack and store them in another place, which was named the heap, probably, as a sort of witticism. In Forth, they go in data space, which might or might not be in the dictionary, and is almost never in a dynamically managed heap; certainly not on a stack. ... No, they're not. Stack based languages have seen better days and Forth (and the SL/1 language I supported with compilers at Bell-Northern Research) were last in fashion in the 1970s. Processors seldom could multitask, so it wasn't recognized that the stack could be a performance bottleneck, where stack operations cannot be pipelined or executed in parallel. Lol. Forth supported multitasking on every processor it was implemented on in the 70's, with blazing speed compared to competitive techniques. I have never seen stack operations to be a bottleneck. ... Forth had a snowball's chance because it forces ordinary programmers to think in Reverse Polish notation and is for the above reasons hard to pipeline, although of course it can be pipelined. Mostly it had a snowball's chance because it was never picked up by the CS gurus who, AFAIK, never really took a serious look at it. Cheers, Elizabeth -- == Elizabeth D. Rather (US Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com Forth-based products and Services for real-time applications since 1973. == -- http://mail.python.org/mailman/listinfo/python-list
Re: scipy / stats : quantiles using sample weights from survey data
In article 94bb6313-1b09-4eeb-9969-07d76048a...@m35g2000prn.googlegroups.com, Christopher Barrington-Leigh christophe...@gmail.com wrote: There is a function scipy.stats.mstats.mquantiles that returns quantiles for a vector of data. But my data should not be uniformly weighted in an estimate of the distribution, since they are from a survey and come with estimated sampling weights based on the stratification used in sampling. Is there a routine to calculate these quantiles taking into account the survey weights? I can find nothing, so maybe you have had the same problem and written something. You should ask on the scipy mailing list. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ ...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box. --Cliff Wells -- http://mail.python.org/mailman/listinfo/python-list
Re: assigning variables from list data
In article mailman.1627.1281018398.1673.python-l...@python.org, Chris Hare ch...@labr.net wrote: cursor.execute('select * from net where NetNumber 0') Unless your table is guaranteed to never change layout, I suggest that instead listing fields is a Good Idea: cursor.execute('select netNumber, netType, from net where NetNumber 0') Then the tuple unpack suggested by other posters will never fail. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ ...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box. --Cliff Wells -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 18, 11:50 am, John Posner jjpos...@optimum.net wrote: On 8/18/2010 1:38 PM, cbr...@cbrownsystems.com wrote: To go the other way, if d = 1, then there exists integers (not neccessarily positive) such that a*x + b*y + c*z = 1 That fact is non-trivial, although the proof isn't *too* hard [1]. I found it interesting to demonstrate the simpler case (a*x + b*y = 1)... And to get the more general case, if we write (a,b) for gcd of and b, we can think of the , as a binary operator that you can show is associative: ((a,b), c) = (a, (b,c)) = (a, b, c) and so a proof that exists x,y with a*x + b*y = (a,b) can then be extended to a proof for an arbitrary number of elements. (Oddly, , is also distributive over itself: ((a,b), c) = ((a,c), (b,c))...) Cheers - Chas -- http://mail.python.org/mailman/listinfo/python-list
Re: when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray'
On Wed, 18 Aug 2010 05:56:27 -0700, Duim wrote: Although I'm sure somewhere this issue is discussed in this (great) group, I didn't know the proper search words for it (although I tried). I'm using python (2.6) scientifically mostly, and created a simple class to store time series (my 'Signal' class). I need this class to have a possibility to get multiplied by an array, but pre and post multiplication have different mathematical outcomes ( basically A* B != B*A ) . Post multiplication by an array works fine defining __mul__ in the Signal class, but pre multiplication does not. It keeps trying to multiply all elements separately instead to send this array to my __rmul__ function. How can I fix this without the need for a separate 'multiplysignal(A,B)' function? Make Signal a subclass of numpy.ndarray. If one operand is a subclass of the other, its __rmul__ will be preferred to the parent's __mul__. In the absence of a subclass-superclass relationship, the LHS's __mul__ is preferred to the RHS's __rmul__, so the RHS's __rmul__ is only called if the LHS lacks a __mul__ method or if the method refuses its argument (returns NotImplemented). Likewise for other reflected methods. -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen calling httpd reload never finishes
On Aug 18, 12:37 pm, Albert Hopkins mar...@letterboxes.org wrote: On Wed, 2010-08-18 at 06:58 -0700, Nan wrote: Ah, I'd been told that there would be no conflict, and that this was just reloading the configuration, not restarting Apache. I do need the web app to instruct Apache to reload because just before this it's creating new VirtualHosts that need to be recognized. Is there a better way to do this (e.g. to say start doing this once I'm finished)? I'm getting a status code and output from the call before the Django script stops executing... Is there a way to stop waiting for the process to complete once I have those? I have a wireless router with a built in web server. Sometimes it needs to reload it's config. Basically what it's doing is rebooting the entire router (I can see this if I'm actuall watching the router). All it is doing, I'm pretty sure, is calling some program that forks another process and then exits the main program. The forked process then reboots the router. Meanwhile before that happens the web server sends a response. Basically in the response it sends an HTTP Refresh with x number of seconds. Presumably x is longer than the time it requires for the router to reboot. The router reboots, the browser refreshes and viola. You probably need to so something similar in that your request calls a program that forks off and restarts apaches. It should probably not do so immediately so that your request has time to send a response with a refresh header (but that shouldn't take long). After a second or so, apache will have restarted and the browser will have refreshed. so (untested): def reload(request): subprocess.call(['my_apache_reloader']) # this should fork and exit response = HttpResponse() response['Refresh']='3; url=%s' % reverse(home) # chk back in 3 secs return response BTW There is a Django mailing list where this might be more appropriate to discuss. -a Sadly, questions about subprocess spawning on the Django lists seem to get referred back to the Python lists when they get an answer at all. You've been very helpful, though, so thank you. I think I'll have to mark in the database when the server needs restarting, and run a cron job to check that and reload Apache from a non-Apache process. It will mean delayed creation of the Virtual Hosts and no immediate feedback to indicate success or failure, but it doesn't look like there's much alternative. -- http://mail.python.org/mailman/listinfo/python-list
q.join() is probably the wrong method for you
The join() method is all about waiting for all the tasks to be done. If you don't care whether the tasks have actually finished, you can periodically poll the unfinished task count: stop = time() + timeout while q.unfinished_tasks and time() stop: sleep(1) This loop will exist either when the tasks are done or when the timeout period has elapsed. Raymond On Thursday, June 17, 2010 5:52 PM pacopyc wrote: Hi, I am trying to work with threads and I need your help. This is code: from threading import Thread from Queue import Queue import time import random def test_fun (k,q,t): time.sleep(t) print hello world from thread + str(q.get()) + (sleep time = + str(t) + sec.) q.task_done() queue = Queue() for i in range (1,10): queue.put(i) for j in range(queue.qsize()): num = random.randint(1,30) worker = Thread(target=test_fun, args=(j,queue,num)) worker.setDaemon(True) worker.start() queue.join() Execution: hello world from thread 1 (sleep time = 5 sec.) hello world from thread 2 (sleep time = 5 sec.) hello world from thread 3 (sleep time = 6 sec.) hello world from thread 4 (sleep time = 8 sec.) hello world from thread 5 (sleep time = 10 sec.) hello world from thread 6 (sleep time = 13 sec.) hello world from thread 7 (sleep time = 18 sec.) hello world from thread 8 (sleep time = 19 sec.) hello world from thread 9 (sleep time = 20 sec.) Some questions for you: 1) Why order is always the same (thread 1, thread 2, thread 3 thread 9) and also seconds are always increasing? I do not understand. 2) I'd like to decide a max time for each thread. If max time = 7 sec. I want to print only threads with sleep time = 7 sec. How can I do? Can you modify my code? Thank you very much On Thursday, June 17, 2010 7:04 PM MRAB wrote: pacopyc wrote: 1) First it puts the numbers 1..9 into 'queue', then it starts 9 threads, giving each a number 'num'. Each thread waits for 'num' seconds ('t' in the thread). The thread with the lowest value of 'num' wakes first, gets the first entry from 'queue' (the value 1), and therefore prints thread 1. The thread with the second-lowest value of 'num' wakes next, gets the second entry from 'queue' (the value 2), and therefore prints thread 2. And so on. 2) If a thread is given a value of 'num' of more than a maximum, that thread should not print its output, but it should still get the entry from the queue (assuming that you want it to still behave the same otherwise). On Friday, June 18, 2010 5:45 PM pacopyc wrote: =3D . Ok, the problem is that I want fix a time max for each thread. For example run 10 threads (each can terminate its work in 10 sec. max fixed time) and wait them. If they finish its work in 10 sec. (for example 2 sec.) very good ... go on immediately (do not wait unnecessary time), but if a thread use more than 10 sec. stop wait (I kill it) when all threads have finished their work or when they have used all their available time (10 sec.) the program must go on (do not wait). On Friday, June 18, 2010 6:27 PM MRAB wrote: pacopyc wrote: [snip] it is not possible to kill a thread. If you want a thread to have a maximum time, the thread must check occasionally how long it has been running and terminate if necessary. Another programming language (Java) originally had the ability to kill threads, but that was later deprecated because it caused problems due to not knowing what the thread was doing when it was killed (it might have been in the middle of updating something at the time, for example, leaving the system in an inconsistent state). On Friday, June 18, 2010 6:58 PM pacopyc wrote: Ok, I understand. But is possible fix max wait time (for example 60 sec.) in main thread and check queue for task done and at the same time the remaining time. When all task have done or wait time has expired main thread go on. Is it possible? Can you write code? Thank you very much. On Friday, June 18, 2010 7:45 PM MRAB wrote: pacopyc wrote: The documentation says that queue.join() cannot have a timeout, so you might have to think of another way to achieve the same effect. You could, for example, have a results queue into which a thread puts something to indicate when it has finished, and then use the .get method on it in the main thread (the .get method can have a timeout). Submitted via EggHeadCafe - Software Developer Portal of Choice Custom Favorites Web Site with MongoDb and NoRM http://www.eggheadcafe.com/tutorials/aspnet/7fbc7a01-5d30-4cd3-b373-51d4a0e1afa8/custom-favorites-web-site-with-mongodb-and-norm.aspx -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
Elizabeth D Rather erat...@forth.com writes: Processors seldom could multitask, so it wasn't recognized that the stack could be a performance bottleneck Lol. Forth supported multitasking on every processor it was implemented on in the 70's, with blazing speed compared to competitive techniques. I have never seen stack operations to be a bottleneck. I think multitasking in that post refers to superscalar execution, which wasn't done in the 1970's except on supercomputers. That the stack is a bottleneck is the precise reason that optimizing Forth compilers do complicated flow analysis to translate stack operations into register operations. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python why questions
On 08/17/2010 10:15 PM, Russ P. wrote: On Aug 7, 5:54 am, D'Arcy J.M. Cainda...@druid.net wrote: Would said beginner also be surprised that a newborn baby is zero years old or would it be more natural to call them a one year old? Zero based counting is perfectly natural. You're confusing continuous and discrete variables. Time is a continuous variable, but a list index is discrete. Take a look at any numbered list, such as the top ten football teams or the top ten software companies. Have you ever seen such a list start with zero? If so, where? I sure haven't. When I studied linear algebra way back, vector and matrix indices also always started with one, and I assume they still do. The convention of starting with zero may have had some slight performance advantage in the early days of computing, but the huge potential for error that it introduced made it a poor choice in the long run, at least for high-level languages. I have to agree, there's innumerable number of examples where sequential number of an item in a series is counted starting with one. Second loaf of bread; third day of vacation, first cup of tea today, first gray hair, 50th anniversary, 2nd century AD, and approximately a gazillion other examples. Contrast this with _one_ example that was repeated in this thread of there being ground floor, 1st floor, 2nd, and so on. However! Consider that ground floor is kind of different from the other floors. It's the floor that's not built up over ground, but is already there -- in case of the most primitive dwelling, you can put some sawdust over the ground, put a few boards overhead and it's a home, although probably not a house. But does it really have what can be officially called a floor? On a more practical angle, ground floors usually have the lobby, receptionists, storefronts and stores, etc; while 1st floor and up are business/residential. I think different numbering from pretty much all other things out there gives you a hint that the ground floor is a different animal. -andrei -- http://mail.python.org/mailman/listinfo/python-list
Re: Python why questions
On 08/17/2010 10:15 PM, Russ P. wrote: On Aug 7, 5:54 am, D'Arcy J.M. Cainda...@druid.net wrote: Would said beginner also be surprised that a newborn baby is zero years old or would it be more natural to call them a one year old? Zero based counting is perfectly natural. You're confusing continuous and discrete variables. Time is a continuous variable, but a list index is discrete. Take a look at any numbered list, such as the top ten football teams or the top ten software companies. Have you ever seen such a list start with zero? If so, where? I sure haven't. When I studied linear algebra way back, vector and matrix indices also always started with one, and I assume they still do. The convention of starting with zero may have had some slight performance advantage in the early days of computing, but the huge potential for error that it introduced made it a poor choice in the long run, at least for high-level languages. Besides that, the way things are now, it's almost an Abbot Costello routine: - How many folders are there? - 5 - Ok, give me the fourth one. - Here. - No, that's the last one! - That's what you said! - No, I said, fourth one! - That's what I did! - How many are there in all? - I already said, five! - You gave me the last one!! - Just like you said - fourth -- http://mail.python.org/mailman/listinfo/python-list
Re: expression in an if statement
On 8/18/2010 11:24 AM, ernest wrote: Hi, In this code: if set(a).union(b) == set(a): pass Does Python compute set(a) twice? CPython does. Shed Skin might optimize. Don't know about Iron Python. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On 8/18/2010 1:32 PM, Paul Rubin wrote: Elizabeth D Rathererat...@forth.com writes: Processors seldom could multitask, so it wasn't recognized that the stack could be a performance bottleneck Lol. Forth supported multitasking on every processor it was implemented on in the 70's, with blazing speed compared to competitive techniques. I have never seen stack operations to be a bottleneck. I think multitasking in that post refers to superscalar execution, which wasn't done in the 1970's except on supercomputers. That the stack is a bottleneck is the precise reason that optimizing Forth compilers do complicated flow analysis to translate stack operations into register operations. Some small FORTH machines had dedicated stack hardware. On each CPU cycle, the CPU could do one stack access, one main memory access, and one return stack access. This was before cacheing; those CPUs were slow relative to their memory, so a non-cached one-instruction-per-clock machine made sense. In the superscalar era, there's not much of an advantage to avoiding stack accesses. x86 superscalar machines have many registers not visible to the program, as the fastest level of cache. In practice, the top of the stack is usually in CPU registers. The huge number of programmer-visible register machines like SPARCs turned out to be a dead end. So did making all the instructions the same width; it makes the CPU simpler, but not faster, and it bulks up the program by 2x or so. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Python why questions
On Aug 18, 2:01 pm, AK andrei@gmail.com wrote: On 08/17/2010 10:15 PM, Russ P. wrote: On Aug 7, 5:54 am, D'Arcy J.M. Cainda...@druid.net wrote: Would said beginner also be surprised that a newborn baby is zero years old or would it be more natural to call them a one year old? Zero based counting is perfectly natural. You're confusing continuous and discrete variables. Time is a continuous variable, but a list index is discrete. Take a look at any numbered list, such as the top ten football teams or the top ten software companies. Have you ever seen such a list start with zero? If so, where? I sure haven't. When I studied linear algebra way back, vector and matrix indices also always started with one, and I assume they still do. The convention of starting with zero may have had some slight performance advantage in the early days of computing, but the huge potential for error that it introduced made it a poor choice in the long run, at least for high-level languages. Besides that, the way things are now, it's almost an Abbot Costello routine: - How many folders are there? - 5 - Ok, give me the fourth one. - Here. - No, that's the last one! - That's what you said! - No, I said, fourth one! - That's what I did! - How many are there in all? - I already said, five! - You gave me the last one!! - Just like you said - fourth Yes, it's confusing. Which element of a list is the first element? Wait, first is sometimes abbreviated as 1st. So is the 1st element the 0 element or the 1 element? I honestly don't know. Is the top team in the league the number 1 team -- or the number 0 team? I have yet to hear anyone call the best team the number 0 team! Unfortunately, we're stuck with this goofy numbering system in many languages. Fortunately, the trend is away from explicit indexing and toward for loops when possible. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python why questions
On 18/08/2010 22:47, Russ P. wrote: On Aug 18, 2:01 pm, AKandrei@gmail.com wrote: On 08/17/2010 10:15 PM, Russ P. wrote: On Aug 7, 5:54 am, D'Arcy J.M. Cainda...@druid.netwrote: Would said beginner also be surprised that a newborn baby is zero years old or would it be more natural to call them a one year old? Zero based counting is perfectly natural. You're confusing continuous and discrete variables. Time is a continuous variable, but a list index is discrete. Take a look at any numbered list, such as the top ten football teams or the top ten software companies. Have you ever seen such a list start with zero? If so, where? I sure haven't. When I studied linear algebra way back, vector and matrix indices also always started with one, and I assume they still do. The convention of starting with zero may have had some slight performance advantage in the early days of computing, but the huge potential for error that it introduced made it a poor choice in the long run, at least for high-level languages. Besides that, the way things are now, it's almost an Abbot Costello routine: - How many folders are there? - 5 - Ok, give me the fourth one. - Here. - No, that's the last one! - That's what you said! - No, I said, fourth one! - That's what I did! - How many are there in all? - I already said, five! - You gave me the last one!! - Just like you said - fourth Yes, it's confusing. Which element of a list is the first element? Wait, first is sometimes abbreviated as 1st. So is the 1st element the 0 element or the 1 element? I honestly don't know. Is the top team in the league the number 1 team -- or the number 0 team? I have yet to hear anyone call the best team the number 0 team! Unfortunately, we're stuck with this goofy numbering system in many languages. Fortunately, the trend is away from explicit indexing and toward for loops when possible. Bring back Coral 66, all is forgiven. http://www.xgc.com/manuals/xgc-c66-rm/x357.html Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: exception handling with sqlite db errors
On Aug 12, 3:31 pm, a...@pythoncraft.com (Aahz) wrote: In article 2a47b306-45d1-474a-9f8e-5b71eba62...@p11g2000prf.googlegroups.com, CM cmpyt...@gmail.com wrote: Maybe it's not much of an issue, but I think it would be a shame if occasional hangs/crashes could be caused by these (rare?) database conflicts if there is a good approach for avoiding them. I guess I could put every last write to the db in a try/except block but I thought there should be a more general solution, since that will require many such exceptions and seems inelegant. Wrap all your uses of sqlite into a function that does the try/except; you only write the code once, then. As you progress, you can also change the code to retry operations. Here's some ugly code I wrote on top of SQLObject: from sqlobject.dbconnection import registerConnection from sqlobject.sqlite.sqliteconnection import SQLiteConnection class RetrySQLiteConnection(SQLiteConnection): Because SQLite is not really concurrent, having multiple processes read/write can result in locked DB failures. In addition, SQLObject doesn't properly protect operations in transations, so you can get spurious DB errors claiming that the DB is corrupt because of foreign key integrity failures. This subclass retries DatabaseError and OperationalError exceptions. MAX_RETRIES = 4 SAFE_DB_ERROR = [ 'database disk image is malformed', 'file is encrypted or is not a database', ] def _safe_db_error(self,exception): err = str(exception).lower() for safe_err in self.SAFE_DB_ERROR: if safe_err in err: return True return False def _check_integrity(self): conn = self.getConnection() try: i = 0 while True: i += 1 try: cursor = conn.cursor() query = pragma integrity_check SQLiteConnection._executeRetry(self, conn, cursor, query) result = cursor.fetchall() if result == [('ok',)]: return True else: logging.error(Bad integrity result: %s, result) return False except DatabaseError, e: if i self.MAX_RETRIES: logging.info('integrity_check, try #%s: %s', i, e) time.sleep(2) else: logging.error('integrity_check, try #%s: %s', i, e) raise finally: self.releaseConnection(conn) def _executeRetry(self, conn, cursor, query): i = 0 while True: i += 1 try: return SQLiteConnection._executeRetry(self, conn, cursor, query) except OperationalError, e: if i self.MAX_RETRIES: logging.warn('OperationalError, try #%s: %s', i, e) time.sleep(10) else: logging.error('OperationalError, try #%s: %s', i, e) raise except DatabaseError, e: if e.__class__ is not DatabaseError: # Don't retry e.g. IntegrityError raise if not self._safe_db_error(e): # Only retry specific errors raise if not self._check_integrity(): raise if i self.MAX_RETRIES: logging.warn('DatabaseError, try #%s: %s', i, e) time.sleep(0.5) else: logging.error('DatabaseError, try #%s: %s', i, e) raise def conn_builder(): return RetrySQLiteConnection registerConnection(['retrysqlite'], conn_builder) def init(): dbpath = os.path.join(common.getSyncDataPath(), app.dbname) connection_string = retrysqlite: + dbpath global _connection _connection = connectionForURI(connection_string) -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ ...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box. --Cliff Wells Thanks, Aahz, I'll try to implement something along these lines. Che -- http://mail.python.org/mailman/listinfo/python-list
Re: expression in an if statement
On Wednesday 18 August 2010, it occurred to John Nagle to exclaim: On 8/18/2010 11:24 AM, ernest wrote: Hi, In this code: if set(a).union(b) == set(a): pass Does Python compute set(a) twice? CPython does. Shed Skin might optimize. Don't know about Iron Python. I doubt any actual Python implementation optimizes this -- how could it? The object set is clearly being called twice, and it happens to be called with the object a as a sole argument twice. What if set has side effects? A compiler could only exclude this possibility if it knew exactly what set will be at run time, which it can't. I expect that set and a have to be looked up twice, actually: set(a).union(b) might rebind either one of them. This would be considered a very rude and inappropriate thing to do, but Python usually guarantees to allow bad taste and behaviour. I might be wrong on some points here, but this is what I expect the expression (set(a).union(b) == set(a)) has to do, in any conforming implementation of Python. Please correct me if I'm wrong. 1. find out which object set refers to 2. find out which object a refers to 3. call (set) with the single positional argument (a), no keyword arguments 4. get the attribute union of the return value of [3] 5. find out which object b refers to 6. call (.union) with the single positional argument (b). 7. look up __eq__ in the __class__ of the return value of [6] 8. find out which object set refers to 9. find out which object a refers to 10. call (set) with the single positional argument (a), no keyword arguments 11. call [7] with two positional arguments: the return values [6] [10] I'm not 100% sure if there are any guarantees as to when (5) is taken care of -- what would happen if set(a) or even set(a).__getattr__ changed the global b? My list there is obviously referring to Python 3.x, so there is no __cmp__ to worry about. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unsupported Format Character '' (0x26)
nvm I got it by adding s and d respectively after each value eg %(query)s thank you all On Wed, Aug 18, 2010 at 4:35 PM, Andrew Evans randra...@gmail.com wrote: I get an error message Unsupported Format Character '' (0x26) I narrowed it down to these two variables any idea how to fix it? SEARCH_URL_0 = http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%(query)fr=sfpfr2=iscqry=http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%%28query%29fr=sfpfr2=iscqry= NEXT_PAGE_0 = http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%(query)fr=sfpxargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2Epstart=%(start)b=11http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%%28query%29fr=sfpxargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2Epstart=%%28start%29b=11 Not sure why its doing it the value in parenthesis should work %(query) etc Any ideas cheeers -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On Aug 18, 12:30 pm, Elizabeth D Rather erat...@forth.com wrote: On 8/18/10 12:09 AM, spinoza wrote: On Aug 18, 1:21 am, Standish Pstnd...@gmail.com wrote: Garbage collection doesn't use a stack. It uses a heap, which is in the abstract a collection of memory blocks of different lengths, divided into two lists, generally represented as linked lists: 1. A list of blocks that are free and may be used to store new data 2. A list of blocks that are in use, or haven't been freed (yet) Is this all that a heap is or is there more to it ? I have been looking for simple but complete explanation of heap for a while and not gotten to it. I think I am looking for a stack allocation on the same pattern. In a disk, a file is fragmented in many contiguous blocks and is accessed automatically. Stacks (at least as far as Forth uses them) and heaps are fundamentally different things. ... However, data structures of variable size, or data structures that merely take up a lot of space, don't play nice with others on the stack, so, we place their address on the stack and store them in another place, which was named the heap, probably, as a sort of witticism. In Forth, they go in data space, which might or might not be in the dictionary, and is almost never in a dynamically managed heap; certainly not on a stack. ... No, they're not. Stack based languages have seen better days and Forth (and the SL/1 language I supported with compilers at Bell-Northern Research) were last in fashion in the 1970s. Processors seldom could multitask, so it wasn't recognized that the stack could be a performance bottleneck, where stack operations cannot be pipelined or executed in parallel. Lol. Forth supported multitasking on every processor it was implemented on in the 70's, with blazing speed compared to competitive techniques. I have never seen stack operations to be a bottleneck. Forth had a snowball's chance because it forces ordinary programmers to think in Reverse Polish notation and is for the above reasons hard to pipeline, although of course it can be pipelined. Mostly it had a snowball's chance because it was never picked up by the CS gurus who, AFAIK, never really took a serious look at it. Its quite possible that the criticism is unfair, but dont you think that in part some responsibility must be borne by your organization in not doing a good job of education ? I have looked at this book you authored in the past few weeks and found a link for your convenience now. This is entitled Advanced . http://www.amazon.com/Forth-Application-Techniques-5th-Notebook/dp/1419685767/ref=sr_1_1?ie=UTF8s=booksqid=1282175842sr=8-1#reader_1419685767 Show me on what page does it explain how Forth implements dynamic binding or lexical binding and takes care of the scope of definition of the nouns ? Provide me with a link, if you kindly would, that can take me to a tutorial of Forth internals or discusses this issue. Cheers, Elizabeth She is quite humble. Take a look at this page, http://www.forth.com/resources/evolution/index.html She is currently the number 1 in the forth world and if there was a nobel prize in forth, it would go to these three. Authors Elizabeth D. Rather FORTH, Inc. 5959 W. Century Blvd. Suite 700 Los Angeles, CA 90045 Elizabeth Rather is the co-founder of FORTH, Inc. and is a leading expert in the Forth programming language. Elizabeth was a colleague of Chuck Moore back when he worked at NRAO in the early 1970s. During his development of Forth, she became the second ever Forth programmer. Since then, she has become a leading expert in the language and one of its main proponents. Elizabeth was the chair of the ANSI Technical Committee that produced the ANSI Standard for Forth (1994). She is an author of several books on Forth and gives regular training seminars on its usage. Donald R. Colburn c/o Digital Media Magic 14712 Westbury Rd. Rockville, MD 20853 Don Colburn was one of the earliest Forth users. He was one of the founders of the Forth Interest Group, and contributed to the development of the first public-domain figForth. Subsequently, he founded Creative Solutions, Inc. (CSI), which introduced MacForth™ in 1984. MacForth was the first programming language capable of running on the Macintosh when it was first introduced. Don was a member of the ANSI Technical Committee that produced the ANSI Standard for Forth (1994). He died in 2009. Charles H. Moore Computer Cowboys 40 Cedar Lane P.O. Box 127 Sierra City, CA 96125 Chuck Moore is Chairman and CTO of Green Arrays, Inc. He co-founded FORTH, Inc., in 1971 and went on to develop a Forth-based chip (RTX2000) in the mid 1980s, derivatives of which are still being used widely by NASA. At Computer Cowboys, Mr. Moore designed the Sh-Boom microprocessor and then co-founded iTv, an Internet Appliance manufacturer. During the 1990s, he used his own CAD software to design
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On Aug 17, 6:38 pm, John Passaniti john.passan...@gmail.com wrote: You asked if Forth borrowed lists from Lisp. It did not. In Lisp, lists are constructed with pair of pointers called a cons cell. That is the most primitive component that makes up a list. Forth has no such thing; in Forth, the dictionary (which is traditionally, but not necessarily a list) is a data structure that links to the previous word with a pointer. Would you show me a picture, ascii art or whatever for Forth ? I know what lisp lists look like so I dont need that for comparison. Forth must have a convention and a standard or preferred practice for its dicts. However, let me tell you that in postscript the dictionaries can be nested inside other dictionaries and any such hiearchical structure is a nested associative list, which is what linked list, nested dictionaries, nested tables are. This is in fact one of the nice things about Lisp; because all lists are created out of the same primitive cons cell, you can consistently process any list in the system. In Forth, any lists (such as the dictionary, if it is a list) are specific to their purpose and have to be treated individually. I don't know what you mean by nested-dictionaries. There is no such thing in Forth. Dictionaries don't nest. You can create wordlists, but each wordlist is flat. When most people think of a nested dictionary, they would think of a structure that would allow any arbitrary level of nesting, not a string of flat wordlists. -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
Standish P stnd...@gmail.com writes: On Aug 18, 12:30 pm, Elizabeth D Rather erat...@forth.com wrote: [...] Mostly it had a snowball's chance because it was never picked up by the CS gurus who, AFAIK, never really took a serious look at it. Its quite possible that the criticism is unfair, but dont you think that in part some responsibility must be borne by your organization in not doing a good job of education ? [snip] Show me on what page does it explain how Forth implements dynamic binding or lexical binding and takes care of the scope of definition of the nouns ? [...] Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory, or comp.lang.python. Please trim the Newsgroups line. -- Keith Thompson (The_Other_Keith) ks...@mib.org http://www.ghoti.net/~kst Nokia We must do something. This is something. Therefore, we must do this. -- Antony Jay and Jonathan Lynn, Yes Minister -- http://mail.python.org/mailman/listinfo/python-list
How to see intermediate fail results from unittest as tests are running?
Hi, I am using unittest in a fairly basic way, where I have a single file that simply defines a class that inherits from unittest.TestCase and then within that class I have a bunch of methods that start with test. Within that file, at the bottom I have: if __name__ == __main__: unittest.main() This works fine and it runs all of the testxx() methods in my file. As it runs it prints if the tests passed or failed, but if they fail, it does not print the details of the assert that made them fail. It collects this info up and prints it all at the end. Ok - my question: Is there any way to get unittest to print the details of the assert that made a test fail, as the tests are running? IE, after a test fails, I would like to see why, rather than waiting until all the tests are done. I've searched the doc and even looked at the code, and it seems the answer is no, but I'm just wondering if I'm missing something. Thanks! Margie -- http://mail.python.org/mailman/listinfo/python-list
Re: Python why questions
On Wed, 18 Aug 2010 16:56:22 -0400, AK wrote: Contrast this with _one_ example that was repeated in this thread of there being ground floor, 1st floor, 2nd, and so on. However! Consider that ground floor is kind of different from the other floors. It's the floor that's not built up over ground, but is already there -- in case of the most primitive dwelling, you can put some sawdust over the ground, put a few boards overhead and it's a home, although probably not a house. But does it really have what can be officially called a floor? That's the perfect example, although perhaps for an [apparently] unintended reason g: I think that the notion of a qualitatively different ground floor is European, or at least that's the way I remember it from my high school French class way back in the late 1970s. In the U.S., when you walk into a building (even a very tall commercial building), that's the first floor, and when you go up a level, that's the second floor, and all the room/suite/office numbers are two hundred and something. I also seem to recall that some European buildings have a mezzanine floor between the ground floor and the floor whose reference number is 1, but again, high school was a long time ago. Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Problem but tough for me if i want it in linear time
On Wed, 18 Aug 2010 16:03:58 +0200, Frederic Rentsch wrote: On Mon, 2010-08-16 at 23:17 +, Steven D'Aprano wrote: On Mon, 16 Aug 2010 20:40:52 +0200, Frederic Rentsch wrote: How about [obj for obj in dataList if obj.number == 100] That should create a list of all objects whose .number is 100. No need to cycle through a loop. What do you think the list comprehension does, if not cycle through a loop? -- Steven What I think is that list comprehensions cycle through a loop a lot faster than a coded loop (for n in ...:). I think measurement beats intuition: [st...@wow-wow ~]$ python -m timeit '[str(i) for i in xrange(10)]' 10 loops, best of 3: 84 msec per loop [st...@wow-wow ~]$ python -m timeit 'L=[] for i in xrange(10): L.append(str(i)) ' 10 loops, best of 3: 105 msec per loop But wait... we're not comparing apples with apples. There's an extra name lookup in the for-loop that the list comp doesn't have. We can fix that: [st...@wow-wow ~]$ python -m timeit 'L=[]; append = L.append for i in xrange(10): append(str(i)) ' 10 loops, best of 3: 86.7 msec per loop The difference between 84 and 86 msec is essentially measurement error. Hell, the difference between 84 and 104 msec is not terribly significant either. As at the time of my post only coded loops had been proposed and the OP was concerned about speed, I thought I'd propose a list comprehension. Yes, but the OP was concerned with asymptotic speed (big-oh notation), and both a for-loop and a list-comp are both O(N). Frankly, I think the OP doesn't really know what he wants, other than premature optimization. It's amazing how popular that is :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python why questions
On Wed, 18 Aug 2010 14:47:08 -0700, Russ P. wrote: Is the top team in the league the number 1 team -- or the number 0 team? I have yet to hear anyone call the best team the number 0 team! Why is the top team the one with the lowest number? Unfortunately, we're stuck with this goofy numbering system in many languages. Fortunately, the trend is away from explicit indexing and toward for loops when possible. Agreed on the second sentence there, but not on the first. There's nothing goofy about indexing items from 0. Yes, it does lead to slight more difficulty when discussing which item you want in *human* languages, but not in *programming* languages. The nth item is always the nth item. The only difference is whether n starts at 0 or 1, and frankly, if you (generic you, not you personally) can't learn which to use, you have no business pretending to be a programmer. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
On 8/18/10 2:23 PM, Standish P wrote: On Aug 17, 6:38 pm, John Passanitijohn.passan...@gmail.com wrote: You asked if Forth borrowed lists from Lisp. It did not. In Lisp, lists are constructed with pair of pointers called a cons cell. That is the most primitive component that makes up a list. Forth has no such thing; in Forth, the dictionary (which is traditionally, but not necessarily a list) is a data structure that links to the previous word with a pointer. Would you show me a picture, ascii art or whatever for Forth ? I know what lisp lists look like so I dont need that for comparison. Forth must have a convention and a standard or preferred practice for its dicts. However, let me tell you that in postscript the dictionaries can be nested inside other dictionaries and any such hiearchical structure is a nested associative list, which is what linked list, nested dictionaries, nested tables are. You indicated that you have a copy of Forth Application Techniques. Sections 8.1 and 8.2 cover this topic, with some drawings. Cheers, Elizabeth -- == Elizabeth D. Rather (US Canada) 800-55-FORTH FORTH Inc. +1 310.999.6784 5959 West Century Blvd. Suite 700 Los Angeles, CA 90045 http://www.forth.com Forth-based products and Services for real-time applications since 1973. == -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Problem but tough for me if i want it in linear time
On 08/18/10 21:47, Steven D'Aprano wrote: Frankly, I think the OP doesn't really know what he wants, other than premature optimization. It's amazing how popular that is :) You see, the trick to prematurely optimizing is to have a good algorithm for prematurely optimizing...the real question them becomes How can I optimize my premature-optimization algorithms to O(1) instead of O(newsgroup)? :-) -tkc PS: I'm not positive, but O(newsgroup) may asymptotically approach O(log n) if the question is well formed, but O(2^n) if flaming, indentation/line-length preferences, the meaning of OOP, SQL-parameter escaping, McNugget combinations, or suggestions that Python is just a scripting language are involved... -- http://mail.python.org/mailman/listinfo/python-list
Re: expression in an if statement
On Thu, Aug 19, 2010 at 9:12 AM, Thomas Jollans tho...@jollybox.de wrote: I doubt any actual Python implementation optimizes this -- how could it? The object set is clearly being called twice, and it happens to be called with the object a as a sole argument twice. What if set has side effects? A compiler could only exclude this possibility if it knew exactly what set will be at run time, which it can't. I expect that set and a have to be looked up twice, actually: set(a).union(b) might rebind either one of them. This would be considered a very rude and inappropriate thing to do, but Python usually guarantees to allow bad taste and behaviour. Yep. def test(): ... a = [1] ... b = [1] ... if set(a).union(b) == set(a): pass ... dis.dis(test) 2 0 LOAD_CONST 1 (1) 3 BUILD_LIST 1 6 STORE_FAST 0 (a) 3 9 LOAD_CONST 1 (1) 12 BUILD_LIST 1 15 STORE_FAST 1 (b) 4 18 LOAD_GLOBAL 0 (set) 21 LOAD_FAST0 (a) 24 CALL_FUNCTION1 27 LOAD_ATTR1 (union) 30 LOAD_FAST1 (b) 33 CALL_FUNCTION1 36 LOAD_GLOBAL 0 (set) 39 LOAD_FAST0 (a) 42 CALL_FUNCTION1 45 COMPARE_OP 2 (==) 48 JUMP_IF_FALSE4 (to 55) 51 POP_TOP 52 JUMP_FORWARD 1 (to 56) 55 POP_TOP 56 LOAD_CONST 0 (None) 59 RETURN_VALUE I might be wrong on some points here, but this is what I expect the expression (set(a).union(b) == set(a)) has to do, in any conforming implementation of Python. Please correct me if I'm wrong. You can use dis module to let Python do compiling and explaining for you -- With best regards, Daniel Kluev -- http://mail.python.org/mailman/listinfo/python-list
Re: Python why questions
On Aug 18, 7:58 pm, Steven D'Aprano steve-REMOVE- t...@cybersource.com.au wrote: On Wed, 18 Aug 2010 14:47:08 -0700, Russ P. wrote: Is the top team in the league the number 1 team -- or the number 0 team? I have yet to hear anyone call the best team the number 0 team! Why is the top team the one with the lowest number? How could it be otherwise? What is the highest number? Here's a couple of things I'd like to see just once before I die: 1. The winner of the championship game chanting, We're number zero! We're number zero! 2. The loser of the championship game chanting, We're number one! We're number one! Unfortunately, we're stuck with this goofy numbering system in many languages. Fortunately, the trend is away from explicit indexing and toward for loops when possible. Agreed on the second sentence there, but not on the first. There's nothing goofy about indexing items from 0. Yes, it does lead to slight more difficulty when discussing which item you want in *human* languages, but not in *programming* languages. The nth item is always the nth item. The only difference is whether n starts at 0 or 1, and frankly, if you (generic you, not you personally) can't learn which to use, you have no business pretending to be a programmer. Maybe goofy was too derogatory, but I think you are rationalizing a bad decision, at least for high-level languages. I don't think programming languages should always mimic human languages, but this is one case where there is no advantage to doing otherwise. Why do you think off by one errors are so common? Because the darn indexing convention is off by one! And I'd still like to know if the 1st element of aList is aList[0] or aList[1]. -- http://mail.python.org/mailman/listinfo/python-list
Simple hack to get $5000 to your Paypal account
Simple hack to get $5000 to your Paypal account At http://simplelivevideos.tk i have hidden the Paypal Form link in an image. in that website on Right Side below search box, click on image and enter your name and Paypal ID. -- http://mail.python.org/mailman/listinfo/python-list
[issue9598] untabify.py fails on files that contain non-ascii characters
Popa Claudiu pcmantic...@gmail.com added the comment: Hello. As it seems, untabify.py opens the file using the builtin function open, making the call error-prone when encountering non-ascii character. The proper handling should be done by using open from codecs library, specifying the encoding as argument. e.g. codecs.open(filename, mode, 'utf-8') instead of simply open(filename, mode). -- nosy: +Popa.Claudiu ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9598 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9631] Python 2.7 installation issue for Linux Red Hat 4.1
Prakash Palanivel spprakash...@gmail.com added the comment: After complete the installation the below error message was displayed.Kindly check and revert. ./python -E ./setup.py install \ --prefix=/usr/local/python-2.7 \ --install-scripts=/usr/local/python-2.7/bin \ --install-platlib=/usr/local/python-2.7/lib/python2.7/lib-dynload \ --root=/ make: execvp: ./python: Text file busy make: *** [sharedinstall] Error 127 -- status: closed - open ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9631 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue5215] change value of local variable in debug
Markus Pröller mproel...@googlemail.com added the comment: Hello, I changed pdb.py to the file I added in the attachment (I just used the given patch pdb_cache_f_locals.patch) Then I created the following file: import pdb def function_1(number): stack_1 = number function_2(stack_1) def function_2(number): stack_2 = number + 1 function_3(stack_2) def function_3(number): stack_3 = number + 1 pdb.set_trace() print stack_3 function_1(1) and run that file with python -i filename This is my python version: --- Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. - And here is what I did in the pdb session: c:\tst_pdb.py(14)function_3() - print stack_3 (Pdb) !print stack_3 3 (Pdb) u c:\tst_pdb.py(9)function_2() - function_3(stack_2) (Pdb) l 4 stack_1 = number 5 function_2(stack_1) 6 7 def function_2(number): 8 stack_2 = number + 1 9 - function_3(stack_2) 10 11 def function_3(number): 12 stack_3 = number + 1 13 pdb.set_trace() 14 print stack_3 (Pdb) !print stack_2 *** NameError: name 'stack_2' is not defined (Pdb) d c:\tst_pdb.py(14)function_3() - print stack_3 (Pdb) l 9 function_3(stack_2) 10 11 def function_3(number): 12 stack_3 = number + 1 13 pdb.set_trace() 14 - print stack_3 15 16 function_1(1) [EOF] (Pdb) !stack_3 = 125 #this works now with the patch (Pdb) !print stack_3 125 (Pdb) When I use my original pdb.py, I can print variable stack_2 when I move one frame up, but can't change the value of these local variables. -- Added file: http://bugs.python.org/file18563/pdb.py ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue5215 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue5215] change value of local variable in debug
Amaury Forgeot d'Arc amaur...@gmail.com added the comment: Ah, the patch is buggy; it was corrected with r71019 which indeed fixes up and down. You could try to apply this change to your local copy. Also consider upgrading to 2.7, where everything works as expected... -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue5215 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9631] Python 2.7 installation issue for Linux Red Hat 4.1
Martin v. Löwis mar...@v.loewis.de added the comment: What file system is this on? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9631 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9631] Python 2.7 installation issue for Linux Red Hat 4.1
Prakash Palanivel spprakash...@gmail.com added the comment: After Installed the following error was through: PYTHONPATH=/usr/local/Python-2.7/lib/python2.7 \ ./python -Wi -tt /usr/local/Python-2.7/lib/python2.7/compileall.py \ -d /usr/local/Python-2.7/lib/python2.7 -f \ -x 'bad_coding|badsyntax|site-packages|lib2to3/tests/data' \ /usr/local/Python-2.7/lib/python2.7 Traceback (most recent call last): File /usr/local/Python-2.7/lib/python2.7/compileall.py, line 17, in module import struct File /usr/local/Python-2.7/lib/python2.7/struct.py, line 1, in module from _struct import * ImportError: No module named _struct make: *** [libinstall] Error 1 -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9631 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue672656] securing pydoc server
Mark Lawrence breamore...@yahoo.co.uk added the comment: This looks weird, a security issue with a low priority??? -- nosy: +BreamoreBoy ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue672656 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9631] Python 2.7 installation issue for Linux Red Hat 4.1
Senthil Kumaran orsent...@gmail.com added the comment: spprakash, do the following, in your python2.7 checkout (or download): do make distclean ./configure make make install If there is any failure in make/make install of the above steps, please paste that error message and also provide the file system type (run df -T) -- nosy: +orsenthil ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9631 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue5215] change value of local variable in debug
Markus Pröller mproel...@googlemail.com added the comment: Okay, thanks for giving me the correct patch, but I still face the following problem (with the same code snippet): c:\tst_pdb.py(14)function_3() - print stack_3 (Pdb) l 9 function_3(stack_2) 10 11 def function_3(number): 12 stack_3 = number + 1 13 pdb.set_trace() 14 - print stack_3 15 16 function_1(1) [EOF] (Pdb) stack_3 3 (Pdb) !stack_3 = 177 (Pdb) !print stack_3 177 (Pdb) u c:\tst_pdb.py(9)function_2() - function_3(stack_2) (Pdb) l 4 stack_1 = number 5 function_2(stack_1) 6 7 def function_2(number): 8 stack_2 = number + 1 9 - function_3(stack_2) 10 11 def function_3(number): 12 stack_3 = number + 1 13 pdb.set_trace() 14 print stack_3 (Pdb) !print stack_2 2 (Pdb) !stack_2 = 144 (Pdb) !print stack_2 144 (Pdb) d c:\tst_pdb.py(14)function_3() - print stack_3 (Pdb) l 9 function_3(stack_2) 10 11 def function_3(number): 12 stack_3 = number + 1 13 pdb.set_trace() 14 - print stack_3 15 16 function_1(1) [EOF] (Pdb) stack_3 3 (Pdb) u c:\tst_pdb.py(9)function_2() - function_3(stack_2) (Pdb) !print stack_2 2 (Pdb) I set the value of stack_3 to 177, go one frame up, do something, go one frame down and stack_3 is 3 again (not 177 as expected) -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue5215 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9433] regrtest.py -j 2 doesn't work on Windows: remove close_fds=True on Windows
Tim Golden m...@timgolden.me.uk added the comment: I can confirm that the patched regrtest runs ok on WinXP. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9433 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8622] Add PYTHONFSENCODING environment variable
Marc-Andre Lemburg m...@egenix.com added the comment: STINNER Victor wrote: STINNER Victor victor.stin...@haypocalc.com added the comment: Here you have a patch. It adds tests in test_sys. The tests are skipped on a non-ascii Python executable path because of #8611 (see #9425). Thanks for the patch. A couple of notes: * The command line -h explanation is missing from the patch. * The documentation should mention that the env var is only read once; subsequent changes to the env var are not seen by Python * If the codec lookup fails, Python should either issue a warning and then ignore the env var (using the get_codeset() API). * Unrelated to the env var, but still important: if get_codeset() does not return a known codec, Python should issue a warning before falling back to the default setting. Otherwise, a Python user will never know that there's an issue and this make debugging a lot harder. We should also add a new sys.setfilesystemencoding() function to make changes possible after Python startup. This would have to go on a separate ticket, though. Or is there some concept preventing this ? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8622 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue5215] change value of local variable in debug
Amaury Forgeot d'Arc amaur...@gmail.com added the comment: Right, this last problem still exists with 2.7 or 3.1. Please open a new tracker item for it, and let's close this one. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue5215 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8622] Add PYTHONFSENCODING environment variable
STINNER Victor victor.stin...@haypocalc.com added the comment: The command line -h explanation is missing from the patch. done The documentation should mention that the env var is only read once; subsequent changes to the env var are not seen by Python I copied the PYTHONIOENCODING doc which doesn't mention that. Does Python re-read other environment variables at runtime? Anyway, I changed the doc to: + If this is set before running the intepreter, it overrides the encoding used + for the filesystem encoding (see :func:`sys.getfilesystemencoding`). I also changed PYTHONIOENCODING doc. Is it better? If the codec lookup fails, Python should either issue a warning Ok, done. I patched also get_codeset() and get_codec_name() to always set a Python error. ... and then ignore the env var (using the get_codeset() API). Good idea, done. Unrelated to the env var, but still important: if get_codeset() does not return a known codec, Python should issue a warning before falling back to the default setting. Otherwise, a Python user will never know that there's an issue and this make debugging a lot harder. It does already write a message to stderr, but it doesn't explain why it failed. I changed initfsencoding() to display two messages on get_codeset() error. First explain why get_codeset() failed (with the Python error) and then say that we fallback to utf-8. Full example (PYTHONFSENCODING error and simulated get_codeset() error): --- PYTHONFSENCODING is not a valid encoding: LookupError: unknown encoding: xxx Unable to get the locale encoding: ValueError: CODESET is not set or empty Unable to get the filesystem encoding: fallback to utf-8 --- We should also add a new sys.setfilesystemencoding() ... No, I plan to REMOVE this function. sys.setfilesystemencoding() is dangerous because it introduces a lot of inconsistencies: this function is unable to reencode all filenames in all objects (eg. Python is unable to find filenames in user objects or 3rd party libraries). Eg. if you change the filesystem from utf8 to ascii, it will not be possible to use existing non-ascii (unicode) filenames: they will raise UnicodeEncodeError. As sys.setdefaultencoding() in Python2, I think that sys.setfilesystemencoding() is the root of evil :-) At startup, initfsencoding() sets the filesystem encoding using the locale encoding. Even for the startup process (with very few objects), it's very hard to find all filenames: - sys.path - sys.meta_path - sys.modules - sys.executable - all code objects - and I'm not sure that the list is complete See #9630 for the details. To remove sys.setfilesystemencoding(), I already patched PEP 383 tests (r84170) and I will open a new issue. But it's maybe better to commit both changes (remove the function and PYTHONFSENCODING) at the same time. -- Added file: http://bugs.python.org/file18564/pythonfsencoding-2.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8622 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9632] Remove sys.setfilesystemencoding()
New submission from STINNER Victor victor.stin...@haypocalc.com: sys.setfilesystemencoding() function is dangerous because it introduces a lot of inconsistencies: this function is unable to reencode all filenames in all objects (eg. Python is unable to find filenames in user objects or 3rd party libraries). Eg. if you change the filesystem from utf8 to ascii, it will not be possible to use existing non-ascii (unicode) filenames: they will raise UnicodeEncodeError. As sys.setdefaultencoding() in Python2, I think that sys.setfilesystemencoding() is the root of evil :-) PYTHONFSENCODING (issue #8622) is the right solution to set the filesysteme encoding. Attached patch removes sys.setfilesystemencoding(). -- components: Library (Lib), Unicode messages: 114211 nosy: haypo priority: normal severity: normal status: open title: Remove sys.setfilesystemencoding() versions: Python 3.2 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9632 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9632] Remove sys.setfilesystemencoding()
Changes by STINNER Victor victor.stin...@haypocalc.com: -- keywords: +patch nosy: +Arfrever, lemburg, pitrou Added file: http://bugs.python.org/file18565/remove_sys_setfilesystemencoding.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9632 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8622] Add PYTHONFSENCODING environment variable
Changes by STINNER Victor victor.stin...@haypocalc.com: Removed file: http://bugs.python.org/file18562/pythonfsencoding.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8622 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8622] Add PYTHONFSENCODING environment variable
STINNER Victor victor.stin...@haypocalc.com added the comment: To remove sys.setfilesystemencoding(), ... I will open a new issue done, issue #9632 -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8622 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9633] pdb go stack up/down
New submission from Markus Pröller mproel...@googlemail.com: Hello, with python 2.7 I encounter the following problem: I have created the following sample script: import pdb def function_1(number): stack_1 = number function_2(stack_1) def function_2(number): stack_2 = number + 1 function_3(stack_2) def function_3(number): stack_3 = number + 1 pdb.set_trace() print stack_3 function_1(1) This is what I have done in the pdb session: c:\tst_pdb.py(14)function_3() - print stack_3 (Pdb) l 9 function_3(stack_2) 10 11 def function_3(number): 12 stack_3 = number + 1 13 pdb.set_trace() 14 - print stack_3 15 16 function_1(1) [EOF] (Pdb) stack_3 3 (Pdb) !stack_3 = 177 (Pdb) !print stack_3 177 (Pdb) u c:\tst_pdb.py(9)function_2() - function_3(stack_2) (Pdb) l 4 stack_1 = number 5 function_2(stack_1) 6 7 def function_2(number): 8 stack_2 = number + 1 9 - function_3(stack_2) 10 11 def function_3(number): 12 stack_3 = number + 1 13 pdb.set_trace() 14 print stack_3 (Pdb) !print stack_2 2 (Pdb) !stack_2 = 144 (Pdb) !print stack_2 144 (Pdb) d c:\tst_pdb.py(14)function_3() - print stack_3 (Pdb) l 9 function_3(stack_2) 10 11 def function_3(number): 12 stack_3 = number + 1 13 pdb.set_trace() 14 - print stack_3 15 16 function_1(1) [EOF] (Pdb) stack_3 3 (Pdb) u c:\tst_pdb.py(9)function_2() - function_3(stack_2) (Pdb) !print stack_2 2 (Pdb) I walked through the stack and changed the values of the variables stack_x but the values weren't saved when I moved one frame up/down -- components: Library (Lib) messages: 114213 nosy: Markus.Pröller priority: normal severity: normal status: open title: pdb go stack up/down type: behavior versions: Python 2.7 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9633 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com