Re: Performance on local constants?
On Dec 23, 2:39 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > "John Machin" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > | On Dec 23, 5:38 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > | > 'Most flexible' in a different way is > | > > | > def searcher(rex): > | > crex = re.compile(rex) > | > def _(txt): > | > return crex.search(txt) > | > return _ > | > > | > | I see your obfuscatory ante and raise you several dots and > | underscores: > > I will presume you are merely joking, but for the benefit of any beginning > programmers reading this, the closure above is a standard functional idiom > for partial evaluation of a function (in this this, re.search(crex,txt)) > > | class Searcher(object): > |def __init__(self, rex): > |self.crex = re.compile(rex) > |def __call__(self, txt): > |return self.crex.search(txt) > > while this is, the equivalent OO version. Intermdiate Python programmers > should know both. > Semi-joking; I thought that your offering of this: def searcher(rex): crex = re.compile(rex) def _(txt): return crex.search(txt) return _ foo_searcher = searcher('foo') was somewhat over-complicated, and possibly slower than already- mentioned alternatives. The standard idiom etc etc it may be, but the OP was interested in getting overhead out of his re searching loop. Let's trim it a bit. step 1: def searcher(rex): crexs = re.compile(rex).search def _(txt): return crexs(txt) return _ foo_searcher = searcher('foo') step 2: def searcher(rex): return re.compile(rex).search foo_searcher = searcher('foo') step 3: foo_searcher = re.compile('foo').search HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython FileDialog, select folder
SMALLp <[EMAIL PROTECTED]> wrote: > >Thanks! I've already figured it out from first reply. Now i get selected >directory and i want to get all directories from thin directory. I found >os.listdir but it oly gets names of files and i nedd output with >permisions e.g. -rw-r--r-- 1 pofuk pofuk 105 2007-12-19 21:59 login.py Do you want to KNOW the permissions, or do you really want to get the output of "ls -l"? What you probably want is os.walk. You can call stat or os.path.isdir to get information about the files you discover. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Modify arguments between __new__ and __init__
Steven D'Aprano wrote: > When you call a new-style class, the __new__ method is called with the > user-supplied arguments, followed by the __init__ method with the same > arguments. > > I would like to modify the arguments after the __new__ method is called > but before the __init__ method, somewhat like this: > > class Spam(object): > ... def __new__(cls, *args): > ... print "__new__", args > ... x = object.__new__(cls) > ... args = ['spam spam spam'] > ... return x > ... def __init__(self, *args): > ... print "__init__", args # hope to get 'spam spam spam' > ... return None > > but naturally it doesn't work: > s = Spam('spam and eggs', 'tomato', 'beans are off') > __new__ ('spam and eggs', 'tomato', 'beans are off') > __init__ ('spam and eggs', 'tomato', 'beans are off') > > Is there any way to do this, or am I all outta luck? You can really only achieve this by writing a metaclass. When a new object is created, what's first called is the __call__ method of the type object. This basically looks like:: def __call__(cls, *args, **kwargs): obj = cls.__new__(cls, *args, **kwargs) obj.__init__(*args, **kwargs) return obj Hopefully that explains the behavior you're seeing. If you want different behavior than this, you can change __call__ by defining your own metaclass with a different __call__ method, for example:: >>> class SpamMeta(type): ... def __call__(cls, *args, **kwargs): ... obj = cls.__new__(cls) ... obj.__init__('spam spam spam') ... return obj ... >>> class Spam(object): ... __metaclass__ = SpamMeta ... def __new__(cls, *args): ... print '__new__', args ... return object.__new__(cls) ... def __init__(self, *args): ... print '__init__', args ... >>> Spam() __new__ () __init__ ('spam spam spam',) <__main__.Spam object at 0x00E756F0> Hope that helps, STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get Python to default to UTF8
Hi Fredrik, Thanks again for your feedback. I am much obliged. Indeed, I am forced to be exteremely rigorous about decoding on the way in and encoding on the way out everywhere in my program, just as you say. Your advice is excellent and concurs with other sources of unicode expertise. Following this approach is the only thing that has made it possible for me to get my program to work. However, the situation is still unacceptable to me because I often make mistakes and it is easy for me to miss places where encoding is necessary. I rely on testing to find my faults. On my development environment, I get no error message and it seems that everything works perfectly. However, once ported to the server, I see a crash. But this is too late a stage to catch the error since the app is already live. I assume that the default encoding that you mention shouldn't ever be changed is stored in the site.py file. I've checked this file and it's set to ascii in both machines (development and server). I haven't touched site.py. However, a week or so ago, following the advice of someone I read on the web, I did create a file in my cgi-bin directory called something like site-config.py, wherein encoding was set to utf8. I ran my program a few times, but then reading elsewhere that the site-config.py approach was outmoded, I decided to remove this file. I'm wondering whether it made a permanent change somewhere in the bowels of python while I wasn't looking? Can you elaborate on where to look to see what stdin/stdout encodings are set to? All inputs are coming at my app either via html forms or input files. All output goes either to the browser via html or to an output file. > > to fix this, figure out from where you got the encoded (8-bit) string, and > make sure you decode it properly on the way in. only use Unicode strings > on the "inside". > > (Python does have two encoding defaults; there's a default encoding that > *shouldn't* ever be changed from the "ascii" default, and there's also a > stdin/stdout encoding that's correctly set if you run the code in an > ordinary terminal window. if you get your data from anywhere else, you > cannot trust any of these, so you should do your own decoding on the way > in, and encoding things on the way out). > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Modify arguments between __new__ and __init__
On Dec 22, 11:03 pm, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > When you call a new-style class, the __new__ method is called with the > user-supplied arguments, followed by the __init__ method with the same > arguments. > Only if __new__ returns an object of the type passed into __new__. Otherwise, __init__ is not called. > I would like to modify the arguments after the __new__ method is called > but before the __init__ method, somewhat like this: > What's your use-case? I mean, why not just do this in __init__ instead of __new__? > >>> class Spam(object): > > ... def __new__(cls, *args): > ... print "__new__", args > ... x = object.__new__(cls) > ... args = ['spam spam spam'] > ... return x > ... def __init__(self, *args): > ... print "__init__", args # hope to get 'spam spam spam' > ... return None > > but naturally it doesn't work: > > >>> s = Spam('spam and eggs', 'tomato', 'beans are off') > > __new__ ('spam and eggs', 'tomato', 'beans are off') > __init__ ('spam and eggs', 'tomato', 'beans are off') > > Is there any way to do this, or am I all outta luck? > >From what I can tell from http://docs.python.org/ref/customization.html, you are out of luck doing it this way unless you jury rig some way to have __new__ return an object of a different type. --Nathan Davis -- http://mail.python.org/mailman/listinfo/python-list
MI5-Persecution: Browse the Website (13792)
MI5 Persecution Update: Friday 25 March, 1999 If You Intend To Reply, Please Read This Please keep your response to one page if you can!. Faxes over a page or two will be deleted without being read. The Usual Words The persecutors-who-wont-admit-theyre-MI5 have been active again this week. On Saturday 20/3/99 I visited Ravenscourt Park in west London, and was verbally assaulted with the usual words, "something wrong with him". This audio file is on the web at URL; This afternoon (Friday 26/March) I was again verbally assaulted while travelling by bus. The same sexual obscenity was thrown at me, and the incident was recorded on my minidisc-walkman. Because of the deeply offensive nature of the slander, I will not be posting this on the website. Keith Hill MP (Labour - Streatham), my elected representative, as ever refuses to help. MI5 Persecution : Browse Website The March 1998 issue (number 42) of .net Magazine reviews the website describing it as an "excellent site". Since August 11, 1996 over 50,000 people have browsed this website. You are encouraged to read the web pages which include a FAQ (frequently asked questions) section outlining the nature of the persecutors, their methods of harassment through the media, people at work and among the general public an evidence section, which carries audio and video clips of media and workplace harassment, rated according to how directly I think they refer to me objective descriptions of the state security agencies involved scanned texts of the complaints I have made to media and state security agencies involved posts which have been made to netnews over the last four years on this topic This article outlines what is to be found on the webpages, which you are encouraged to browse for the complete story. Frequently Asked Questions Your excursion through the website starts with the "FAQ - Frequently Asked Questions" portion. MI5s campaign of harassment against me has been going on for almost 9 years, and its longevity and breadth is reflected in the FAQ. Many thousands of people in Britain and abroad, including some recipients of this fax, have known for many years of MI5s activities against me. The FAQ describes the mass "Omerta suppressing its publication"; we pretend Britain is part of the "Free World", yet the British Secret Police, which is what MI5 are, carry on for many years a campaign which politicians and the media know about, and rely on the silent complicity of so many thousands of people. The FAQs introductory article names those who are "in the know"; media figures like Martyn Lewis, Michael Buerk, entertainment figures like Chris Tarrant, politicians and many in the general public, "all united in a conspiracy which breaks the laws which the UK does have regarding harassment, and all completely uncaring for any semblance of decency or elementary respect for individual rights. Broadcast media play a key role in the harassment. The very first incident in June 1990 was when a television newsreader reacted to what she saw happen in my living room at home; such incidents of "interactive television" are still happening in 1999. The same goes for radio stations such as Capital FM. In spring 1994, Chris Tarrant on his Capital morning show made an aside to someone else in the studio, about a person he didn't identify. He said, "You know this bloke? He says we're trying to kill him. We should be done for attempted manslaughter". Tarrant and Capital have made strenuous efforts to avoid answering this charge. Perhaps worst of all, MI5 have deliberately set-up many incidents in public places such as tube stations, shops, cinemas, where they have paid people to throw abuse at me. Since MI5 obtains funds to the tune of 160 million a year to fund its criminal activities, it has funds both to pay its operatives and to "buy" media figures and members of the public to take part in its campaign of persecution. The Security Service are professional liars. They throw slanderous abuse, yet they refuse to admit out loud that they are doing so. When challenged about their activities through the Security Service Tribunal they lie and deny their activities. They induce other workers and managers at places of employment to take part in their campaign of abuse, presumably by buying them in the same way they buy media figures. Complaints, and Press Coverage (BBC Lies, MI5 Lies) As you might expect I have challenged both the Security Service, through the Security Service Tribunal, and offending broadcasters, to own up to what they have been doing. And as you might also expect, all of these people have lied through their teeth. Still worse, they have refused to commit unambiguous lies on paper; they have couched their lies in bureaucratic language, and allowed others to make false assurances and tell lies on their behalf. So when their lies are exposed, they will then tell further Clintonesque lies about how they werent really telling lies in the first
Re: It's ok to __slots__ for what they were intended
Fredrik Lundh wrote: > John Nagle wrote: > >> I'd like to hear more about what kind of performance gain can be >> obtained from "__slots__". I'm looking into ways of speeding up >> HTML parsing via BeautifulSoup. If a significant speedup can be >> obtained when navigating large trees of small objects, that's worth >> quite a bit to me. > > The following micro-benchmarks are from Python 2.5 on a Core Duo > machine. C0 is an old-style class, C1 is a new-style class, C2 is a > new-style class using __slots__: > > # read access > $ timeit -s "import q; o = q.C0(); o.attrib = 1" "o.attrib" > 1000 loops, best of 3: 0.133 usec per loop > $ timeit -s "import q; o = q.C1(); o.attrib = 1" "o.attrib" > 1000 loops, best of 3: 0.184 usec per loop > $ timeit -s "import q; o = q.C2(); o.attrib = 1" "o.attrib" > 1000 loops, best of 3: 0.161 usec per loop > > # write access > $ timeit -s "import q; o = q.C0(); o.attrib = 1" "o.attrib = 1" > 1000 loops, best of 3: 0.15 usec per loop > $ timeit -s "import q; o = q.C1(); o.attrib = 1" "o.attrib = 1" > 100 loops, best of 3: 0.217 usec per loop > $ timeit -s "import q; o = q.C2(); o.attrib = 1" "o.attrib = 1" > 100 loops, best of 3: 0.209 usec per loop Not much of a win there. Thanks. > > > I'm looking into ways of speeding up HTML parsing via BeautifulSoup. > > The solution to that is spelled "lxml". I may eventually have to go to a non-Python solution. But I've finally made enough robustness fixes to BeautifulSoup that it's usable on large numbers of real-world web sites. (Only two exceptions in the last 100,000 web sites processed. If you want to exercise your HTML parser on hard cases, run hostile-code web sites through it.) John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Modify arguments between __new__ and __init__
When you call a new-style class, the __new__ method is called with the user-supplied arguments, followed by the __init__ method with the same arguments. I would like to modify the arguments after the __new__ method is called but before the __init__ method, somewhat like this: >>> class Spam(object): ... def __new__(cls, *args): ... print "__new__", args ... x = object.__new__(cls) ... args = ['spam spam spam'] ... return x ... def __init__(self, *args): ... print "__init__", args # hope to get 'spam spam spam' ... return None but naturally it doesn't work: >>> s = Spam('spam and eggs', 'tomato', 'beans are off') __new__ ('spam and eggs', 'tomato', 'beans are off') __init__ ('spam and eggs', 'tomato', 'beans are off') Is there any way to do this, or am I all outta luck? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
On 2007-12-23, Grant Edwards <[EMAIL PROTECTED]> wrote: > On 2007-12-22, cf29 <[EMAIL PROTECTED]> wrote: > >> The goal is to control all the chess board with five queens that do >> not attack each other. > [...] >> My problem starts now. How can I find the next solution and >> append it to the list? Has anyone tried to do a such script? > > ftp://ftp.visi.com/users/grante/python/queens.py > > It's a pretty standard depth-first search of the solution space. Never mind. I just realized that you said 5-queens, not 8-queens. -- -- http://mail.python.org/mailman/listinfo/python-list
Element bug?(ElementTree)
I don't know if it's a bug? Try below code: >>> from elementtree.ElementTree import Element >>> a = Element('a') >>> if a: ... print '' ... >>> a.__len__() 0 You can see if I test a, the result will be False. I don't know if it's an expected result, but this thing has beaten me some times. -- I like python! UliPad <>: http://code.google.com/p/ulipad/ meide <>: http://code.google.com/p/meide/ My Blog: http://www.donews.net/limodou -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
Hi, The problem you are trying to solve is a very famous and common problem which can be solved by backtracking. Please try google with 8 queens problem or n queens problem. > > I designed in JavaScript a small program on my website called 5 > queens. > (http://www.cf29.com/design/dame5_eng.php) > > The goal is to control all the chess board with five queens that do > not attack each other. I found "manually" many solutions to this > problem (184 until now) and wanted to create a Python script to find > them all. As I am new to Python, I struggle a lot. > > I found a way to create: > - a board where each square is defined by its row, column and if it is > controlled or not > - a function that tells which squares are controlled by a queen on a > particular square > - a function that counts how many squares are controlled > - a function that can reset all squares control to 0 > - a function that can place 5 queens safely on the board > - I can find the first solution and register it in a list > > My problem starts now. How can I find the next solution and append it > to the list? Has anyone tried to do a such script? If anyone is > interested to help I can show what I've done so far. Try to generate the next permutation and check if it's a valid solution. Need to use recursion for this. regards, Subeen. -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance on local constants?
"John Machin" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | On Dec 23, 5:38 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote: | > 'Most flexible' in a different way is | > | > def searcher(rex): | > crex = re.compile(rex) | > def _(txt): | > return crex.search(txt) | > return _ | > | | I see your obfuscatory ante and raise you several dots and | underscores: I will presume you are merely joking, but for the benefit of any beginning programmers reading this, the closure above is a standard functional idiom for partial evaluation of a function (in this this, re.search(crex,txt)) | class Searcher(object): |def __init__(self, rex): |self.crex = re.compile(rex) |def __call__(self, txt): |return self.crex.search(txt) while this is, the equivalent OO version. Intermdiate Python programmers should know both. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
"John Machin" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | It's *91* distinct solutions to what appears to be *exactly* your | problem: | | """ | Dudeney (1970, pp. 95-96) also gave the following results for the | number of distinct arrangements N_u(k,n) of k queens attacking or | occupying every square of an nxn board for which no two queens attack | one another (they are "not protected"). | k queens nxn N_u(k,n) | 1 2 1 | 1 3 1 | 3 4 2 | 3 5 2 | 4 6 17 | 4 7 1 | 5 8 91 | """ If you don't want to work out everything for yourself, I would go to the Wolffram site and find the Dudeney reference and see if it has an algorithm or merely a list of solutions (even that would help). A brute force search off the top of my head goes as follows: The 'topmost' queen can potentially be in any column of rows 0 to 3; The second queen in the next row to 4, any column; Etc. r8 = range(8) for i0 in range(0, 4): for j0 in r8: for i1 in range(i0+1,5): for j1 in r8: for i2 in range(i1+1, 6): for j2 in r8: for i3 in range(i2+1,7): for ji in r8: for i4 in range(i3+1): for j4 in r8: test_position: Optimizations: test non-attacking property as add each queen. Change range of j0 to range(4) to delete reflections about vertical axis. To detect all duplicates by reflection and rotation, one needs a 'canonical' form for each position. With that, I think one could do much better in not generating duplicates. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: exception message output problem
On Dec 22, 5:34 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Russ P. wrote: > > Actually, the parens aren't needed, so this works too: > > > def __init__(self, args=""): self.args = args, > > > The trailing comma wasn't necessary a while back (pre 2.5?), so > > something in Python must have changed. I'd say that it looks a bit > > cleaner without the trailing comma, so maybe whatever changed should > > get changed back. > > as the name implies, "args" is supposed to be a sequence, and is stored > internally as a tuple. if something has changed, it's probably that 2.5 > enforces this behaviour via a property. > > to fix your code, just replace your own __init__ method with a "pass", > and leave the initialization to the Exception class itself. That works. And because it is the simplest solution here, I'd say it's the "correct" solution. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Inter-process communication, how? Part 2
Hello, just to recap: last time I asked how to do an interprocess communitation, between one Manager process (graphical beckend) and some Worker processes. I decided to go with sockets, thanks for replies, once more. However, I would like to ask another thing: I would like to collect everyting what the Workers print and display in Manager. Or, redirect all Workers' stdout to stdio of Manager. If there was only one Worker I could use a pipe, right? But if there are more than one Worker, what to do? I found something called "named pipe" which seems rather complicated. Then I thought I could somehow (how?) create a fake (virtual) file object, redirect stdout of a Worket into it and from there send the data to Manager via sockets. Please, what do you think? Preferably, it should look like this: --- Worker 1 --- ...some code... print '123' --- Manager --- Worker 1: 123 --- Worker 2 --- ...some code... print '456' --- Manager --- Worker 1: 123 Worker 2: 456 Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternative to python -u for binary upload to cgi on windows?
On Dec 14, 6:58 pm, Cameron Walsh <[EMAIL PROTECTED]> wrote: > Hi all, > > Using a pythoncgiscript such as the one below to handle uploaded > binary files will end up with atruncatedfile (truncates when it hits > ^Z) on Windows systems. On linux systems the code works and the file is > nottruncated. > > One solution for Windows is to use the -u flag, i.e. > #!C:\Python\python.exe -u > > Is there another fix that doesn't require python to be run in unbuffered > mode? What performance hits would I expect for running in unbuffered mode? Answer to the first part: import msvcrt, sys, os msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) # other problems may also be fixed with: # msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) Cameron. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simple way to parse this string ?
On Sat, 22 Dec 2007 07:21:26 -0800, [EMAIL PROTECTED] wrote: > Steven D'Aprano, > > On Dec 21, 2:08 am, Steven D'Aprano > <[EMAIL PROTECTED]> wrote: >> On Thu, 20 Dec 2007 20:27:23 -0800, [EMAIL PROTECTED] wrote: >> > Stef, >> >> > For clarification, there is nothing hazardous about using eval on the >> > string that you presented. >> >> > t = eval('(0, 0, 0, 255), (192, 192, 192, 255), True, 8') >> >> > Whether or not this is the "simplest" solution, remains a question. >> >> For clarification, if all the poster wanted was to convert the >> *specific* *known* string to a tuple, he would be better off just >> writing it as a tuple: > > Steven, > > No, that's not what he asked. Read the original question. I did. I even read all the way down to the part where he wrote: "(Not needed now, but might need it in the future: even deeper nested lists, represented by a string.)" Its clear that the OP has more in mind than just a single specific known string. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this a bug in int()?
On Sat, 22 Dec 2007 14:03:09 -0800, MartinRinehart wrote: > Tokenizer accepts "0x" as zero. Spec says its an error not to have at > least one hex digit after "0x". > > This is a more serious bug than I had originally thought. Consider this: > > Joe types "security_code = 0x" and then goes off to the Guardian-of- > the-Codes to get the appropriate hex string. Which is *hard coded* in the source code??? How do you revoke a compromised code, or add a new one? Let me guess... the Guardian of the Codes stores them on a postit note stuck to the side of the fridge in the staff lunchroom? Written backwards, so nobody can guess what they really are. > Returning to computer, > Joe's boss grabs him. Tells him that effective immediately he's on the > "rescue us from this crisis" team; his other project can wait. Serves him write for writing in hex, when everybody knows that for *real* security you should store your security codes as octal. > Some hours, days or weeks later Joe returns to the first project. At > this point Joe has a line of code that says "security_code = 0x". I > think Joe would be well-served by a compiler error on that line. *shrug* Maybe so, but how is that worse than if he had written "security_code = 123456" intending to come back and put the actual code in later, and forgot? > As is > now, Joe's program assigns 0 to security_code and compiles without > complaint. Which Joe will *instantly* discover, the first time he tries to test the program and discovers that entering the *actual* security code doesn't work. > I'm pretty sure any line of the form "name = 0x" was a > product of some form of programmer interruptus. There's no doubt that 0x is a bug, according to the current specs. It probably should be fixed (as opposed to changing the specs). But trying to up-sell a trivial bug into a OMG The Sky Is Falling This Is A Huge Security Risk Panic Panic Panic just makes you seem silly. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
Sorry again I forgot a part of the function in my previous post: --- # add nbQueens (5) new queens on safe squares def newQueens(nbQueens=5): solution = [] # one solution for i in range(len(board)): # 64 squares if len(solution) < nbQueens:# 5 queens if board[i][2]==0: # free square solution.append(i) # a queen position queenCtrl(board[i]) # the queen controls squares if calcCtrl() == len(board):# whole board controlled allSolutions.append(solution) # add this solution to the list resetCtrl() # reset the controled squares -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this a bug in int()?
On Dec 22, 5:03 pm, [EMAIL PROTECTED] wrote: > Tokenizer accepts "0x" as zero. Spec says its an error not to have at > least one hex digit after "0x". > > This is a more serious bug than I had originally thought. Consider > this: > > Joe types "security_code = 0x" and then goes off to the Guardian-of- > the-Codes to get the appropriate hex string. Returning to computer, > Joe's boss grabs him. Tells him that effective immediately he's on the > "rescue us from this crisis" team; his other project can wait. > > Some hours, days or weeks later Joe returns to the first project. At > this point Joe has a line of code that says "security_code = 0x". I > think Joe would be well-served by a compiler error on that line. As is > now, Joe's program assigns 0 to security_code and compiles without > complaint. I'm pretty sure any line of the form "name = 0x" was a > product of some form of programmer interruptus. :-) Are you a fiction writer by any chance ? Nice story but I somehow doubt that the number of lines of the form "name = 0x" ever written in Python is greater than a single digit (with zero the most likely one). George -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
On Dec 23, 1:49 am, John Machin <[EMAIL PROTECTED]> wrote: > > > How did you find 184 solutions? Wolfram says there are 91 distinct > > > solutions for 5-queens on an 8x8 board with no two queens attacking > > > each other. > > It's *91* distinct solutions to what appears to be *exactly* your > problem: > > """ > k queens nxn N_u(k,n) > 5 8 91 Sorry I missed that. Anyway I found 192 solutions now, they include rotations and mirroring so that gives 24 "unique" solutions. May be there is a total of 91 unique solutions that would give 91x8 = 728 distinct solutions. I don't know yet. Sorry for any misunderstanding as English is not my native language. I'll include my script so you may understand my code better than my English and tell me where I went wrong. Thanks a lot to everyone for your patience and kind help to a such newbie I am. I am learning a lot, I started to learn Python 3 days ago. the code I wrote so far - # Solutions to the 5 queens problem # Control all the board with five queens # that do not attack each other board = [] # squares list nbRows = 8 # number of rows nbCols = 8 # number of columns # create 64 squares definied by their row, column # and a 0 meaning that they aren't controlled yet # ie the 1st square board[0] is [0,0,0], the last one board[63] is [7,7,0] for r in range(nbRows): for c in range(nbCols): board.append([r,c,0]) # control done by a queen on square (sq) def queenCtrl(sq): for c in range(len(board)): if (board[c][0] == sq[0] or # same row board[c][1] == sq[1] or # same col (board[c][0] + board[c][1]) == (sq[0] + sq[1]) or # diagonal1 (board[c][0] - board[c][1]) == (sq[0] - sq[1])): # diagonal2 board[c][2] = 1 # the square is controlled # count the number of controlled squares def calcCtrl(): nbCtrl = 0 # number of controlled squares for c in range(len(board)): if board[c][2] == 1: nbCtrl += 1 return nbCtrl # reset controlled squares def resetCtrl(): for c in range(len(board)): board[c][2] = 0 # all the solutions list allSolutions = [] # add nbQueens (5) new queens on safe squares def newQueens(nbQueens=5): solution = [] # one solution for i in range(len(board)): # 64 squares if len(solution) < nbQueens:# 5 queens if board[i][2]==0: # free square solution.append(i) # a queen position queenCtrl(board[i]) # the queen controls squares resetCtrl() # reset the controled squares allSolutions.append(solution) # add this solution to the list # testing newQueens() for s in allSolutions: print s # this gives me the first solution # please tell me # how can I ask newQueens() to find the next new solution # and add it to the allSolutions list until there is no more ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting memory leaks on apache, mod_python
On Sat, 22 Dec 2007 13:05:23 -0800, Dennis Lee Bieber wrote: > I've never encountered such items > supported by the language. > > OS specific extensions MIGHT supply it... Picky picky... but of course you are right. When I said that programming languages I have used before had facilities to measure memory usage, I meant that the *implementation* had those facilities rather than the language itself. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: exception message output problem
On Dec 23, 4:30 am, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Lie a écrit : > > > PPS: Actually, what makes a tuple is both the parens and the comma, > > Nope, it's definively the comma. You can check the language's grammar, > it's part of the doc. Or just test FWIW: > > Python 2.4.3 (#1, Mar 12 2007, 23:32:01) > [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on > linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> a = 1, > >>> type(a) > > >>> > > > with comma as the minimum signifier, inspect this: "str(a) + > > str((a,b,c))", you have to use the double parens, one to make the > > tuple and the other as part of the str. > > This is a problem of operator precedence. I think some people have misunderstood me, I know parens isn't a formal definition for tuples, but it's more or less a de facto grammar, as it is hard to create parens-less tuples without the interpreter mistaking it for other things, except for a few cases. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure Python GUI lib?
oyster wrote: > For the word "Pure", I mean it is not a C/C++/Z++.. extension, so that > we can use it under pythons of different version. Is it possible? > I don't like to update the module for different python and the module > > Currently, I am writing the interface to > iup(http://www.tecgraf.puc-rio.br/iup) via ctypes, but find 2 too > strange things which have let me feel blue for some days, and I don't > know whether it can be successful or not. Can anyone give me some > lights? Thank you. :) Venster is a Windows API GUI wrapper on top of ctypes. Fairly low level, but quite viable. I have an application at work using an old version (0.21) on an old version of ctypes (0.6.3) that works fine, though it doesn't do MDI. Sadly Venster appears not to have recently been maintained in line with changes in ctypes, but the code (available from SourceForge) could still prove a useful reference. Cheers, Andrew. -- - Andrew I MacIntyre "These thoughts are mine alone..." E-mail: [EMAIL PROTECTED] (pref) | Snail: PO Box 370 [EMAIL PROTECTED] (alt) |Belconnen ACT 2616 Web:http://www.andymac.org/ |Australia -- http://mail.python.org/mailman/listinfo/python-list
Re: getattr() question
On Dec 22, 7:14 pm, John Machin <[EMAIL PROTECTED]> wrote: > On Dec 23, 10:39 am, Sledge <[EMAIL PROTECTED]> wrote: > > > > > Hi. > > > I am trying to dynamically load a class and attributes at run time. I > > do not know what classes will be referenced until run time. I have it > > loading the module correctly, but when I use getattr to access the > > class and its attributes everything works except that I get additional > > unwanted output. The code > > > testclass.py: > > > #!/usr/bin/python > > > class testclass(object): > > > myname = "" > > > def __init__(self, name): > > self.myname = name > > > def view(self): > > print "hello %s" % self.myname > > > test.py: > > > #!/usr/bin/python > > > import sys > > sys.path.append('.') > > from pprint import pprint > > > if __name__ == '__main__': > > myname = "testclass" > > myaction = "view" > > try: > > tc = __import__(myname) > > myclass = getattr(tc,myname) > > myinstance = getattr(myclass('python n00b'), myaction, > > myaction) > > pprint(myinstance()) > > except ImportError: > > "error" > > What do you expect to see if the import fails? > > > > > Here is the output that I get: > > > [EMAIL PROTECTED]:~/$ python test.py > > hello python n00b > > None > > [EMAIL PROTECTED]:~/$ > > > Why is it printing 'None'? What am I doing wrong. I appreciate any > > help. > > The problem is nothing to do with using getattr; it "works" in the > sense that it does what you appear to want it to. > > You have *two* explict outputting statements: the print statement in > the first file and the pprint invocation in the second file. Seems > fairly obvious that it's not the first of these. So dissect > "pprint(myinstance())". > > myinstance is bound to the view method [in the first file] which > (implicitly) returns None. So you are in effect doing pprint(None). that did the trick. How could I have missed something so obvious? > > Aside: give your fingers a rest: don't type "my" so often. It was just for demonstration purposes :). Thanks for your help John. -- http://mail.python.org/mailman/listinfo/python-list
Re: getattr() question
On Dec 23, 10:39 am, Sledge <[EMAIL PROTECTED]> wrote: > Hi. > > I am trying to dynamically load a class and attributes at run time. I > do not know what classes will be referenced until run time. I have it > loading the module correctly, but when I use getattr to access the > class and its attributes everything works except that I get additional > unwanted output. The code > > testclass.py: > > #!/usr/bin/python > > class testclass(object): > > myname = "" > > def __init__(self, name): > self.myname = name > > def view(self): > print "hello %s" % self.myname > > test.py: > > #!/usr/bin/python > > import sys > sys.path.append('.') > from pprint import pprint > > if __name__ == '__main__': > myname = "testclass" > myaction = "view" > try: > tc = __import__(myname) > myclass = getattr(tc,myname) > myinstance = getattr(myclass('python n00b'), myaction, > myaction) > pprint(myinstance()) > except ImportError: > "error" What do you expect to see if the import fails? > > Here is the output that I get: > > [EMAIL PROTECTED]:~/$ python test.py > hello python n00b > None > [EMAIL PROTECTED]:~/$ > > Why is it printing 'None'? What am I doing wrong. I appreciate any > help. The problem is nothing to do with using getattr; it "works" in the sense that it does what you appear to want it to. You have *two* explict outputting statements: the print statement in the first file and the pprint invocation in the second file. Seems fairly obvious that it's not the first of these. So dissect "pprint(myinstance())". myinstance is bound to the view method [in the first file] which (implicitly) returns None. So you are in effect doing pprint(None). Aside: give your fingers a rest: don't type "my" so often. -- http://mail.python.org/mailman/listinfo/python-list
Re: The 0.8181818181... Truth Movement
Dustan <[EMAIL PROTECTED]> writes: > On Dec 22, 8:20 am, Phil Carmody <[EMAIL PROTECTED]> > wrote: > > On 1117th December 2004, Dustan <[EMAIL PROTECTED]> wrote: > > > Look at the list of groups. Python's the only language in there. > > > Python uses double precision. Period. > > > > But Professor Checkman was evidently interested in decimals, so > > surely this is more relevant: > > > > >>> from decimal import * > > >>> Decimal('9')/Decimal('11') > > > > Decimal("0.8181818181818181818181818182") > > > > That's not double precision. So evidently Python uses more > > than just double precision. So your above absolute statement > > is either wrong or misleading. Period. > > I stand corrected. Sort of. Not really. Python's built-in types remain > limited to doubles. Misleading, maybe. Don't worry, I was only pulling your leg. > > > Of course, I could also have said that 9/11==0. Would you have figured > > > out what I was talking about then? > > > > Odd, it appears that you joined the thread after the good > > professor did. Therefore it is you who should be trying to > > figure out what _he_ was saying, not the other way round. > > Yeah, because what he was saying was very cryptic. Not compared to half of the nonsense I write :-) Seasons greetings, Phil -- Dear aunt, let's set so double the killer delete select all. -- Microsoft voice recognition live demonstration -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
On Dec 23, 10:18 am, cf29 <[EMAIL PROTECTED]> wrote: > On Dec 23, 12:39 am, Jervis Liang <[EMAIL PROTECTED]> wrote: > > > On Dec 22, 2:36 pm, cf29 <[EMAIL PROTECTED]> wrote: > > > > The goal is to control all the chess board with five queens that do > > > not attack each other. I found "manually" many solutions to this > > > problem (184 until now) > > > How did you find 184 solutions? Wolfram says there are 91 distinct > > solutions for 5-queens on an 8x8 board with no two queens attacking > > each other. > > >http://mathworld.wolfram.com/QueensProblem.html > > If I am not mistaken, the 92 solutions are for 8 queens on a 8x8 board > with no queen attacking each other. It's *91* distinct solutions to what appears to be *exactly* your problem: """ Dudeney (1970, pp. 95-96) also gave the following results for the number of distinct arrangements N_u(k,n) of k queens attacking or occupying every square of an nxn board for which no two queens attack one another (they are "not protected"). k queensnxn N_u(k,n) 1 2 1 1 3 1 3 4 2 3 5 2 4 6 17 4 7 1 5 8 91 """ > On the same page they say that for 5 queens controlling all the board > the number of solutions is 4860 but it is in the case that "every > queen is attacked ("protected") by at least one other". The picture > above shows a position where all queens are "safe" though. > > So my problem is how to find the solutions for 5 (FIVE) queens > controlling ALL the board with NO queen being under attack. I think > that a short visit to the problem at (http://www.cf29.com/design/ > dame5_eng.php) will make it crystal clear. > And more precisely as I did already a part of the job (see the > original post). How can I record solutions in a way that the function > goes to the NEXT possible valid position? It is probably a basic thing > but I am new to programming and it is not obvious for me. If squares > are indexed from 0, the first solution I found is [0, 10, 20, 25, 35] > and now how can I look for the next one, er, the same way as you found the first one? > record it in my solutions > list solutions_list.append(solution) -- http://mail.python.org/mailman/listinfo/python-list
getattr() question
Hi. I am trying to dynamically load a class and attributes at run time. I do not know what classes will be referenced until run time. I have it loading the module correctly, but when I use getattr to access the class and its attributes everything works except that I get additional unwanted output. The code testclass.py: #!/usr/bin/python class testclass(object): myname = "" def __init__(self, name): self.myname = name def view(self): print "hello %s" % self.myname test.py: #!/usr/bin/python import sys sys.path.append('.') from pprint import pprint if __name__ == '__main__': myname = "testclass" myaction = "view" try: tc = __import__(myname) myclass = getattr(tc,myname) myinstance = getattr(myclass('python n00b'), myaction, myaction) pprint(myinstance()) except ImportError: "error" Here is the output that I get: [EMAIL PROTECTED]:~/$ python test.py hello python n00b None [EMAIL PROTECTED]:~/$ Why is it printing 'None'? What am I doing wrong. I appreciate any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
On Dec 23, 12:39 am, Jervis Liang <[EMAIL PROTECTED]> wrote: > On Dec 22, 2:36 pm, cf29 <[EMAIL PROTECTED]> wrote: > > > The goal is to control all the chess board with five queens that do > > not attack each other. I found "manually" many solutions to this > > problem (184 until now) > > How did you find 184 solutions? Wolfram says there are 91 distinct > solutions for 5-queens on an 8x8 board with no two queens attacking > each other. > > http://mathworld.wolfram.com/QueensProblem.html If I am not mistaken, the 92 solutions are for 8 queens on a 8x8 board with no queen attacking each other. On the same page they say that for 5 queens controlling all the board the number of solutions is 4860 but it is in the case that "every queen is attacked ("protected") by at least one other". The picture above shows a position where all queens are "safe" though. So my problem is how to find the solutions for 5 (FIVE) queens controlling ALL the board with NO queen being under attack. I think that a short visit to the problem at (http://www.cf29.com/design/ dame5_eng.php) will make it crystal clear. And more precisely as I did already a part of the job (see the original post). How can I record solutions in a way that the function goes to the NEXT possible valid position? It is probably a basic thing but I am new to programming and it is not obvious for me. If squares are indexed from 0, the first solution I found is [0, 10, 20, 25, 35] and now how can I look for the next one, record it in my solutions list until there is no more? -- http://mail.python.org/mailman/listinfo/python-list
OMG please help
Here is the program I just started, The problem i am having is I'm trying to get it to load the image file Sand1 with eval(loader) = pygame.image.load(loader) because Loader is euqual to "Sand1" but It wont load it. If I set it as loader = pygame.image.load(loader) then it sets the image to the variable loader. So I'm basically trying to set a string equal to a surface variable. I dont want to have to go Sand1 = pygame.image.load("Sand1.bmp") for every image because I'm expecting there to be a lot of them when I am done. So hard to explain if you don't understand what I'm trying to get from it please let me know. import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode( (150,150) ) background = pygame.Surface( screen.get_size() ) pygame.display.set_caption("Empire Strategy") pygame.key.set_repeat(1, 1) def LoadMaterial(): loader = loading + "1" eval(loader) = pygame.image.load(loader) loader = loading + "2" eval(loader) = pygame.image.load(loader) loader = loading + "3" eval(loader) = pygame.image.load(loader) loader = loading + "4" eval(loader) = pygame.image.load(loader) loader = loading + "R" eval(loader) = pygame.image.load(loader) loader = loading + "L" eval(loader) = pygame.image.load(loader) loader = loading + "T" eval(loader) = pygame.image.load(loader) loader = loading + "D" eval(loader) = pygame.image.load(loader) loader = loading + "TR" eval(loader) = pygame.image.load(loader) loader = loading + "TL" eval(loader) = pygame.image.load(loader) loader = loading + "BR" eval(loader) = pygame.image.load(loader) loader = loading + "BL" eval(loader) = pygame.image.load(loader) loading = "Sand" LoadMaterial() pygame.display.update() repeat = True while repeat: for event in pygame.event.get(): if event.type == (QUIT): pygame.quit() if (event.type == KEYDOWN): if (event.key == K_ESCAPE): pygame.quit() if event.type == MOUSEBUTTONDOWN: if event.button == 1: position = pygame.mouse.get_pos() Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -- http://mail.python.org/mailman/listinfo/python-list
[Python API] execution environment regarding embedded python
Hi there guys and girls, I'm new (like many people I guess) to python and embedded python and have been struggling to get c++ and python to play nicely for the past couple of weeks. Up till now I've overcome most obstacles by rtfm, but there are still a few things I don't get. My setup: embedding and extending pyhton into c++ using swig on windows (mingw). I've been able to create classes in c++ and share instances of these with the embedded python interpreter. So I can instantiate an instance in c++ add this to a PyDict object, then run a script that manipulates it via python. Or of course I can instantiate the instance in a script and then retrieve it from a PyDict after running the script. ### 1st question: What's the best way to go about this? At the moment I've got a base class that python and c++ share (via swig), then in c++ I've got a container class that handles setting up a dictionary, running the script and getting the base class instance back from python. Is this the best way to do it? ### 2nd question: What's up with the local and global dictionaries in PyRun_String? When creating a new dictionary for the script to run in I know I have to add: PyDict_Update(dict, PyObject_GetAttrString(PyImport_AddModule("__main__"), "__dict__")); and / or ?! PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins() ); What's the difference between these two? At the moment I'm just putting everything into my dictionary before I run a script otherwise I get errors regarding missing functions. Then actually running the script... result = PyRun_String(const_cast(temp_script.c_str()), Py_file_input, dict, dict); This all seems to be working, though it's very unstable. If someone can point me to a nice explanation of the environment that needs to be set up to execute scripts properly it would be nice. I've read through everything I could find regarding the c API but couldn't find the difference between the global and local dict being past to PyRun_String. Most people just pass the same dictionary. ### 3rd question: I've got a seperate folder with python modules, and tell python about this using PyObject* pModule = PyImport_ImportModuleEx("site", dict, dict, NULL); PyObject* pFunc = PyDict_GetItemString(PyModule_GetDict(pModule), "addsitedir"); PyObject_CallFunction(pFunc, "s", "scripts/"); I have to do this because setting .pth files in windows doesn't work... Doing this does work, though I just hit a snag: I wrote a function that uses ceil() from the math module which should get imported automatically. When this function is defined in the script that I pass to PyRun_String it works perfectly. Though when I place it in a module in the site directory I get an error saying the global name ceil is not defined. Even when I import the math module explicitly I get the error. I don't get it. Why would it work in the script being passed to PyRun_string but not when imported from a module? I guess there's something I don't understand about the environment in which python needs to execute things. It would be great if one of you can explain all of this to me, or even just point me to where I can read up on this... Y'all have a great weekend, and enjoy the holidays! Merry x-mas, cputter -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
Michael Spencer wrote: > Tim Peters has a solution to 8 queens in test_generators in the standard > library > test suite (see: Lib/test/test_generators.py) and for a more straightforward and perhaps more grokkable implementation, see Guido's original Python demo code in Demo/scripts/queens.py -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
On Dec 22, 2:36 pm, cf29 <[EMAIL PROTECTED]> wrote: > The goal is to control all the chess board with five queens that do > not attack each other. I found "manually" many solutions to this > problem (184 until now) How did you find 184 solutions? Wolfram says there are 91 distinct solutions for 5-queens on an 8x8 board with no two queens attacking each other. http://mathworld.wolfram.com/QueensProblem.html -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
On Dec 22, 11:05 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > Only 5? The classic algorithm is 8-queens on a standard 8x8 board, > as I recall... This is a different problem. You have to control all the squares with only 5 queens. In the 8 queens problem you have to put 8 "safe queens". I also have it on my website at http://www.cf29.com/design/dame_eng.php I know about the Wikipedia 8 queens solution and it is how I discovered Python. I wanted to learn more about it to try to modify this script for the 5 queens problem. It helped me to go as far as I did with my 5 queens script but the 8 queens script only considers a number of queens equal to the number of rows. In the 5 queens problem, there are 8 rows and 3 of them are empty. It may be not particularly related to Python so may be my message is misplaced. Thanks for the help anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: Output buffer
Cesar D. Rodas wrote: > I am newbie in Python, but I like it very much. > > Right now I am having a problem, I am working with mod_python in apache. > What I needing is a stdout buffering, that means that everything that I > send to stdout keep it in a variable, then flush it and clear. plug in a StringIO instance on sys.stdout, or use (or adapt) a library designed for this purpose: http://www.mnot.net/cgi_buffer/ -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
On Dec 23, 8:05 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Sat, 22 Dec 2007 11:36:07 -0800 (PST), cf29 <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > Greetings, > > > I designed in JavaScript a small program on my website called 5 > > queens. > > Only 5? The classic algorithm is 8-queens on a standard 8x8 board, > as I recall... The classic *problem* is "8 queens don't attack each other". > > http://en.wikipedia.org/wiki/Eight_queens_puzzle#The_eight_queens_puz... and then type Ctrl-F followed by domination. As the OP says, his "goal is to control all the chess board with five queens that do not attack each other" > > > My problem starts now. How can I find the next solution and append it > > to the list? Has anyone tried to do a such script? If anyone is > > interested to help I can show what I've done so far. > > None of your problems are Python related. This is an exercise in > designing an algorithm -- algorithms are language neutral. Indeed. The Wikipedia article has several clues on how to avoid a brute-force solution to the classic problem -- some of these should be applicable to the OP's problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: 5 queens
cf29 wrote: > Greetings, > > I designed in JavaScript a small program on my website called 5 > queens. .. Has anyone tried to do a such script? If anyone is > interested to help I can show what I've done so far. Tim Peters has a solution to 8 queens in test_generators in the standard library test suite (see: Lib/test/test_generators.py) HTH Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
[EMAIL PROTECTED] a écrit : > > Bruno Desthuilliers wrote: > >>... that's definitively not >>something I'd store in global. > > > So where would you put it? You don't have to "put" functions arguments anywhere - they're already local vars. def tokenize(text): do some work returns or (yields) a list of tokens or whatever If you want the tokenizer module to work as a self-contained appliction *too*, then : if __name__ == '__main__': text = reads the text from a file or stdin for token in tokenize(text): do something with token HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this a bug in int()?
Tokenizer accepts "0x" as zero. Spec says its an error not to have at least one hex digit after "0x". This is a more serious bug than I had originally thought. Consider this: Joe types "security_code = 0x" and then goes off to the Guardian-of- the-Codes to get the appropriate hex string. Returning to computer, Joe's boss grabs him. Tells him that effective immediately he's on the "rescue us from this crisis" team; his other project can wait. Some hours, days or weeks later Joe returns to the first project. At this point Joe has a line of code that says "security_code = 0x". I think Joe would be well-served by a compiler error on that line. As is now, Joe's program assigns 0 to security_code and compiles without complaint. I'm pretty sure any line of the form "name = 0x" was a product of some form of programmer interruptus. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do i scale my axes in matplotlib?
On Dec 22, 5:42 pm, Eric Holbrook <[EMAIL PROTECTED]> wrote: > I'm using matplotlib to generate (and save) plots of bandwidth data > from simulation logs. Since the simulations are of varying lengths, i > need a way to scale the axes so that every 100,000 points on the > X-axis are roughly equal to the height of the Y-axis. In other words, > if my X data varied from 0 to 575,000, my aspect ratio would be > roughly 6:1. If X goes from 200,000 to 400,000, then the aspect ratio > should be 2:1. > > I've looked through the manuals, but i can't find out how to do > this. The 'axis' and 'axes' methods looked promising, but don't seem > to let me set an aspect ratio of the axes. Anyone know how to do this? > > tia, > Eric You should look at the matplotlib examples : There is one called "equal_aspect_ratio.py" http://matplotlib.sourceforge.net/matplotlib_examples_0.91.2svn.zip -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - what's the term for input/output to a web page?
Rachel Garrett a écrit : > Thanks to both. > > The web page I am trying to work with happens to be .aspx, so there is > lots of junk to wade through -- no clear way to tell my program how to > submit information to the page. I will keep looking, though. You don't submit information to a page, you submit informations to a web server - thru an HTTP request FWIW. So you have to: 1/ build the appropriate HTTP request 2/ connect to the server 3/ send your request 4/ get the HTTP response 5/ do whatever with it. There are Python packages dealing with all this, from the lowest level to the highest - urllib2 might be a good start. wrt/ building the request, I suppose the "page" you're mentionning has a form. Lookup the form's controls, and you'll know what arguments you can pass in. HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Steven D'Aprano wrote: > Context is all gone, so I'm not sure that I remember what "it" is. I > think it is the text that you're parsing. Yes. I'm tokenizing today. Parsing comes after Christmas. > TEXT = "placeholder" > > def parse(): > while True: > token = get_next_token() # looks at global TEXT > yield token Classic, but I'm not going to go there (at least until I fail otherwise). My tokenizer returns an array of Token objects. Each Token includes the text from which is created, locations in the original text and, for something like CONSTANT_INTEGER, it has an intValue data member. > # Run as many independent parsers as I need: > parser1 = parse(open("filename", "r").read()) > parser2 = parse(open("filename2", "r").read()) > parser3 = parse("some text") Interesting approach, that. Could have a separate parser for each statement. Hmmm. Maybe my tokenizer should return a list of arrays of Tokens, one array per statement. Hmmm. I'm thinking about an OO language construction that would be very easy to extend. Tentatively, I'll have Production objects, Statement objects, etc. I've already got Tokens. Goal is a really simple language for beginners. Decaf will be to Java as BASIC was to Fortran, I hope. -- http://mail.python.org/mailman/listinfo/python-list
Re: exception message output problem
Lie a écrit : > On Dec 22, 6:18 am, Bruno Desthuilliers > <[EMAIL PROTECTED]> wrote: > >>Lie a écrit : >>(snip) >> >> >>># Python have an odd (read: broken) singleton implementation >>># single member tuple must have a comma behind it >> >>You may call it weird or even a wart if you want, but given that what >>makes the tuple is the comma - not the parens[1] -, it is _not_ broken. >> >>[1] with the exception of the empty tuple. > > > I also realized that you don't need to use parens to make tuple, it's > rather my habit to always use parens in making a tuple FWIW, almost anybody does so except in a couple cases (mostly related to tuple unpacking). First because it's more readable, and also because - as you noticed - there are cases where you need the parens to force evaluation order. > PS: My wording on broken doesn't actually means broken so it won't > work, but rather broken syntactically, making the syntax inconsistent, > funny, illogical, etc. One could argue though that the trailing comma > is a formalized workaround. The problem is that there are not so many "grouping" characters available, and that parens end up being used for too many things: function call operator, function arguments definitions, evaluation order (grouping) and the empty tuple (and now generator expressions). I guess this would make it impractical for the parser to have to distinguish between grouping and literal tuples. So while I agree it's a bit weird, it's not illogical - once you get the logic !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: exception message output problem
Lie a écrit : > PPS: Actually, what makes a tuple is both the parens and the comma, Nope, it's definively the comma. You can check the language's grammar, it's part of the doc. Or just test FWIW: Python 2.4.3 (#1, Mar 12 2007, 23:32:01) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 1, >>> type(a) >>> > with comma as the minimum signifier, inspect this: "str(a) + > str((a,b,c))", you have to use the double parens, one to make the > tuple and the other as part of the str. This is a problem of operator precedence. -- http://mail.python.org/mailman/listinfo/python-list
Output buffer
Hello I am newbie in Python, but I like it very much. Right now I am having a problem, I am working with mod_python in apache. What I needing is a stdout buffering, that means that everything that I send to stdout keep it in a variable, then flush it and clear. Thanks in advance. -- Best Regards Cesar D. Rodas http://www.cesarodas.com http://www.thyphp.com http://www.phpajax.org Phone: +595-961-974165 -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance on local constants?
On Dec 23, 5:38 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > | >>> def spam2(x, s=re.compile('nobody expects the Spanish > Inquisition!')): > | ... return s.search(x) > | > | I suspect that this will be not only the fastest solution, but also the > | most flexible. > > 'Most flexible' in a different way is > > def searcher(rex): > crex = re.compile(rex) > def _(txt): > return crex.search(txt) > return _ > I see your obfuscatory ante and raise you several dots and underscores: class Searcher(object): def __init__(self, rex): self.crex = re.compile(rex) def __call__(self, txt): return self.crex.search(txt) Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest + sqlobject (TDD)
Thanks, it works. And thanks for your comments which are worth to think about :) Petr > This has nothing to do with your previous problem. Use > > from __main__ import myFunction, myOtherFunction, ... > > or > > from __main__ import * > > if you prefer "namespace pollution paradise"*. > > Again, it would be better to move the doctest.testfile() call into a > separate script. > > Peter > > (*) which I'm tempted to write "namespace 'pollution' paradise" or > "namespace pollution 'paradise'", but don't, for fear of "quoting hell". -- http://mail.python.org/mailman/listinfo/python-list
Re: Inter-process communication, how?
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote: > Hi, > let's say I have two scripts: one does some computations and the other > one is a graphical front end for launching the first one. And both run > in separate processes (front end runs and that it spawns a subprocess > with the computation). Now, if the computation has a result I would > like to display it in the front end. In another words, I would like to > pass some data from one process to another. How to do that? I'm > affraid I can't use a pipe since the computation could print out some > logging (if I understant pipes correctly). Others have given you good suggestions; there's also this option which may or may not be an appropriate tool for what you want to do: http://NikitaTheSpider.com/python/shm/ -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest + sqlobject (TDD)
petr.jakes.tpc wrote: > thanks for your reply. I will try to live with the > import __main__ as displeje_pokus > > in the text file. Why? > Anyway, using this, it looks like I have to assign all functions/ > methods to a local name like: > > myFunction=displeje_pokus.myFunction > > to avoid to write modul name (displeje_pokus) in front of the each > function/method calling. > > Do you think there is a way how to protect the text file contents > against such a "assigning hell"? This has nothing to do with your previous problem. Use from __main__ import myFunction, myOtherFunction, ... or from __main__ import * if you prefer "namespace pollution paradise"*. Again, it would be better to move the doctest.testfile() call into a separate script. Peter (*) which I'm tempted to write "namespace 'pollution' paradise" or "namespace pollution 'paradise'", but don't, for fear of "quoting hell". -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does __builtins__ mean different things...
Dustan wrote: > On Dec 21, 8:11 pm, James Stroud <[EMAIL PROTECTED]> wrote: >> I swear there is another thread going on here of which I am not aware. > > You just keep on telling yourself that. Is there a cricket here? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com -- http://mail.python.org/mailman/listinfo/python-list
How do i scale my axes in matplotlib?
I'm using matplotlib to generate (and save) plots of bandwidth data from simulation logs. Since the simulations are of varying lengths, i need a way to scale the axes so that every 100,000 points on the X-axis are roughly equal to the height of the Y-axis. In other words, if my X data varied from 0 to 575,000, my aspect ratio would be roughly 6:1. If X goes from 200,000 to 400,000, then the aspect ratio should be 2:1. I've looked through the manuals, but i can't find out how to do this. The 'axis' and 'axes' methods looked promising, but don't seem to let me set an aspect ratio of the axes. Anyone know how to do this? tia, Eric -- http://mail.python.org/mailman/listinfo/python-list
5 queens
Greetings, I designed in JavaScript a small program on my website called 5 queens. (http://www.cf29.com/design/dame5_eng.php) The goal is to control all the chess board with five queens that do not attack each other. I found "manually" many solutions to this problem (184 until now) and wanted to create a Python script to find them all. As I am new to Python, I struggle a lot. I found a way to create: - a board where each square is defined by its row, column and if it is controlled or not - a function that tells which squares are controlled by a queen on a particular square - a function that counts how many squares are controlled - a function that can reset all squares control to 0 - a function that can place 5 queens safely on the board - I can find the first solution and register it in a list My problem starts now. How can I find the next solution and append it to the list? Has anyone tried to do a such script? If anyone is interested to help I can show what I've done so far. -- http://mail.python.org/mailman/listinfo/python-list
Tcl/Tk 8.5.0 released
Thought this might interest some... http://www.osnews.com/story.php/19073/TclTk-8.5-Released The relevant bits for Python here are the major improvements in Tk, specifically native themed widgets for full platform integration on Windows and OS X and improved appearance under X11, additonal widgets such as a combobox and treeview, a faster, smoother text widget, anti-aliased font rendering under X11 and an improved font engine under OS X (ATUSI), and more. I've been giving 8.5 a test run in my own Tkinter application under OS X, and the improvements are pretty dramatic, especially with the addition of themed widgets. It's definitely worth checking out! --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest + sqlobject (TDD)
On Dec 22, 7:05 pm, Peter Otten <[EMAIL PROTECTED]> wrote: > petr.jakes.tpc wrote: While you could either alter the textfile to > > >>> import __main__ as displeje_pokus > > or the module along the lines of > > # not recommended! > from displeje_pokus import TextyDispleje > if __name__ == "__main__": ># doctest > else: >class TextyDispleje(SQLObject): >pass > > the clean way to fix the problem is to use a separate script to invoke the > doctest. > > Peter Peter, thanks for your reply. I will try to live with the >>> import __main__ as displeje_pokus in the text file. Anyway, using this, it looks like I have to assign all functions/ methods to a local name like: myFunction=displeje_pokus.myFunction to avoid to write modul name (displeje_pokus) in front of the each function/method calling. Do you think there is a way how to protect the text file contents against such a "assigning hell"? Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure Python GUI lib?
On Dec 22, 7:31 am, oyster <[EMAIL PROTECTED]> wrote: > For the word "Pure", I mean it is not a C/C++/Z++.. extension, so that > we can use it under pythons of different version. Is it possible? > I don't like to update the module for different python and the module > > Currently, I am writing the interface to > iup(http://www.tecgraf.puc-rio.br/iup) via ctypes, but find 2 too > strange things which have let me feel blue for some days, and I don't > know whether it can be successful or not. Can anyone give me some > lights? Thank you. :) > > You can download the files > athttp://pyguiviactypes.googlepages.com/mini_bug.zip > I am using python 2.5.1 on win2k with sp4 > While wxPython may not be pure (per se), it DOES offer some MDI interfaces. And it works with 2.3 - 2.5. I would think that that would be good enough for the purposes you mention in your post. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance on local constants?
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | >>> def spam2(x, s=re.compile('nobody expects the Spanish Inquisition!')): | ... return s.search(x) | | I suspect that this will be not only the fastest solution, but also the | most flexible. 'Most flexible' in a different way is def searcher(rex): crex = re.compile(rex) def _(txt): return crex.search(txt) return _ One can then create and keep around multiple searchers based on different patterns, to be used as needed. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: The 0.8181818181... Truth Movement
Proginoskes wrote: > On Dec 20, 4:29 pm, Dustan <[EMAIL PROTECTED]> wrote: >> On Dec 20, 8:24 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: >> >>> On Thu, 20 Dec 2007 03:04:48 -0800, Dustan wrote: On Dec 20, 1:05 am, Proginoskes <[EMAIL PROTECTED]> wrote: > I myself prefer the 0.81818181... Truth Movement. More precisely, 0.81818181818181823. >>> Hm... >>> In [59]: '%.60f' % (9 / 11.0) >>> Out[59]: '0.81818181818181823228286475568893365561962127685546875000' > > Only using double precision. Weenie. > >> Whoa... I only just realized, this was cross-posted to four other >> groups. [...] > > And we have comprehension! > > Other posts about 9/11 to sci.math are likely to receive the same > treatment. > > --- Christopher Heckman And what is the answer to 818181818/17 or about 0.8181818122727273140909088013636383904545312668182811... ? David Bernier -- http://mail.python.org/mailman/listinfo/python-list
Re: disabling button
if you disable the button it can still respond to clicks? it only greys out.. or is there a problem with my code here? class MyApp: def __init__(self,parent): self.mainframe=Frame(parent) self.mainframe.pack() self.button1=Button(self.mainframe,bg="green") self.button1.configure(text="1") self.button1.pack(side=LEFT) self.button1.bind("",self.buttonClick1) self.button2=Button(self.mainframe,bg="yellow") self.button2.configure(text="2") self.button2.pack(side=LEFT) self.button2.bind("",self.buttonClick2) self.button3=Button(self.mainframe,bg="red") self.button3.configure(text="3") self.button3.pack(side=RIGHT) self.button3.bind("",self.buttonClick3) def buttonClick1(self,event): print "ok clicked" self.button2.configure(state=DISABLED) self.button2.update_idletasks() def buttonClick2(self,event): print "2 clicked" def buttonClick3(self,event): print "3 clicked" self.button2.configure(state=NORMAL) #self.button2.update_idletasks() root = Tk() myapp = MyApp(root) root.mainloop() here when u click button 1 ,the button2 greys out but can still respond to clicks..is there a way to truly disable it? damon -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest + sqlobject (TDD)
petr.jakes.tpc wrote: > Hi, > > inspired by the article written by Tarek Ziade in the February 07 > issue of the "Linux +" magazine I am experimenting with the doctest > module. > > I have two files, "displeje_pokus.py" and "displeje_pokus.txt" (you > can see the simplified contents of the files bellow). > > When I run "python displeje_pokus.py" I am getting an error (see > below) which I am not able to eliminate. > > thanks for your reply > > Petr Jakes > > == > displeje_pokus.py > == > from sqlobject import * > class TextyDispleje(SQLObject): > pass > > if __name__ == "__main__": > import doctest > doctest.testfile("displeje_pokus.txt", verbose=True) > > == > displeje_pokus.txt > == import displeje_pokus > > > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on VIT, Standard Trying: > import displeje_pokus > Expecting nothing > ** > File "Z:\automat\displeje_pokus.txt", line 13, in displeje_pokus.txt > Failed example: > import displeje_pokus > Exception raised: > Traceback (most recent call last): > File "C:\Python25\lib\doctest.py", line 1212, in __run > compileflags, 1) in test.globs > File "", line 1, in > import displeje_pokus > File "Z:\automat\displeje_pokus.py", line 41, in > class TextyDispleje(sqlobject.SQLObject): > File "c:\python25\lib\site-packages\SQLObject-0.9.2-py2.5.egg > \sqlobject\declarative.py", line 121, in __new__ > cls.__classinit__(cls, new_attrs) > File "c:\python25\lib\site-packages\SQLObject-0.9.2-py2.5.egg > \sqlobject\main.py", line 803, in __classinit__ > classregistry.registry(cls.sqlmeta.registry).addClass(cls) > File "c:\python25\lib\site-packages\SQLObject-0.9.2-py2.5.egg > \sqlobject\classregistry.py", line 91, in addClass > '__file__', '(unknown)'))) > ValueError: class TextyDispleje is already in the registry (other > class is , from the module __main__ in > Z:\automat\displeje_pokus.py; attempted new class is 'displeje_pokus.TextyDispleje'>, from the module displeje_pokus in Z: > \automat\displeje_pokus.py) > ** > 1 items had failures: >1 of 1 in displeje_pokus.txt > 1 tests in 1 items. > 0 passed and 1 failed. > ***Test Failed*** 1 failures. It seems that sqlobject does not allow for two SQLObject subclasses with the same name: >>> from sqlobject import SQLObject >>> class A(SQLObject): pass ... >>> try: ... class A(SQLObject): pass ... except: ... print "Oops!" ... Oops! In your scenario these are __main__.TextyDispleje and displeje_pokus.TextyDispleye. While you could either alter the textfile to >>> import __main__ as displeje_pokus or the module along the lines of # not recommended! from displeje_pokus import TextyDispleje if __name__ == "__main__": # doctest else: class TextyDispleje(SQLObject): pass the clean way to fix the problem is to use a separate script to invoke the doctest. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Seperate Files
katie smith wrote: > I'm attempting to create a game and right now the game has 6000 lines of > code and is confusing me. > > I have seen it done but have no idea how to do it, but I would like to > use seperate files and incorporate them together. One for my units, one > for the map maker, one for the playing part. > > Any ideas on how to do that? chapter 6 in the tutorial has the full story: http://docs.python.org/tut/node8.html -- http://mail.python.org/mailman/listinfo/python-list
doctest + sqlobject (TDD)
Hi, inspired by the article written by Tarek Ziade in the February 07 issue of the "Linux +" magazine I am experimenting with the doctest module. I have two files, "displeje_pokus.py" and "displeje_pokus.txt" (you can see the simplified contents of the files bellow). When I run "python displeje_pokus.py" I am getting an error (see below) which I am not able to eliminate. thanks for your reply Petr Jakes == displeje_pokus.py == from sqlobject import * class TextyDispleje(SQLObject): pass if __name__ == "__main__": import doctest doctest.testfile("displeje_pokus.txt", verbose=True) == displeje_pokus.txt == >>> import displeje_pokus Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on VIT, Standard >>> Trying: import displeje_pokus Expecting nothing ** File "Z:\automat\displeje_pokus.txt", line 13, in displeje_pokus.txt Failed example: import displeje_pokus Exception raised: Traceback (most recent call last): File "C:\Python25\lib\doctest.py", line 1212, in __run compileflags, 1) in test.globs File "", line 1, in import displeje_pokus File "Z:\automat\displeje_pokus.py", line 41, in class TextyDispleje(sqlobject.SQLObject): File "c:\python25\lib\site-packages\SQLObject-0.9.2-py2.5.egg \sqlobject\declarative.py", line 121, in __new__ cls.__classinit__(cls, new_attrs) File "c:\python25\lib\site-packages\SQLObject-0.9.2-py2.5.egg \sqlobject\main.py", line 803, in __classinit__ classregistry.registry(cls.sqlmeta.registry).addClass(cls) File "c:\python25\lib\site-packages\SQLObject-0.9.2-py2.5.egg \sqlobject\classregistry.py", line 91, in addClass '__file__', '(unknown)'))) ValueError: class TextyDispleje is already in the registry (other class is , from the module __main__ in Z:\automat\displeje_pokus.py; attempted new class is , from the module displeje_pokus in Z: \automat\displeje_pokus.py) ** 1 items had failures: 1 of 1 in displeje_pokus.txt 1 tests in 1 items. 0 passed and 1 failed. ***Test Failed*** 1 failures. -- http://mail.python.org/mailman/listinfo/python-list
Seperate Files
I'm attempting to create a game and right now the game has 6000 lines of code and is confusing me. I have seen it done but have no idea how to do it, but I would like to use seperate files and incorporate them together. One for my units, one for the map maker, one for the playing part. Any ideas on how to do that? Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs-- http://mail.python.org/mailman/listinfo/python-list
gtk.TreeView cell inconsistent state
In the below code setting cell to inconsistent sets entire column inconsistent (renderer).However, I need a third state off | on | inconsistent . How can I change one path->cell? Any help appreciated. Thanks john # get current value fixed = model.get_value(iter, MARK_FOR_COLUMN) icont = model.get_value(iter,MARK_FOR_INCONSISTENT) # clear for action model.set(iter,MARK_FOR_INCONSISTENT,False) cell.set_property('inconsistent',False) cell.set_property('active',False) # ready for action # find resolution to all being marked inconsistent # flip modified as we are changing it model.set_value(iter,MODIFIED_COLUMN,not modified) if icont: cell.set_property('inconsistent',True) else: model.set(iter,MARK_FOR_INCONSISTENT, not icont) model.set(iter, MARK_FOR_COLUMN, not fixed) model.set(iter,ICON_COLUMN, icon) model.row_changed(path,iter) ___ Join Excite! - http://www.excite.com The most personalized portal on the Web! -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
"Dennis Lee Bieber" <...netcom.com> wrote: > SD declaimed the following in > comp.lang.python: > > > > > At 15-35 lines, it is short enough for people to copy it down on paper, > > or even memorize it, then take it home and work on finding a > > vulnerability in it. > > I'd actually been thinking of the real product getting out, > not just the "protection"... I wonder if the OP would not be better off splitting the app into two bits, releasing the "client" side and keeping the "server" side secret, in a protected directory. That would add the complication of a protocol to make a hacker's life more miserable, and if there is an "interesting bit" it can be hidden in the server side. It also has the advantage that you can log accesses to the server. Its a lot of extra work, though, and if the stuff is computationally intensive, it can be slow, because what could be done concurrently on several client machines would be done serially on the single secret server. Pyro could help here, as always. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting memory leaks on apache, mod_python
On 22 Δεκ, 09:09, Fredrik Lundh <[EMAIL PROTECTED]> wrote: [...] > For Python, standard process monitoring tools (combined with a basic > understanding of how dynamic memory allocation works on modern > platforms) are usually sufficient to get a good view of an application's > memory usage patterns. [...] which "standard process monitoring tools" are those? Aren't there any python specific tools (e.g. which list the python modules which use the memory)? . http://case.lazaridis.com/wiki/PythonAudit -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - what's the term for input/output to a web page?
Thanks to both. The web page I am trying to work with happens to be .aspx, so there is lots of junk to wade through -- no clear way to tell my program how to submit information to the page. I will keep looking, though. -- http://mail.python.org/mailman/listinfo/python-list
$$$$ HONEST MONEY MAKING $$$$
No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.516 / Virus Database: 269.17.6/1192 - Release Date: 12/21/2007 1:17 PM -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simple way to parse this string ?
Steven D'Aprano, On Dec 21, 2:08 am, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Thu, 20 Dec 2007 20:27:23 -0800, [EMAIL PROTECTED] wrote: > > Stef, > > > For clarification, there is nothing hazardous about using eval on the > > string that you presented. > > > t = eval('(0, 0, 0, 255), (192, 192, 192, 255), True, 8') > > > Whether or not this is the "simplest" solution, remains a question. > > For clarification, if all the poster wanted was to convert the *specific* > *known* string to a tuple, he would be better off just writing it as a > tuple: Steven, No, that's not what he asked. Read the original question. > > t = (0, 0, 0, 255), (192, 192, 192, 255), True, 8 > > is much faster than calling eval(). > > But obviously that's not what the Original Poster wants to do. There's nothing "Obviously" Implied about what the author wants to do here, besides convert an innocent string object to a tuple. > The tuple > give was indicative of input that comes from somewhere Really? I personally can't tell that from his provided example. There's definitely not enough info on this one. > -- perhaps a > config file, perhaps a web form, perhaps a command line argument, who > knows? The point is, if the string comes from a user, then it could > contain anything: > > '(0, 0, 0, 255), (192, 192, 192, 255), True, 8' > '1000, 10001, 12, 104' > '"foo bar baz".split()' > '[i for i in range(10)]' > '[19852.7412]*10**2' > '__import__("os").system("ls -r *")' > > Just because the OP's specific example is safe doesn't make eval() safe. Agreed. And after the last couple comments, he was probably made aware of that. Thank you for reiterating :-) > > -- > Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib problem, Unable to relay for
On 2007-12-21, Benedict Verheyen <[EMAIL PROTECTED]> wrote: > i get an "Unable to relay for" when trying to send an email > from within my network to an email address not on my domain. I > don't understand why it says "relaying" as i'm sending from an > internal domain user to an external user. You're asking the SMTP server to accept mail for a user that's not local to that server. That's relaying. > Email server is exchange 2003 Ah, well, that's too bad. You can probably get it to work anyway... > See this trace > > >>> smtp.sendmail("[EMAIL PROTECTED]", ["[EMAIL PROTECTED]"], msg) > Traceback (most recent call last): >File "", line 1, in >File "C:\Python25\Lib\smtplib.py", line 695, in sendmail > raise SMTPRecipientsRefused(senderrs) > smtplib.SMTPRecipientsRefused: {'[EMAIL PROTECTED]': (550, '5.7.1 > Unable to relay for [EMAIL PROTECTED]')} > > The smpt var is this: > smtp = smtplib.SMTP(server) where server is my mail server > > I can mail to any user that is part of mydomain.be but as soon > as i try an external address, i get the "Unable to relay" > message. > > With a mail program it works With what "mail program"? Outlook? Outlook doesn't use SMTP to send mail, so it doesn't matter what works or doesn't work in Outlook. If relaying does work with other SMTP clients, then comparing a TCP trace of a program that works with one from a program that doesn't work would be very informative. > but i need to be able to do it via code. You can use Python to send e-mails via Outlook if you want to do that instead of using SMTP. However, Microsoft has crippled Outlook's automation interface in a half-witted and mostly ineffectual attempt to plug security holes. So, you have to jump through a hoop to bypass Microsoft Outlook's security stuff (it's not really hard to bypass -- big surprise there). Googling for "python sending mail with outlook" will find you all sorts of examples. > I thought that i would have to authenticate (smtp.login) to > our mail server but that didn't resolve the issue > > Any idea how i could do this? Ask the Exchange admin to enable relaying. But, (this is _very_important_) make sure he limits relaying so that it only relays mail accepted from the _internal_ network. If you allowing relaying of mail accepted from outside hosts (to outside hosts), you'll be used by spammers and criminals for all sorts of evil, mischief, and crime. -- Grant Edwards grante Yow! I'm rated PG-34!! at visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: 3D plotting with python 2.5 on win32
On Dec 20, 1:24 pm, Peter Wang <[EMAIL PROTECTED]> wrote: > On a side note, we are almost done putting together an updated one- > click installer of python + packages for scientific computing. This > will be based on Python 2.5, will include most of what was included in > the 2.4.3-based installer, and will be available for multiple > platforms. > > -Peter We who? (a little of a side note) I just bought Chun's book and have been monitor c.l.p. I also browsed through the Enthought site. While I found Enthought very interesting, I found it kind of disappointing that they seem to support Windows, only, unless I am not seeing the big picture. In anycase, I would really like very much to see what you are talking about, a multi-platform one-clik-installer of python+scientific- computing...who is "we" and where do you think it will be? gsal -- http://mail.python.org/mailman/listinfo/python-list
Twisted: UDP socket not closed.
Hi. I have to send UDP packets very often. Approx twice in a second. But socket is not closed after sending packet. So soon i bump into open sockets\files limit. How to close socket after sending data? Python 2.5, Twisted class DataClient(DatagramProtocol): def __init__(self, address, datagram = "PONG"): self.address, self.datagram = address, datagram def startProtocol(self): self.transport.socket.setsockopt(socket.SOL_SOCKET, \ socket.SO_BROADCAST, True) self.transport.connect(self.address[0], self.address[1]) self.sendDatagram() def sendDatagram(self): self.transport.write(self.datagram) debug("Data client: Sending to %s" % repr(self.address)) while True: clientprotocol = DataClient(("255.255.255.255", 5999), data) reactor.listenUDP(0, clientprotocol).stopListening() [EMAIL PROTECTED]:~$ ls -la /proc/15429/fd/ | wc -l 43 [EMAIL PROTECTED]:~$ ls -la /proc/15429/fd/ | wc -l 44 [EMAIL PROTECTED]:~$ ls -la /proc/15429/fd/ | wc -l 44 [EMAIL PROTECTED]:~$ ls -la /proc/15429/fd/ | wc -l 44 [EMAIL PROTECTED]:~$ ls -la /proc/15429/fd/ | wc -l 45 [EMAIL PROTECTED]:~$ ls -la /proc/15429/fd/ | wc -l 45 [EMAIL PROTECTED]:~$ ls -la /proc/15429/fd/ | wc -l 46 Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: fiber(cooperative multi-threading)
On Dec 22, 2:37 pm, Duncan Booth <[EMAIL PROTECTED]> wrote: > Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > > I am not really familiar with ruby but these fibers seem to be some > > sort of coroutines. Since python 2.5, generators can be sent values, > > this can be used to implement what you want. I have had a got at it > > for fun and this is what I came up with: note that there is no need > > for a specific class, or for threads. I have tested this only on your > > example, but it gives the same result as your code :) > > I think it was Microsoft who invented the term 'fiber' as a synonym for > coroutine. Seehttp://msdn2.microsoft.com/en-us/library/ms682661.aspx OK > Unfortunately generators only save a single level of stack-frame, so they > are not really a replacement for fibers/coroutines. The OP should perhaps > look at Stackless Python or Greenlets. > Seehttp://codespeak.net/py/dist/greenlet.html Still what I am proposing offers a level of cooperative multi- threading which may be enough for the OP. In fact it is not clear to me at the moment what can be done (sensibly :) with the OP's Fiber class that cannot be achieved with the run() function I suggested. This makes me think that there is something important that I am failing to take into consideration; I would be grateful if it was pointed out to me. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: exception message output problem
Lie wrote: > PPS: Actually, what makes a tuple is both the parens and the comma, > with comma as the minimum signifier, inspect this: "str(a) + > str((a,b,c))", you have to use the double parens, one to make the > tuple and the other as part of the str. This harmless little case > gives error if done without the double parens, but what would happen > if we exchange the str into a function that accepts one argument and > several optional arguments (or better yet, one argument and an > optional * argument)? I think the effect there is operator precedence. In str(a,b,c) the function-calling operator () takes over, and the commas are considered as argument separators. In str ((a,b,c)) the inner parens present a single tuple-expression to the function-calling operator. Just like a+b/c as against (a+b)/c but with esoteric overloading of ( ) and , . Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: fiber(cooperative multi-threading)
Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > I am not really familiar with ruby but these fibers seem to be some > sort of coroutines. Since python 2.5, generators can be sent values, > this can be used to implement what you want. I have had a got at it > for fun and this is what I came up with: note that there is no need > for a specific class, or for threads. I have tested this only on your > example, but it gives the same result as your code :) I think it was Microsoft who invented the term 'fiber' as a synonym for coroutine. See http://msdn2.microsoft.com/en-us/library/ms682661.aspx Unfortunately generators only save a single level of stack-frame, so they are not really a replacement for fibers/coroutines. The OP should perhaps look at Stackless Python or Greenlets. See http://codespeak.net/py/dist/greenlet.html -- http://mail.python.org/mailman/listinfo/python-list
Re: The 0.8181818181... Truth Movement
On 1117th December 2004, Dustan <[EMAIL PROTECTED]> wrote: > I must break my promise and make another post. > > On Dec 22, 2:31 am, Proginoskes <[EMAIL PROTECTED]> wrote: > > On Dec 20, 4:29 pm, Dustan <[EMAIL PROTECTED]> wrote: > > > > > On Dec 20, 8:24 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > > > > > > On Thu, 20 Dec 2007 03:04:48 -0800, Dustan wrote: > > > > > On Dec 20, 1:05 am, Proginoskes <[EMAIL PROTECTED]> wrote: > > > > >> I myself prefer the 0.81818181... Truth Movement. > > > > > More precisely, 0.81818181818181823. > > > > Hm... > > > > In [59]: '%.60f' % (9 / 11.0) > > > > Out[59]: > > > > '0.81818181818181823228286475568893365561962127685546875000' > > > > Only using double precision. Weenie. > > Look at the list of groups. Python's the only language in there. > Python uses double precision. Period. But Professor Checkman was evidently interested in decimals, so surely this is more relevant: >>> from decimal import * >>> Decimal('9')/Decimal('11') Decimal("0.8181818181818181818181818182") That's not double precision. So evidently Python uses more than just double precision. So your above absolute statement is either wrong or misleading. Period. ... > Of course, I could also have said that 9/11==0. Would you have figured > out what I was talking about then? Odd, it appears that you joined the thread after the good professor did. Therefore it is you who should be trying to figure out what _he_ was saying, not the other way round. Phil -- Dear aunt, let's set so double the killer delete select all. -- Microsoft voice recognition live demonstration -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting memory leaks on apache, mod_python
Steven D'Aprano wrote: >> > Not me. >> >> You're quite knew to this internet thing, aren't you? ;-) > > :-D (hmm. why is that whenever you make some silly last-second addition to a post, you end up making a stupid typo?) >> And things like "how much memory is free in the heap" isn't even a >> meaningful concept on a modern machine, thanks to the wonders of virtual >> memory (especially the overcommitting kind). > > Maybe the memory model used in modern multi-tasking virtual-memory PCs > makes the concept of "free memory" obsolete. Although if so, somebody > should have a quiet word with the author of the Linux free command: > > $ free > total used free sharedbuffers cached > Mem: 1002524 988736 13788 0 7044 98916 > -/+ buffers/cache: 882776 119748 > Swap: 42410803939736 301344 > > (Admittedly that's system-wide memory usage, rather than for a single > process.) the problem isn't that you can get a number, it's that the number you get has no *direct* correlation to the amount of memory your process can actually allocate -- or at least allocate without causing excessive swapping or triggering the OOM killer or otherwise annoying all the other processes on the machine. >> For Python, standard process monitoring tools (combined with a basic >> understanding of how dynamic memory allocation works on modern >> platforms) are usually sufficient to get a good view of an application's >> memory usage patterns. Just run the program under a few different >> scenarios, and see what it does. > > Are you saying that Python programs can't monitor their own memory use? > > I'm happy to accept that "free memory" is not a meaningful concept for a > process in a modern system. That makes sense. But surely it is reasonable > for a process to have an idea of how much memory it has actually used. > Yes? No? unless you do utterly trivial things, a process allocates memory from a lot of different resource pools (i/o buffers, virtual memory buffers, network buffers, graphics resources, etc). there's simply no way for the process itself to know how much memory it uses. if you want to know, ask the operating system. >> If the memory use looks suspicious, >> use standard debugging techniques to locate the problematic area, and >> standard benchmarking techniques to look for unexpected blowups and >> leaks. > > What sort of "standard debugging techniques" work in the absence of any > way (that I know of) to measure memory usage? as I said, use standard process monitoring tools (i.e. "ps" and "top" etc on Unix, the task manager on Windows) takes you a long way. > In Python, standard > debugging techniques usually start with the print statement > but one can't do anything like this: > > # problematic area of code > last = memory() > for i in xrange(100): > x = foo() > if memory() >= last: > print "memory use increased", memory() it doesn't have to be harder than this: # problematic area of code raw_input("before: check memory here") for i in xrange(100): x = foo() raw_input("after: check memory here") on unix, you can also do e.g. os.system("ps ux") or os.system("ps -F -p %d" % os.getpid()) or some variation thereof. > So what are you suggesting is standard? running individual modules/classes/functions under test harnesses, so you can analyze their behaviour under well-known conditions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure Python GUI lib?
> For the word "Pure", I mean it is not a C/C++/Z++.. extension, so that > we can use it under pythons of different version. Is it possible? The python-xlib project provides such a module. It implements the X11 protocol directly. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: disabling button
an explicit call to "update_idletasks" will clear out the > task queue for you. > it worked Thanks F.L!! dn -- http://mail.python.org/mailman/listinfo/python-list
Re: fiber(cooperative multi-threading)
On Dec 22, 12:10 pm, Akihiro KAYAMA <[EMAIL PROTECTED]> wrote: > Hi all. > > I found cooperative multi-threading(only one thread runs at once, > explicit thread switching) is useful for writing some simulators. > With it, I'm able to be free from annoying mutual exclusion, and make > results deterministic. > > For this purpose, and inspired by Ruby(1.9) fiber, I wrote my own > version of fiber in Python. > > It just works, but using native Python threads for non-preemptive > threading is not cost-effective. Python has generator instead but it > seemed to be very restricted for general scripting. I wish I could > write nested (generator) functions easily at least. > > Is there any plan of implementing real (lightweight) fiber in Python? > > > import threading > > class Fiber(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > > self.semaphore_running = threading.Semaphore(0) > self.semaphore_finish = None > self.val = None > > self.setDaemon(True) > self.start() > self.start = self.start_fiber > > def start_fiber(self): > self.semaphore_finish = threading.Semaphore(0) > self.semaphore_running.release() > self.semaphore_finish.acquire() > > def run(self): # override > self.semaphore_running.acquire() > self.main() > if self.semaphore_finish is not None: > self.semaphore_finish.release() > > def switchto(self, fiber, val=None): > fiber.val = val > fiber.semaphore_running.release() > self.semaphore_running.acquire() > return self.val > > def main(self): # should be overridden > pass > > class F1(Fiber): > def main(self): > print "f1 start" > self.switchto(f2) > print "f1 foo" > v = self.switchto(f2) > print "f1 v=%s world" % v > self.switchto(f2, "OK") > print "f1 end" > > class F2(Fiber): > def main(self): > print "f2 start" > self.switchto(f1) > print "f2 bar" > result = self.switchto(f1, "Hello, ") > print "f2 result=%s" % result > print "f2 end" > self.switchto(f1) > > f1 = F1() > f2 = F2() > > print "start" > f1.start() > print "end" > > -- kayama I am not really familiar with ruby but these fibers seem to be some sort of coroutines. Since python 2.5, generators can be sent values, this can be used to implement what you want. I have had a got at it for fun and this is what I came up with: note that there is no need for a specific class, or for threads. I have tested this only on your example, but it gives the same result as your code :) - # A 'fiber' is a generator function that yields tuples (fiber, value) # or (fiber,). The 'run' function starts the the fiber and carries on # with the fiber it yields. If the fiber also yields a value, then # this value is sent to the 'next' fiber. def run(fiber): it, val = fiber(), [] fibers = { fiber: it } try: while True: n = it.send(*val) if val else it.next() co, val = n[0], n[1:] it = fibers.get(co) if it is None: fibers[co] = it = co() except StopIteration: return val[0] if val else None # Now the two 'fibers' def f1(): print "f1 start" yield f2, print "f1 foo" v = yield f2, print "f1 v=%s world" % v yield f2, "OK" print "f1 end" def f2(): print "f2 start" yield f1, print "f2 bar" result = yield f1, "Hello, " print "f2 result=%s" % result print "f2 end" yield f1, print "start" run(f1) print "end" -- HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: disabling button
[EMAIL PROTECTED] wrote: > then in the buttonClick(self,event) i want to disable it till some > time consuming calculations are completed ..then i enable it > > def button1Click(self, event): > self.okButton.configure(state=DISABLED) + self.okButton.update_idletasks() > print "ok disabled" > somebigcalculations() > self.okButton.configure(state=NORMAL) > print "ok enabled" > > well,the button doesn't grey out when i click it ,though the print > staements are executed.. > but if some error happens and program exits with some ioerror(say > errno2 file not found ..)then the button is shown as greyed out.. > > am i missing something here ? how can i get the button disabled and > greyed out on clicking it? when Tkinter needs to redraw things, it adds the redraw action to an internal "task" queue. tasks in this queue are usually handled by the main event loop, but that loop doesn't run when you do your big calculations. an explicit call to "update_idletasks" will clear out the task queue for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance on local constants?
On Dec 22, 6:04 am, John Machin <[EMAIL PROTECTED]> wrote: > t3 = re.compile('whatever').search Ack! No! Too Pythonic! GETITOFF! GETITOFF!! -- http://mail.python.org/mailman/listinfo/python-list
Re: exception message output problem
Russ P. wrote: > Actually, the parens aren't needed, so this works too: > > def __init__(self, args=""): self.args = args, > > The trailing comma wasn't necessary a while back (pre 2.5?), so > something in Python must have changed. I'd say that it looks a bit > cleaner without the trailing comma, so maybe whatever changed should > get changed back. as the name implies, "args" is supposed to be a sequence, and is stored internally as a tuple. if something has changed, it's probably that 2.5 enforces this behaviour via a property. to fix your code, just replace your own __init__ method with a "pass", and leave the initialization to the Exception class itself. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does __builtins__ mean different things...
On Dec 21, 8:11 pm, James Stroud <[EMAIL PROTECTED]> wrote: > I swear there is another thread going on here of which I am not aware. You just keep on telling yourself that. -- http://mail.python.org/mailman/listinfo/python-list
Pure Python GUI lib?
For the word "Pure", I mean it is not a C/C++/Z++.. extension, so that we can use it under pythons of different version. Is it possible? I don't like to update the module for different python and the module Currently, I am writing the interface to iup(http://www.tecgraf.puc-rio.br/iup) via ctypes, but find 2 too strange things which have let me feel blue for some days, and I don't know whether it can be successful or not. Can anyone give me some lights? Thank you. :) You can download the files at http://pyguiviactypes.googlepages.com/mini_bug.zip I am using python 2.5.1 on win2k with sp4 1. in iup.py, if I delete [code] _IupMap.argtypes= [ PTR_Ihandle,#ih ] [/code] then when I choose the menu "MDI-New", no MDI window come out. Why it behaves like this? 2. for most of the time, I can only choose menu "MDI-New" 3~4 times, then it crashes with this msg: [msg] Traceback (most recent call last): File "\loewis\25\python\Modules\_ctypes\callbacks.c", line 206, in 'calling callback function' File "mdisample_callback.py", line 372, in mdi_new IupShow(dlg) File "H:\my_project\iup4py\mini\iup\iup.py", line 434, in IupShow ih, WindowsError: exception: access violation writing 0x72292AA4 Traceback (most recent call last): File "mdisample_callback.py", line 455, in main() File "mdisample_callback.py", line 447, in main IupMainLoop() File "H:\my_project\iup4py\mini\iup\iup.py", line 247, in IupMainLoop return _IupMainLoop() WindowsError: exception: access violation writing 0x9B73F12E [/msg] sometimes the above happens when I delete some "???.argtypes=???" form iup.py 3. and some time, python crashes with this msg: [msg] Traceback (most recent call last): File "mdisample_callback.py", line 455, in main() File "mdisample_callback.py", line 447, in main IupMainLoop() File "H:\my_project\iup4py\mini\iup\iup.py", line 247, in IupMainLoop return _IupMainLoop() WindowsError: exception: priviledged instruction [/msg] -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting memory leaks on apache, mod_python
On Sat, 22 Dec 2007 08:09:50 +0100, Fredrik Lundh wrote: > Steven D'Aprano wrote: > > > Not me. > > You're quite knew to this internet thing, aren't you? ;-) :-D >> So... how do you measure memory usage in Python? Every programming >> language I've used before (not a huge range, I'll admit) had *some* >> sort of facility to measure memory usage, typically things like: >> >> * how much memory is free in the stack? >> >> * how much memory is free in the heap? >> >> * how big a block does this pointer point to? >> >> * how much memory does this record/struct/object/string use? > > And what languages would that be? I cannot think of a single modern > language that does any of that. Including low-level stuff like C/C++. I didn't actually say they were *modern* languages. E.g. THINK Pascal for Apple Mac, circa 1990. > And things like "how much memory is free in the heap" isn't even a > meaningful concept on a modern machine, thanks to the wonders of virtual > memory (especially the overcommitting kind). Maybe the memory model used in modern multi-tasking virtual-memory PCs makes the concept of "free memory" obsolete. Although if so, somebody should have a quiet word with the author of the Linux free command: $ free total used free sharedbuffers cached Mem: 1002524 988736 13788 0 7044 98916 -/+ buffers/cache: 882776 119748 Swap: 42410803939736 301344 (Admittedly that's system-wide memory usage, rather than for a single process.) > For Python, standard process monitoring tools (combined with a basic > understanding of how dynamic memory allocation works on modern > platforms) are usually sufficient to get a good view of an application's > memory usage patterns. Just run the program under a few different > scenarios, and see what it does. Are you saying that Python programs can't monitor their own memory use? I'm happy to accept that "free memory" is not a meaningful concept for a process in a modern system. That makes sense. But surely it is reasonable for a process to have an idea of how much memory it has actually used. Yes? No? > If the memory use looks suspicious, > use standard debugging techniques to locate the problematic area, and > standard benchmarking techniques to look for unexpected blowups and > leaks. What sort of "standard debugging techniques" work in the absence of any way (that I know of) to measure memory usage? In Python, standard debugging techniques usually start with the print statement, but one can't do anything like this: # problematic area of code last = memory() for i in xrange(100): x = foo() if memory() >= last: print "memory use increased", memory() So what are you suggesting is standard? > For really hard problems, use the "gc" module, instrumenting memory > allocation libraries (e.g. dmalloc), or C/C++-level debuggers. I'm not so much concerned about the really hard problems as I am about the really easy ones. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
On Sat, 22 Dec 2007 04:13:31 -0800, MartinRinehart wrote: > Bruno Desthuilliers wrote: >> ... that's definitively not >> something I'd store in global. > > So where would you put it? Context is all gone, so I'm not sure that I remember what "it" is. I think it is the text that you're parsing. I believe you are currently doing something like this: TEXT = "placeholder" def parse(): while True: token = get_next_token() # looks at global TEXT yield token # And finally actually run your parser: TEXT = open("filename", "r").read() for token in parse(): print token If I were doing this, I would do something like this: def parse(text): while True: token = get_next_token() # looks at local text yield token # Run as many independent parsers as I need: parser1 = parse(open("filename", "r").read()) parser2 = parse(open("filename2", "r").read()) parser3 = parse("some text") for token in parser1: print token # etc. Unless the text you are parsing is truly enormous (multiple hundreds of megabytes) you are unlikely to run into memory problems. And you gain the ability to run multiple parsers at once. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get Python to default to UTF8
weheh wrote: > Hi Fredrik, thanks for responding. After reading up some more on this, I > think my title should be changed to "How to get Python to default to ASCII". > In point of fact, I want my 2 environments to agree so that I can debug > thinkgs more easily. Right now it's a nightmare. > > As to your questions, in this example, I believe the exception was caused by > trying to do a count of the number of times a string appears in an array. > One of the strings was unicode and the other was encoded by Python by > default. to fix this, figure out from where you got the encoded (8-bit) string, and make sure you decode it properly on the way in. only use Unicode strings on the "inside". (Python does have two encoding defaults; there's a default encoding that *shouldn't* ever be changed from the "ascii" default, and there's also a stdin/stdout encoding that's correctly set if you run the code in an ordinary terminal window. if you get your data from anywhere else, you cannot trust any of these, so you should do your own decoding on the way in, and encoding things on the way out). -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd behavior in Python/Tkinter?
On Dec 22, 7:35 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Lie wrote: > > But an expression (e.g. string) is NOT a variable. > > in this case, it is. I don't know if it's worth spending more time on > this, since you're not listening, but let's make one more attempt. Sure I'm listening (well, actually I'm reading), but please spare me since I can't understand what you meant in the previous posts (I'm just starting Python, and yesterday was my first introduction to Tkinter/Tk/Tcl). Everyone has their own newbie moments... > for the Entry widget, the "textvariable" argument, if given, identifies > an *internal* Tkinter variable (managed by the embedded Tcl inter- > preter, not Python). changes to this variable will be reflected in the > widget, and changes to the widget will be reflected in the variable. That clears things up. I never realized that we can even specify the name for the Tcl's variable, setting its values is a behavior, but setting its name is... some kind of incomplete encapsulation (well its understandable, complete encapsulation is never a Pythonic thing and proper ways to keep the encapsulation is available [through StringVar]). > the *usual* way to create such a variable is to use StringVar, and leave > it to Tkinter to come up with an internal variable name, but you can > refer to any Tcl variable; if it doesn't exist, it's created. > > in your example, you told both widgets to use the same internal > variable. you can do the same thing with a StringVar: > > var = Tk.StringVar() > > e1 = Tk.Entry(root, textvariable = var) > e2 = Tk.Entry(root, textvariable = var) > > doing this has the advantage that you can access the internal variable > via the StringVar object (held in the Python variable named "var"), but > at the Tkinter level, it's exactly the same thing. changes to the > variable will be reflected in both widgets, and changes to *either* > widget will be reflected in the variable, and therefore also in the > other widget. > > On the other hand, the oddness multiplied since the value replication > > doesn't happen if I set the textvariable to a variable. > > sure does, if you use the same internal variable for both widgets. After reading your post, I realized the reason why it doesn't replicate was because I set the variable to an empty string, which doesn't initialize the textvariable. -- http://mail.python.org/mailman/listinfo/python-list
disabling button
using tkinter i created a gui and put a button on the frame class mygui: def __init__(self, parent): ... self.okButton = Button(self.btnFrame) self.okButton.configure(width=somewdth,text="OK", anchor=W,disabledforeground="tan") self.okButton.bind("",self.button1Click) then in the buttonClick(self,event) i want to disable it till some time consuming calculations are completed ..then i enable it def button1Click(self, event): self.okButton.configure(state=DISABLED) print "ok disabled" somebigcalculations() self.okButton.configure(state=NORMAL) print "ok enabled" well,the button doesn't grey out when i click it ,though the print staements are executed.. but if some error happens and program exits with some ioerror(say errno2 file not found ..)then the button is shown as greyed out.. am i missing something here ? how can i get the button disabled and greyed out on clicking it? dn -- http://mail.python.org/mailman/listinfo/python-list
fiber(cooperative multi-threading)
Hi all. I found cooperative multi-threading(only one thread runs at once, explicit thread switching) is useful for writing some simulators. With it, I'm able to be free from annoying mutual exclusion, and make results deterministic. For this purpose, and inspired by Ruby(1.9) fiber, I wrote my own version of fiber in Python. It just works, but using native Python threads for non-preemptive threading is not cost-effective. Python has generator instead but it seemed to be very restricted for general scripting. I wish I could write nested (generator) functions easily at least. Is there any plan of implementing real (lightweight) fiber in Python? import threading class Fiber(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.semaphore_running = threading.Semaphore(0) self.semaphore_finish = None self.val = None self.setDaemon(True) self.start() self.start = self.start_fiber def start_fiber(self): self.semaphore_finish = threading.Semaphore(0) self.semaphore_running.release() self.semaphore_finish.acquire() def run(self): # override self.semaphore_running.acquire() self.main() if self.semaphore_finish is not None: self.semaphore_finish.release() def switchto(self, fiber, val=None): fiber.val = val fiber.semaphore_running.release() self.semaphore_running.acquire() return self.val def main(self): # should be overridden pass class F1(Fiber): def main(self): print "f1 start" self.switchto(f2) print "f1 foo" v = self.switchto(f2) print "f1 v=%s world" % v self.switchto(f2, "OK") print "f1 end" class F2(Fiber): def main(self): print "f2 start" self.switchto(f1) print "f2 bar" result = self.switchto(f1, "Hello, ") print "f2 result=%s" % result print "f2 end" self.switchto(f1) f1 = F1() f2 = F2() print "start" f1.start() print "end" -- kayama -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd behavior in Python/Tkinter?
Lie wrote: > But an expression (e.g. string) is NOT a variable. in this case, it is. I don't know if it's worth spending more time on this, since you're not listening, but let's make one more attempt. for the Entry widget, the "textvariable" argument, if given, identifies an *internal* Tkinter variable (managed by the embedded Tcl inter- preter, not Python). changes to this variable will be reflected in the widget, and changes to the widget will be reflected in the variable. the *usual* way to create such a variable is to use StringVar, and leave it to Tkinter to come up with an internal variable name, but you can refer to any Tcl variable; if it doesn't exist, it's created. in your example, you told both widgets to use the same internal variable. you can do the same thing with a StringVar: var = Tk.StringVar() e1 = Tk.Entry(root, textvariable = var) e2 = Tk.Entry(root, textvariable = var) doing this has the advantage that you can access the internal variable via the StringVar object (held in the Python variable named "var"), but at the Tkinter level, it's exactly the same thing. changes to the variable will be reflected in both widgets, and changes to *either* widget will be reflected in the variable, and therefore also in the other widget. > On the other hand, the oddness multiplied since the value replication > doesn't happen if I set the textvariable to a variable. sure does, if you use the same internal variable for both widgets. -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance on local constants?
On Sat, 22 Dec 2007 10:53:39 +, William McBrine wrote: > Hi all, > > I'm pretty new to Python (a little over a month). I was wondering -- is > something like this: > > s = re.compile('whatever') > > def t(whatnot): > return s.search(whatnot) > > for i in xrange(1000): > print t(something[i]) > > significantly faster than something like this: > > def t(whatnot): > s = re.compile('whatever') > return s.search(whatnot) > > for i in xrange(1000): > result = t(something[i]) > > ? Or is Python clever enough to see that the value of s will be the same > on every call, and thus only compile it once? Let's find out: >>> import re >>> import dis >>> >>> def spam(x): ... s = re.compile('nobody expects the Spanish Inquisition!') ... return s.search(x) ... >>> dis.dis(spam) 2 0 LOAD_GLOBAL 0 (re) 3 LOAD_ATTR1 (compile) 6 LOAD_CONST 1 ('nobody expects the Spanish Inquisition!') 9 CALL_FUNCTION1 12 STORE_FAST 1 (s) 3 15 LOAD_FAST1 (s) 18 LOAD_ATTR2 (search) 21 LOAD_FAST0 (x) 24 CALL_FUNCTION1 27 RETURN_VALUE No, the Python compiler doesn't know anything about regular expression objects, so it compiles a call to the RE engine which is executed every time the function is called. However, the re module keeps its own cache, so in fact the regular expression itself may only get compiled once regardless. Here's another approach that avoids the use of a global variable for the regular expression: >>> def spam2(x, s=re.compile('nobody expects the Spanish Inquisition!')): ... return s.search(x) ... >>> dis.dis(spam2) 2 0 LOAD_FAST1 (s) 3 LOAD_ATTR0 (search) 6 LOAD_FAST0 (x) 9 CALL_FUNCTION1 12 RETURN_VALUE What happens now is that the regex is compiled by the RE engine once, at Python-compile time, then stored as the default value for the argument s. If you don't supply another value for s when you call the function, the default regex is used. If you do, the over-ridden value is used instead: >>> spam2("nothing") >>> spam2("nothing", re.compile('thing')) <_sre.SRE_Match object at 0xb7c29c28> I suspect that this will be not only the fastest solution, but also the most flexible. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How to in Python
Chris Mellon wrote: > You don't seem to be implementing the > lexer in Python I am absolutely implementing my language in Python, a language I have now been writing for two entire weeks. This list has been more than helpful, tolerating numerous newbie questions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Bruno Desthuilliers wrote: > ... that's definitively not > something I'd store in global. So where would you put it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Hendrik van Rooyen wrote: > I wonder if you have some COBOL data divisions under your belt? Hendrik, I go way back but somehow I missed COBOL. Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance on local constants?
William McBrine <[EMAIL PROTECTED]> wrote: > Hi all, > > I'm pretty new to Python (a little over a month). I was wondering -- is > something like this: > > s = re.compile('whatever') > > def t(whatnot): > return s.search(whatnot) > > for i in xrange(1000): > print t(something[i]) > > significantly faster than something like this: > > def t(whatnot): > s = re.compile('whatever') > return s.search(whatnot) > > for i in xrange(1000): > result = t(something[i]) > > ? Or is Python clever enough to see that the value of s will be the same > on every call, and thus only compile it once? > The best way to answer these questions is always to try it out for yourself. Have a look at 'timeit.py' in the library: you can run it as a script to time simple things or import it from longer scripts. C:\Python25>python lib/timeit.py -s "import re;s=re.compile('whatnot')" "s.search('some long string containing a whatnot')" 100 loops, best of 3: 1.05 usec per loop C:\Python25>python lib/timeit.py -s "import re" "re.compile('whatnot').search('some long string containing a whatnot')" 10 loops, best of 3: 3.76 usec per loop C:\Python25>python lib/timeit.py -s "import re" "re.search('whatnot', 'some long string containing a whatnot')" 10 loops, best of 3: 3.98 usec per loop So it looks like it takes a couple of microseconds overhead if you don't pre-compile the regular expression. That could be significant if you have simple matches as above, or irrelevant if the match is complex and slow. You can also try measuring the compile time separately: C:\Python25>python lib/timeit.py -s "import re" "re.compile('whatnot')" 10 loops, best of 3: 2.36 usec per loop C:\Python25>python lib/timeit.py -s "import re" "re.compile('<(?:p|div)[^>]*>(?P(?:(?P\\]*\\>)\\]+class\\s*=[^=>]*captioned[^>]+\\>\\)|\\]+class\\s*=[^=>]*captioned[^>]+\\>)|(?P(?:(?P\\]*\\>)\\]+class\\s*=[^=>]*captioned[^>]+\\>\\)|\\]+class\\s*=[^=>]*captioned[^>]+\\>)')" 10 loops, best of 3: 2.34 usec per loop It makes no difference whether you use a trivial regular expression or a complex one: Python remembers (if I remember correctly) the last 100 expressions it compiled,so the compilation overhead will be pretty constant. -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance on local constants?
On Dec 22, 9:53 pm, William McBrine <[EMAIL PROTECTED]> wrote: > Hi all, > > I'm pretty new to Python (a little over a month). I was wondering -- is > something like this: > > s = re.compile('whatever') > > def t(whatnot): > return s.search(whatnot) > > for i in xrange(1000): > print t(something[i]) > > significantly faster than something like this: > > def t(whatnot): > s = re.compile('whatever') > return s.search(whatnot) > > for i in xrange(1000): > result = t(something[i]) > > ? No. Or is Python clever enough to see that the value of s will be the same > on every call, No. It doesn't have a crystal ball. > and thus only compile it once? But it is smart enough to maintain a cache, which achieves the desired result. Why don't you do some timings? While you're at it, try this: def t2(whatnot): return re.search('whatever', whatnot) and this: t3 = re.compile('whatever').search HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance on local constants?
On Dec 22, 10:53 am, William McBrine <[EMAIL PROTECTED]> wrote: > Hi all, > > I'm pretty new to Python (a little over a month). I was wondering -- is > something like this: > > s = re.compile('whatever') > > def t(whatnot): > return s.search(whatnot) > > for i in xrange(1000): > print t(something[i]) > > significantly faster than something like this: > > def t(whatnot): > s = re.compile('whatever') > return s.search(whatnot) > > for i in xrange(1000): > result = t(something[i]) > > ? Or is Python clever enough to see that the value of s will be the same > on every call, and thus only compile it once? > > -- > 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on Python RE's do have a cache but telling it to compile multiple times is going to take time. Best to do as the docs say and compile your RE's once before use if you can. The timeit module: http://www.diveintopython.org/performance_tuning/timeit.html will allow you to do your own timings. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd behavior in Python/Tkinter?
> But an expression (e.g. string) is NOT a variable. It's fine if the > value mirrored when I set the textvariable conf to the same variable, > but in this case I'm setting them to the same expression (e.g. string). On the other hand, the oddness multiplied since the value replication doesn't happen if I set the textvariable to a variable. So, why is it? A checkbox/optionbox value replication works if they're set to a variable (I don't know if they're set to an expression) but Entry's value replication works only if they're set to expression not variable. -- http://mail.python.org/mailman/listinfo/python-list