Leipzig Python User Group - Meeting, June 13, 2006, 8:00pm
= Leipzig Python User Group = Next Meeting Tuesday, June 13, 2006 --- We will meet on June 13 at 8:00 pm at the training center of Python Academy in Leipzig, Germany (http://www.python-academy.com/center/find.html). Stefan Schwarzer will give its presentation for the EuropPython 2006 titled Speed up your Python code. The talk will be in English. Food and soft drinks are provided. Please send a short confirmation mail to [EMAIL PROTECTED], so we can prepare appropriately. Everybody who uses Python, plans to do so or is interested in learning more about the language is encouraged to participate. While the meeting language will be mainly German, English speakers are very welcome. We will provide English interpretation if needed. Current information about the meetings can always be found at http://www.python-academy.com/user-group/index.html = Leipzig Python User Group = Stammtisch am 13.06.2006 - Wir treffen uns am 13.06.2006 um 20:00 Uhr wieder im im Schulungszentrum der Python Academy in Leipzig (http://www.python-academy.de/Schulungszentrum/anfahrt.html). Stefan Schwarzer wird seinen Vortrag für die EuroPython 2006 Anfang Juli in Genf mit dem Titel Speed up your Python code vorstellen. Die Vortragsprache wird diesmal Englisch sein. Wir werden aber in deutsch diskutieren und bei Bedarf Wichtiges auf deutsch wiederholen. Für das leibliche Wohl wird gesorgt. Wir bitten um kurze Anmeldung per e-mail an: [EMAIL PROTECTED] An den Treffen der Python Anwendergruppe kann jeder teilnehmen, der Interesse an Python hat, die Sprache bereits nutzt oder nutzen möchte. Die Arbeitssprachen des Treffens ist Deutsch. Englisch sprechende Python-Enthusiasten sind trotzdem herzlich eingeladen. Wir übersetzen gern. Aktuelle Informationen zu den Treffen sind immer unter http://www.python-academy.de/User-Group/index.html zu finden. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Python-Workshop in Leipzig, Germany, September 8, 2006
The following announcement is in German. Despite this we would like to post it here, because many German speaking Python users read this group/list. === Workshop Python im deutschsprachigen Raum === Am 8. September 2006 findet in Leipzig der Workshop Python im deutschsprachigen Raum statt. Der Workshop ist als Ergänzung zu den internationalen und europäischen Python-Zusammenkünften gedacht. Die Themenpalette der Vorträge ist sehr weit gefasst und soll alles einschließen, was mit Python im deutschsprachigen Raum zu tun hat. Eine ausführliche Beschreibung der Ziele des Workshops, der Workshop-Themen sowie Details zu Organisation und Anmeldung sind unter http://www.python-academy.de/workshophttp://www.python-academy.de/workshop nachzulesen. Vorträge können bis zum 15. Juli angemeldet werden. Dazu bitte eine Kurzfassung an [EMAIL PROTECTED] senden. Zu jedem Vortrag kann ein Artikel eingereicht werden, der in einem Proceedings-Band Ende des Jahres erscheinen wird. === Wichtige Termine === 15.07.2005 Vortragsanmeldung mit Kurzfassung 31.07.2006 Einladung und vollständiges Programm 15.08.2006 Letzter Termin für Frühbucherrabatt 08.09.2006 Workshop 15.09.2006 Letzter Termin für die Einreichung der publikationsfähigen Beiträge Dezember 2006 Veröffentlichung des Tagungsbandes === Bitte weitersagen === Der Workshop soll auch Leute ansprechen, die bisher nicht mit Python arbeiten. Wer mithelfen möchte den Workshop bekannt zu machen, kann einen Link auf http://www.python-academy.de/workshophttp://www.python-academy.de/workshop setzen. Auch außerhalb des Internets kann der Workshop durch den Flyer http://www.python-academy.de/download/workshop_call_for_papers.pdfhttp://www.python-academy.de/download/workshop_call_for_papers.pdf bekannt gemacht werden. Einfach doppelseitig ausdrucken oder kopieren und ein paar Exemplare am Schwarzen Brett von Universitäten, Firmen, Organisationen usw. aushängen. Wir freuen uns auf eine rege Teilnahme, Mike Müller Stefan Scharzer -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Writing to a certain line?
Tommy B [EMAIL PROTECTED] writes: I was wondering if there was a way to take a txt file and, while keeping most of it, replace only one line. See, I'd have a file like: .. Is there any easy way to do this? An easy way? If you know how many bytes in from the start of the file your desired changes are to be positioned, the utility of choice is the strange but wonderful dd for Unix, MSwindows, MSDOS, etc. That's its name: dd. Are you planning to execute a call to dd from within a python program? Of course, you are constrained to substituting N bytes with another N bytes, exactly. -- John Savage (my news address is not valid for email) -- http://mail.python.org/mailman/listinfo/python-list
Re: Extended zip() for lists
Hello Gene, a big THANKS for this tip. This is exactly what I was looking for. Regards Florian Reiser gene tani [EMAIL PROTECTED] schrieb im Newsbeitrag news:[EMAIL PROTECTED] Florian Reiser wrote: Hello, I have 4 lists: a, b, c and d Out of this 4 lists I want to build a table (e.g. list of lists): a|b|c|d --- a1|b1|c1|d1 a1|b2||d2 You see: the lists are not equally sized. Is there a command which fills up the shorter lists with blanks? Like an enhanced zip() command, maybe? map(None, list1, list2, list3) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410687 -- http://mail.python.org/mailman/listinfo/python-list
Re: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement)
Ilias Lazaridis wrote: crossposted to 5 groups, which are affected by this case. [some random ramblings about a troll being silenced for the moment] And your article has exactly what relationship to Perl? *PLONK* jue -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic inheritance
alf wrote: is there any way to tell the class the base class during runtime? a. Example: class A(object):pass class B(A):pass B.mro() [class '__main__.B', class '__main__.A', type 'object'] See also Micheles nice article about the semantics of the mro ( method resolution order). http://www.python.org/download/releases/2.3/mro/ Regards, Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing again and again
abcd wrote: If I have code which imports a module over and over again...say each time a function is called, does that cause Python to actually re-import it...or will it skip it once the module has been imported?? for example: def foo(): import bar bar.printStuff() foo() foo() foo() foo() ...will that re-import bar 4 times...or just import it once? is this a big performance hit? thanks To address the performance question, by the way, the first thing that the import process does is look in sys.modules to see whether the module has already been imported. If so then it uses the module referenced by sys.modules, so the overhead is pretty small (dicts being quite fast generally speaking). So your code is a reasonable way to defer the import of bar until the function is called, which is why I presumed you coded it that way. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
[EMAIL PROTECTED] wrote: Hello, Terry Reedy wrote: So I do not see any point or usefulness in saying that a tuple subcript is not what it is. I know that a tuple is *constructed*. The question is, is this, conceptually, the feature that allows you to ommit the parentheses of a tuple in some cases. If we see this as the same feature, it's reasonable that nothing won't be seen as an empty tuple, just like a = doesn't mean a = (). However, if we see this as a different feature, which allows multidimensional subscript by constructing a tuple behind the scenes, constructing an empty tuple for x[] seems very reasonable to me. Since in some cases you can't have the parentheses at all, I think that x[] makes sense. Hey, I have an idea, why don't we look at the language reference manual instead of imagining how we think it might work! In section 3.2 we find: Tuples The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a `singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses. So it seems that your speculation is false. Section 2.6 specifically defines [ and ] as delimiters. Section 5.3.2 defines a subscription (a term I've not really grown to love, but what the heck) as subscription ::= primary [ expression_list ] and section 5.12, which defines expression_list, explicitly says An expression list containing at least one comma yields a tuple.. So it would appear that while your change might be very convenient to allow you to refer to scalar values as zero-dimensional arrays, it doesn't really fit into Python's conceptual framework. Sorry. One further point: if you really do conceptualize scalars as zero-dimensional arrays, where is the value conceptually stored? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Error in Chain of Function calls
Hi, There is a code in my main function which is something like: while prunedFinal != []: prunedNew = genColocations(prunedK) *** tableInstancesNew = genTableInstances(prunedNew,tableInstancesK) tiCountDict = tiCount(tableInstancesNew) tiDict = findPI(tableInstancesNew) prunedFinal = pruneTI(tiDict,pi) rulesDict = genRules(prunedFinal) cpDict = findCP(rulesDict) prunedRulesList = pruneCP(cpDict,cp) prunedK = prunedFinal tableInstancesK = tableInstancesNew else: return prunedRulesList prunedK and tableInstancesK are defined in the main function. Before the main function, i have defined the other functions such as genColocations,genTableInstances,etc. Output of genColocations is to be given to the next function genTableInstances,output of this function to tiCount and findPI, and so on. However i am getting an error at the line marked with ***. Also,i am getting a ValueError in the code below: for s in prunedNew: substrings = [s[:i]+s[i+1:] for i in range(len(s))] for string in substrings: if string not in prunedK: prunedNew.remove(s) continue continue The error is: prunedNew.remove(s) ValueError: list.remove(x): x not in list Could anyone enlighten me as to why i'm getting these two errors?? Thanks a lot, girish -- http://mail.python.org/mailman/listinfo/python-list
Re: Win XP: Problem with shell scripting in Python
A.M wrote: It works very fine with DIR command, but for commands like MD : it doesn't return the error message into the string: print os.popen('MD :').read() # No error message in python, MD is spelled os.mkdir. Am I missing anything? the difference between STDOUT and STDERR, and the difference between buffered output and non-buffered output, and perhaps a few other things related to how STDIO behaves on modern computers... however, if you want to pretend that STDOUT and STDERR are the same thing, you can use os.popen4: o, i = os.popen4(md :) i.read() 'The filename, directory name, or volume label syntax is incorrect.\n' or the subprocess module. Considering the fact that Ruby doesn't have any problem with redirecting STDOUT into files or string variables, is Python the right tool for this kinds of shell scripting? rewriting BAT files as a series of os.system or os.popen calls isn't exactly optimal (neither for the computer nor the programmer nor the future user); better take an hour to skim the generic operating system services section in the library reference, and use built-in functions wherever you can: http://docs.python.org/lib/allos.html the following modules are especially useful: http://docs.python.org/lib/module-os.html http://docs.python.org/lib/module-os.path.html http://docs.python.org/lib/module-glob.html http://docs.python.org/lib/module-shutil.html by using the built-in tools, you get better performance in many cases, better error handling, and code that's a lot easier to reuse (also on non-Windows platforms). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Select hangs after some reads
Donn Cave wrote: In article [EMAIL PROTECTED], Steve Holden [EMAIL PROTECTED] wrote: The PSH flag indicates that the data stream must be flushed right through to the other end. This is essential for interactive protocols such as FTP: without it the server has no way to know that the client has sent a complete command, and vice versa. So you would expect to see this done explicitly in the source for an FTP client or server implementation -- something that sets this PSH flag or else the protocol won't work? Or am I misunderstanding what you mean? I don't see that specific string anywhere in a the particular FTP implementation whose source happened to be handy, basically a Berkeley 4.4 variant as I think most are on UNIX. Somewhere around here I have a pass-through FTP client/server application that adds GSSAPI-Kerberos5 authentication to the protocol traffic, and I don't remember needing to do any such thing there. I'd have to look harder at the details, but as I recall it, like any sane application the protocol is defined in terms of data, so you know if you have a complete command by looking at what you have. Nope, I wouldn't look any harder. You and I both know you won't find them. The client in this case was the client's transport layer, not the client application - I should have said sender, since I referred to the system at the other end as the receiver. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: better Python IDE? Mimics Maya's script editor?
warpcat wrote: I've been scripting in Maya, via mel for years now. Recently learning to Python, love it. Thing that's driving me nuts it the IDE. I'm using PythonWin right now and trying to find something better, mainly with this functionality: In Maya's mel script editor window, it's split into two sections. Bottom window you can enter commands (where your script lives), top window gives results. The thing I'm really used to is highlighting X# of lines in the bottom window (little snippits from my script), and executing that selection, with instant feedback of the results on top. This really speeds my workflow. It seems completely missing (so far) in Python's IDE. I have to copy and paste from a script to the ide window to execute and see the results, or I have to make a bunch of buffer scripts with just the code snippetsI want to test in. Seems *really* clunky. Does anyone know of a scripting enviroment for Python that mimics what Maya's script editor has? Much appreciated. I don't know of anything that exhibits the exact behaviour you describe, but then again you might like to consider that i found your request very odd. I'm sure that way of testing code seems entirely natural to you, but I can honestly say that in almost ten years using Python it's not something I have ever wished for. You might also wish to reconsider your approach to the Python community. PythonWin sucks isn't my idea of how to win friends and influence people in a first posting to a usenet newsgroup. By and large we are a friendly bunch here, but you don't want to start off on the wrong foot :-) Take a look at DrPython (http://drpython.sourceforge.net/) - you might be able to script it to do what you want, and anyway it's more of a lightweight interface than PythonWin so you might find it less intrusive. [Irrelevant ramble: Man, SoureceForge really know how to screw a web site up. I'm guessing they think that the changes of the last year are improvements. Boy are they wrong. What a mess!] regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Exeucte a system command in python script
[EMAIL PROTECTED] wrote: I am using python 2.4, so I don' t need to insteall that module separately. [EMAIL PROTECTED] wrote: Thanks I get this error 'NameError: global name 'call' is not defined I already import 'subprocess'. Can you pleaes tell me what am I missing? Among other things you are missing the traceback that the Python interpreter provides with its error messages. This will point you to a particular line of the source. If you include a few lines of the source around that point, as well as a pasted copy of the traceback, we have some chance to determine the error without overtaxing our psychic powers. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Class for Apache log analysis
And80 wrote: Hi all, I am looking for a python package that I could employ to analyze Apache's log files in real time. Of course I already have found some scripts, but most of them are outdated (python1.5), while others are simply impossible to use for a custom application. I was looking for something reliable, flexible and not to much outdated... Are you saying that a Python 1.5 script won't work on recent Pythons, or just that the scripts, being old, don't meet your requirements? The log file format is old enough that you might find the old scripts are fine. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
[EMAIL PROTECTED] wrote: Well, what do you think about this? -0 from me, but it's definitely a PEP-able proposal. suggestion: turn your post into a pre-PEP and post it somewhere, post the patch to the patch tracker, and post a brief heads-up to python-dev, and see what happens. (you probably have to do all that today if you want this to go into 2.5, though...) /F -- http://mail.python.org/mailman/listinfo/python-list
RE: better Python IDE? Mimics Maya's script editor?
[Steve Holden] | warpcat wrote: | In Maya's mel script editor window, it's split into two sections. | Bottom window you can enter commands (where your script lives), top | window gives results. The thing I'm really used to is | highlighting X# | of lines in the bottom window (little snippits from my script), and | executing that selection, with instant feedback of the | results on top. | This really speeds my workflow. | I don't know of anything that exhibits the exact behaviour | you describe, | but then again you might like to consider that i found your | request very | odd. I'm sure that way of testing code seems entirely natural to you, | but I can honestly say that in almost ten years using Python it's not | something I have ever wished for. I may have misread, but it sounds just like what Lightning does: https://sourceforge.net/project/showfiles.php?group_id=125834 Except that you enter snippets in the top window and the results appear in the bottom window. (Or, I think, even side-by-side according to some preference setting). Try it and see, perhaps. TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in Chain of Function calls
Girish Sahani wrote: However i am getting an error at the line marked with ***. what error ? Also,i am getting a ValueError in the code below: for s in prunedNew: substrings = [s[:i]+s[i+1:] for i in range(len(s))] for string in substrings: if string not in prunedK: prunedNew.remove(s) continue continue The error is: prunedNew.remove(s) ValueError: list.remove(x): x not in list the ValueError means exactly what it says -- have you verified that the value of s really is present in the list? did you really mean to remove s and not, say, string ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Select hangs after some reads
Steve Holden wrote: Nope, I wouldn't look any harder. You and I both know you won't find them. The client in this case was the client's transport layer, not the client application - I should have said sender, since I referred to the system at the other end as the receiver. you know that it's a terminology issue when three experienced developers reply well, it already does that, you cannot do that, and I don't understand what you mean to the same question. (if you're playing Who Wants To Be A Millionaire, this is the right time to take the money and quit...) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic inheritance
alf wrote: is there any way to tell the class the base class during runtime? Technically, yes - the solution depending on your definition of during runtime FWIW, the class statement is evaled at import/load time, which is during runtime So if you want to use one or other (compatible) classes depending on configuration or system or like, you can use a conditionnal at the top level, *before* the class statement is eval'd. ie: import os if os.name == 'posix': import posixmodule as basemodule elif os.name == 'nt': import ntmodule as basemodule # etc... class MyClass(basemodule.baseclass): # class def here If you want to dynamically change the base class (or one of the base classes) during execution (ie: after the class statement has been eval'd), read Kay Schluehr's answer. *But* you'd probably better tell us about the problem you're trying to solve. Since in Python, inheritance is mostly about implementation (ie: not needed for subtyping), your problem would probably be best solved with composition/delegation, for which Python offers a good support: class MyClass(object): def __init__(self, delegate): self._delegate = delegate def __getattr__(self, name): return getattr(self._delegate, name) or, if you don't want to explicitely pass the delegate at instanciation time: import os if os.name == 'posix': import posixmodule as basemodule elif os.name == 'nt': import ntmodule as basemodule # etc... class MyClass(object): _delegate_class = basemodule.SomeClass def __init__(self): self._delegate = self._delegate_class() # etc there are of course some variants of the above solutions, but one can't tell you which one to use without knowing more about your actual problem. HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate k+1 length strings from a list of k length strings?
[EMAIL PROTECTED] wrote: Boris Borcic: I challenge you to write simpler code to do the equivalent. context ? I don't do challenges. Pfff... and you don't do real debates either. I too have written the code to solve that problem, Why ? When ? -- http://mail.python.org/mailman/listinfo/python-list
Re: tracking dependencies
Dennis Benzinger wrote: I've never tried it, but http://www.tarind.com/depgraph.html looks like what you are looking for. This is EXACTLY what I had in mind :-) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in Chain of Function calls
Girish Sahani wrote: Hi, There is a code in my main function which is something like: while prunedFinal != []: prunedNew = genColocations(prunedK) *** tableInstancesNew = genTableInstances(prunedNew,tableInstancesK) tiCountDict = tiCount(tableInstancesNew) tiDict = findPI(tableInstancesNew) prunedFinal = pruneTI(tiDict,pi) rulesDict = genRules(prunedFinal) cpDict = findCP(rulesDict) prunedRulesList = pruneCP(cpDict,cp) prunedK = prunedFinal tableInstancesK = tableInstancesNew else: return prunedRulesList prunedK and tableInstancesK are defined in the main function. defined as what ? functions, strings, lists, classes, ... ? Before the main function, i have defined the other functions such as genColocations,genTableInstances,etc. Output of genColocations is to be given to the next function genTableInstances,output of this function to tiCount and findPI, and so on. However i am getting an error at the line marked with ***. Which error ? How do you hope us to be of any help here if you don't *at least* provide the full traceback ? FWIW, the canonical way to do things is to: - provide minimal *runnable* code exposing the problem - explain what you hoped to get - explain what you got instead (including full traceback) As a matter of fact, it's often the case that one solves the problem when working on the first point !-) (snip) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing again and again
Le Jeudi 08 Juin 2006 22:02, abcd a écrit : def foo(): import bar bar.printStuff() foo() foo() foo() foo() ...will that re-import bar 4 times...or just import it once? is this a big performance hit? Import a module more than once doesn't execute the code of this module more than once. I don't know what's your need but as some have spoke of reload I just want to warn you, reload a module means that you want invalidate the code of this and replace it by a new one, this is not like a normal but deeper import. Also, you'll have to deal yourself wiith references to your old code. Hmmm, the following example should be clear than my explanations :) n [1]: import temp In [2]: class a(temp.Base temp.Base In [2]: class a(temp.Base temp.Base In [2]: class a(temp.Base temp.Base In [2]: class a(temp.Base) : pass ...: In [3]: reload(temp) Out[3]: module 'temp' from 'temp.pyc' In [4]: class b(temp.Base) : pass ...: In [7]: b.__base__, a.__base__, b.__base__ is a.__base__ Out[7]: (class 'temp.Base', class 'temp.Base', False) In [8]: isinstance(a(), temp.Base), isinstance(b(), temp.Base) Out[8]: (False, True) -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
Re: what are you using python language for?
baalbek wrote: To score with the chicks! A Python script roams the nightclubs for beautiful women, finds an appropriate woman based on my preferances, charms her with its sleek Pythonic manners, calls for a cab and brings the lady to my recidency. Works like a charm! Is that OSS ?-) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate k+1 length strings from a list of k length strings?
Boris Borcic: I don't do challenges. Pfff... and you don't do real debates either. Different nations have different values and different cultures, in mine challenges are often seen as things for children, and a waste of time for adults (probably in USA challenges are appreciated more). Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Python to be used to build OLPC apps
The $100 laptop from MIT will be providing Python for application developers to use. This laptop is a low-power consumption innovative laptop that includes features like: - low-power wi-fi with longer than normal range and the ability to keep communicating after the CPU has been put to sleep. - color LCD screen that can be switched to an extra-low power reflective monochrome mode for reading ebooks. - limited memory, flash storage and no hard drive like a PDA - several USB ports - accepts DC input voltages from 5 to 25 volts to recharge battery - ships with a hand-crank power generator The table of contents of their wiki is the best place to learn more: http://wiki.laptop.org/index.php/Table_of_Contents Other key pages are http://wiki.laptop.org/index.php/OLPC_Python_Environment and http://wiki.laptop.org/index.php/Sugar -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The question is, is this, conceptually, the feature that allows you to ommit the parentheses of a tuple in some cases. To repeat: tuples are defined by commas. There are no 'parentheses of a tuple', except for empty tuples, to be omitted. Consider: a+b is a sum; in (a+b)*c, the sum is parenthesized to avoid confusion with a+b*c. Like other expressions, tuples are parenthesezed when needed to avoid similar confusion. So (1,2)+(3,4) needs parens because 1,2+3,4 would be something different. In both examples, parens are used to reverse normal precedence relations. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Steve Holden wrote: Hey, I have an idea, why don't we look at the language reference manual instead of imagining how we think it might work! I don't know. Sounds risky. In section 3.2 we find: Tuples The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a `singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses. So it seems that your speculation is false. Section 2.6 specifically defines [ and ] as delimiters. Section 5.3.2 defines a subscription (a term I've not really grown to love, but what the heck) as subscription ::= primary [ expression_list ] and section 5.12, which defines expression_list, explicitly says An expression list containing at least one comma yields a tuple.. So it would appear that while your change might be very convenient to allow you to refer to scalar values as zero-dimensional arrays, it doesn't really fit into Python's conceptual framework. Sorry. Yes, that would appear to be so. You would have a point... if the documentation were correct. Only it's not. According to the reference manual, the rule for an expression_list is: expression_list ::= expression ( , expression )* [,] But take the following legal Python subscripted array: a[1:2,...,3:4] Is 1:2 an expression? How about ...? When I enter 1:2 at the Python prompt, I get a syntax error. The fact is, the documentation here is either wrong or simplified or both. (I don't think it's a big deal, actually: the real grammar has lots of complexity to handle tricky cases that would needlessly complicate the reference manual for a human reader.) So let's look at an excerpt the actual Python grammar (from 2.4.3). You'll be happy to know subscription isn't used. :) trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] sliceop: ':' [test] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] testlist: test (',' test)* [','] Clearly, the grammar rule used for list subscript is different from the one used for list of expressions (for some reason, what an ordinary person would call an expression is called a test in the grammar, whereas expr is a non-short-circuiting expression). So there's a regular way to create non-empty tuples, and a subscript way. And there's a regular way to create an empty tuple... but not a subscript way. So I'd say this change fits the conceptual framework of the tuple quite well; in fact, it makes subscript tuples more parallel to their regular counterparts. One further point: if you really do conceptualize scalars as zero-dimensional arrays, where is the value conceptually stored? Think of it this way: an array with n-dimensions of length 3 would have 3**n total entries. How many entries would a 0-dimensional array have? 3**0 == 1. Numeric has had zero-dimensional arrays for a long time, and has had no problem storing them. Think of the rule for accessing an element of an array: it's a base pointer + sum (indices*stride) for all indices. Now generalize it down to zero: there are no indices, so the scalar is stored at the base pointer. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate k+1 length strings from a list of k length strings?
[EMAIL PROTECTED] wrote: Boris Borcic: I don't do challenges. Pfff... and you don't do real debates either. Different nations have different values and different cultures, in mine challenges are often seen as things for children, and a waste of time for adults (probably in USA challenges are appreciated more). (1) This is becoming very ridiculous. What do the USA have to do with it ? (2) Different nations have different languages, and a good rule of thumb when debating with someone of unknown linguistic origins is not to focus on the connotations you percieve to a single word you abstract from its context. (3) Different intellectual communities have different values, in mine it is the rule not to make abstract claims if not ready to put them to experimental test - and it's less a matter of (passing or failing) tests than a matter of making clear the rule of translation between one's own abstract language and objective facts. And by these means, ultimately, to measure the divergence in languages. (4) As concerns the matter of the case, you made broad and abstract claims while implicitely referring to some doctrine(s), and I concisely formulated the demand that you back them up with (according to you) observable facts. I note that instead you chose to articulate your doctrine while avoiding an occasion to probe its adequacy. (5) I find your systematic enrollment of children to your cause quite inappropriate. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: better Python IDE? Mimics Maya's script editor?
warpcat wrote: I've been scripting in Maya, via mel for years now. Recently learning to Python, love it. Thing that's driving me nuts it the IDE. http://wiki.python.org/moin/IntegratedDevelopmentEnvironments -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate k+1 length strings from a list of k length strings?
[EMAIL PROTECTED] wrote: It's not that difficult to improve the readability of a quite long line, you can start splitting it. The point is that it is observer and context dependent whether res = set(''.join(sorted(X|Y)) for X in sets for Y in sets if len(X^Y)==2) is measurably easier to read than res = set(''.join(sorted(X|Y)) for X in sets for Y in sets if len(X^Y)==2) *and* that I acknowledged it by writing I find most readable while you denied it by speaking of the readability - and similar language. -- http://mail.python.org/mailman/listinfo/python-list
Amazon and Webservices
Hi All I've been trying to consume the webservices at Amazon using python. I have not been able to find a *good* webservices module and I've had a look at SOAPpy, etc. Yes I have googled etc, but there seems to be a lack of development in this space apart for one or two projects. Does anyone have a working webservices implementation (not pyamazon) ? /vpr -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Carl Banks wrote: Steve Holden wrote: Hey, I have an idea, why don't we look at the language reference manual instead of imagining how we think it might work! I don't know. Sounds risky. In section 3.2 we find: Tuples The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a `singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses. So it seems that your speculation is false. Section 2.6 specifically defines [ and ] as delimiters. Section 5.3.2 defines a subscription (a term I've not really grown to love, but what the heck) as subscription ::= primary [ expression_list ] and section 5.12, which defines expression_list, explicitly says An expression list containing at least one comma yields a tuple.. So it would appear that while your change might be very convenient to allow you to refer to scalar values as zero-dimensional arrays, it doesn't really fit into Python's conceptual framework. Sorry. Yes, that would appear to be so. You would have a point... if the documentation were correct. Only it's not. According to the reference manual, the rule for an expression_list is: expression_list ::= expression ( , expression )* [,] But take the following legal Python subscripted array: a[1:2,...,3:4] But the element inside the brackets there isn't an expression-list, it's a slicing (see section 5.3.2). Is 1:2 an expression? How about ...? When I enter 1:2 at the 1:2 is a short slice. ... is an ellipsis. Neither of these elements are allowed in non-subscripting contexts. Python prompt, I get a syntax error. The fact is, the documentation here is either wrong or simplified or both. (I don't think it's a big deal, actually: the real grammar has lots of complexity to handle tricky cases that would needlessly complicate the reference manual for a human reader.) So let's look at an excerpt the actual Python grammar (from 2.4.3). You'll be happy to know subscription isn't used. :) trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] sliceop: ':' [test] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] testlist: test (',' test)* [','] The simplification of the grammar is explicitly documented: Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice nor ellipses). Similarly, when the slice list has exactly one short slice and no trailing comma, the interpretation as a simple slicing takes priority over that as an extended slicing. Clearly, the grammar rule used for list subscript is different from the one used for list of expressions (for some reason, what an ordinary person would call an expression is called a test in the grammar, whereas expr is a non-short-circuiting expression). So there's a regular way to create non-empty tuples, and a subscript way. And there's a regular way to create an empty tuple... but not a subscript way. So I'd say this change fits the conceptual framework of the tuple quite well; in fact, it makes subscript tuples more parallel to their regular counterparts. Although this debate is beginning to make me sound like one, I am really not a language lawyer. However, I should point out that what you are describing as a tuple should more correctly be described as a slice-list once you include slices or an ellipsis as elements. Slicings are described, as I am fairly sure you know, in section 5.3.3. One further point: if you really do conceptualize scalars as zero-dimensional arrays, where is the value conceptually stored? Think of it this way: an array with n-dimensions of length 3 would have 3**n total entries. How many entries would a 0-dimensional array have? 3**0 == 1. Numeric has had zero-dimensional arrays for a long time, and has had no problem storing them. Think of the rule for accessing an element of an array: it's a base pointer + sum (indices*stride) for all indices. Now generalize it down to zero: there are no indices, so the scalar is stored at the base pointer. I can see that, and it doesn't seem unreasonable. Fortunately your persistence has goaded me into determining the point that *did* seem unreasonable to me: you were falsely trying to equate slicings and tuples. Having said all of which, there probably *is* a case for proposing that an empty slicing become syntactically acceptable, so why not write the PEP and go for it? But be quick: feature freeze for 2.5b1 looms ... regards Steve -- Steve Holden +44 150 684
Re: Large Dictionaries
Tim Peters wrote: shellsort is much more a refinement of insertion-sort than of bubblesort, but is not an O(N log N) algorithm regardlesss. With a judiciously chosen increment sequence, the number of comparisons made by shellsort *is* of the order N log N for practical values of N. See Figure 8 in http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate k+1 length strings from a list of k lengthstrings?
Girish Sahani schrieb: Yes it is the former of course.Common elements could be in any order in both strings. Thanks Marc :)...though we need to add an if for checking the length of the string (k+1). No, why? Every character from string1 is removed from string2 at most once. And string2 is added to string1 if and only if it has length 1; if not, string1 is set to the empty string. So either string1 is empty or it has length k+1. Or did you mean checking if string1 is empty? -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg e-mail : [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Amazon and Webservices
vpr I've been trying to consume the webservices at Amazon using python. vpr I have not been able to find a *good* webservices module... pyamazon. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Instead of saving text files i need as html
Tim Chase [EMAIL PROTECTED] wrote: [ ... ] urllib.urlretrieve(lines.strip('/n'), 'c:\\temp\\' \ + outfilename.strip('\n')[7:] + '.html') [ ... ] I'm not sure what the odd slicing is for, but I'll presume the OP knows what they're doing. It's taking the http://; off the front of the URL. len(http://;) 7 -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | Frankly I have no feelings towards penguins one way or the other \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Sybren Stuvel wrote: Just curious: how would you initialize 'x' in such a case? If I simply say 'x = []' and then try to index it with x[1, 2], I get TypeError: list indices must be integers. that's up to the x implementation to decide, of course: class MyContainer: ... def __getitem__(self, index): ... return index ... x = MyContainer() x[1] 1 x[1, 2] (1, 2) x[(1, 2, 3)] (1, 2, 3) x[()] () noam's proposal is to make this work: x[] () (but should it really result in an empty tuple? wouldn't None be a bit more Pythonic?) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate k+1 length strings from a list of k length strings?
Hum, since your code is not syntactically correct, anything will run faster :) in fact it parses, I was fooled by this line if k in range(1,len(prunedK),1) i+k = len(prunedK) -1: I was fooled because the form k in range( tends to imply a for statement ; in the case of an if statement, one usually uses chained comparisons instead. If you know i=0 and i,k are integers (as is implied by context), you could simply write something like: if 0 k i+k len(prunedK) : in the contrary case, assuming your line does what you want, you should really write it as if 1 = k len(prunedK) and i+k = len(prunedK)-1 : or more concisely if 1 = k len(prunedK) = i+k+1 : or even if i+k len(prunedK) k 0 : -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in Chain of Function calls
Girish Sahani wrote: However i am getting an error at the line marked with ***. what error ? ...line 266, in colocationMiner prunedNew = genColocations(prunedK) genColocations is a function defined before which returns prunedNew. Also,i am getting a ValueError in the code below: for s in prunedNew: substrings = [s[:i]+s[i+1:] for i in range(len(s))] for string in substrings: if string not in prunedK: prunedNew.remove(s) continue continue The error is: prunedNew.remove(s) ValueError: list.remove(x): x not in list the ValueError means exactly what it says -- have you verified that the value of s really is present in the list? did you really mean to remove s and not, say, string ? Yes. I want to remove s from the prunedNew list if that condition is not satisfied. /F -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Large Dictionaries
Marcin Ciura wrote: Tim Peters wrote: shellsort is much more a refinement of insertion-sort than of bubblesort, but is not an O(N log N) algorithm regardlesss. With a judiciously chosen increment sequence, the number of comparisons made by shellsort *is* of the order N log N for practical values of N. See Figure 8 in http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf That isn't what the reference says. It only covers N up to a few thousand. Practical values of N need to at least go up into the millions. Read the summary: Using sequential analysis, the search for optimal increment sequences for Shellsort was accelerated enough to find them for arrays up to several thousand elements. ... However, the sequences obtained so far are too short to draw a reliable conclusion whether an appropriate sequence of increments can make Shellsort a O(N logN) sorting method on the average. Some hypotheses may be possible when the sequences are prolonged to sort arrays of about 10^5 elements. -- http://mail.python.org/mailman/listinfo/python-list
Re: Win XP: Problem with shell scripting in Python
Fredrik Lundh [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] A.M wrote: in python, MD is spelled os.mkdir. Am I missing anything? the difference between STDOUT and STDERR, and the difference between buffered output and non-buffered output, and perhaps a few other things related to how STDIO behaves on modern computers... however, if you want to pretend that STDOUT and STDERR are the same thing, you can use os.popen4: o, i = os.popen4(md :) i.read() 'The filename, directory name, or volume label syntax is incorrect.\n' or the subprocess module. Considering the fact that Ruby doesn't have any problem with redirecting STDOUT into files or string variables, is Python the right tool for this kinds of shell scripting? rewriting BAT files as a series of os.system or os.popen calls isn't exactly optimal (neither for the computer nor the programmer nor the future user); better take an hour to skim the generic operating system services section in the library reference, and use built-in functions wherever you can: http://docs.python.org/lib/allos.html the following modules are especially useful: http://docs.python.org/lib/module-os.html http://docs.python.org/lib/module-os.path.html http://docs.python.org/lib/module-glob.html http://docs.python.org/lib/module-shutil.html by using the built-in tools, you get better performance in many cases, better error handling, and code that's a lot easier to reuse (also on non-Windows platforms). /F Thanks Fredrik for help. The MD : is just a sample. The actual script contains different commands. The actual script that I am translating consolidates huge table data from multiple SQL Server database into Oracle. I have to use BCP command line at the SQL server side and SQL*Loader at the Oracle side. I must capture the stdout/stderr output of command lines into log files for future inspection/troubleshooting. Beside the issue with stdout/stderror, the main stressful problem that I have is the fact that Python captures command line's output somehow differently. For example, popen captures BCP's command output completely wrong. Some part of summary is at the top and the progress percentages are at the bottom and more.! This is just stdout output. I am going to investigate other popen4 and other popen forms per your suggestion and try to fix the stdout sequence problem. Regards, Alan -- http://mail.python.org/mailman/listinfo/python-list
Writing PNG with pure Python
Just in case anybody has the same problem, here's my first attempt at implementing a subset of the PNG spec in pure Python. I license it to you under the terms of the GNU GPL. http://trac.browsershots.org/browser/trunk/shotfactory/lib/image/png.py It encodes RGB images with 24 bits per pixel into PNG, using only the modules sys, zlib and struct. These are all included in the base distribution of Python. You don't need gd or imlib. I have done a little testing, and my implementation processes 8 megs of RGB input in 0.6 seconds. With Adam7 interlacing enabled, it takes 10 times longer. I would really appreciate any feedback and suggestions for improvement. Cheers, Johann -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in Chain of Function calls
Girish Sahani wrote: what error ? ...line 266, in colocationMiner prunedNew = genColocations(prunedK) genColocations is a function defined before which returns prunedNew. that's a line of code, not an error. please include the entire traceback, or at least the actual error message. also see: http://pyfaq.infogami.com/tutor-i-need-help-im-getting-an-error-in-my-program-what-should-i-do The error is: prunedNew.remove(s) ValueError: list.remove(x): x not in list the ValueError means exactly what it says -- have you verified that the value of s really is present in the list? did you really mean to remove s and not, say, string ? Yes. I want to remove s from the prunedNew list if that condition is not satisfied. are the item you want to remove in the list? if you cannot be sure of that when you call remove, you need to check first (or catch the exception). i.e. if s in prunedNew: prunedNew.remove(s) or try: prunedNew.remove(s) # remove, if present except ValueError: pass # ignore error if not present /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in Chain of Function calls
Girish Sahani wrote: Also,i am getting a ValueError in the code below: for s in prunedNew: substrings = [s[:i]+s[i+1:] for i in range(len(s))] for string in substrings: if string not in prunedK: prunedNew.remove(s) continue continue The error is: prunedNew.remove(s) ValueError: list.remove(x): x not in list Could anyone enlighten me as to why i'm getting these two errors?? Why don't you use sets instead of lists ? It would make your life much easier. Specifically here, the problem seems to be that for some s there is more than one substring of it that fails to be in prunedK, so that the failing line is called more than once for a single s. The simplest modification is to replace your first 'continue' by a 'break' (and remove the second 'continue' which serves no purpose). -- http://mail.python.org/mailman/listinfo/python-list
Short questions wrt Python Unicode
Hi all, I've been reading about unicode in general and using it in Python in particular lately as this turns out to be not so straightforward actually. I wanted to aks two questions: 1) I'm writing a program that interacts with the user through wxPython (unicode build) and stores retrieves data using PySQLite. As fas as I know now, both packages are capable of handling Python unicode objects (wxPython returns the values of text controls etc. by default as Python unicode objects and TEXT columns in PySQLite have unicode entries) and since of course both interface with me through Python unicode objects I should be able to use each others generated unicode objects without any fear in each other functions, right?? 2) How do I get a representation of a unic. object in terms of Unicode code points? repr() doesn't do that, it sometimes parses or encodes the code points right: s=u\u0040\u0166\u00e6 s u'@\u0166\xe6' (does this latter \xe6 have to do with the internal representation of unic. objects, maybe with this UCS-2 encoding?) Thanks in advance! - Kees -- http://mail.python.org/mailman/listinfo/python-list
Re: Large Dictionaries
Duncan Booth wrote: Marcin Ciura wrote: See Figure 8 in http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf That isn't what the reference says. It only covers N up to a few thousand. Practical values of N need to at least go up into the millions. Please look at the performance graph of Tokuda's increment sequence. You can see that it scales pretty well at least up to 100 million. Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: Win XP: Problem with shell scripting in Python
A.M wrote: Fredrik Lundh [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] A.M wrote: in python, MD is spelled os.mkdir. Am I missing anything? the difference between STDOUT and STDERR, and the difference between buffered output and non-buffered output, and perhaps a few other things related to how STDIO behaves on modern computers... however, if you want to pretend that STDOUT and STDERR are the same thing, you can use os.popen4: o, i = os.popen4(md :) i.read() 'The filename, directory name, or volume label syntax is incorrect.\n' or the subprocess module. Considering the fact that Ruby doesn't have any problem with redirecting STDOUT into files or string variables, is Python the right tool for this kinds of shell scripting? rewriting BAT files as a series of os.system or os.popen calls isn't exactly optimal (neither for the computer nor the programmer nor the future user); better take an hour to skim the generic operating system services section in the library reference, and use built-in functions wherever you can: http://docs.python.org/lib/allos.html the following modules are especially useful: http://docs.python.org/lib/module-os.html http://docs.python.org/lib/module-os.path.html http://docs.python.org/lib/module-glob.html http://docs.python.org/lib/module-shutil.html by using the built-in tools, you get better performance in many cases, better error handling, and code that's a lot easier to reuse (also on non-Windows platforms). /F Thanks Fredrik for help. The MD : is just a sample. The actual script contains different commands. The actual script that I am translating consolidates huge table data from multiple SQL Server database into Oracle. I have to use BCP command line at the SQL server side and SQL*Loader at the Oracle side. I must capture the stdout/stderr output of command lines into log files for future inspection/troubleshooting. Beside the issue with stdout/stderror, the main stressful problem that I have is the fact that Python captures command line's output somehow differently. For example, popen captures BCP's command output completely wrong. Some part of summary is at the top and the progress percentages are at the bottom and more.! This is just stdout output. I am going to investigate other popen4 and other popen forms per your suggestion and try to fix the stdout sequence problem. I dare hardly suggest this, but might it not be better to use Python's database functionality to perform the task? The language can access both databases, and you might find it quicker. Then again, if your database experience is limited, you may not ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
How to link foreign keys primary keys using python?
Hi all, I hv started with python just recently... and have been assigned to make an utility which would be used for data validations... In short we take up various comma separated data files for eg: area.txt, school.txt, students.txt and so on (ok?!?) now, 1. area code used in the school.txt must be defined in the area.txt (Primary key in area = area_code defined in area.txt Foreign key on school = area_code defined in school.txt) i hv created primary key using the following piece of code: # primary key for area.txt (index created on the column AREACODE as per the # schema defined earlier ) area_pk = PartitionedPK( name = 'Area PK ', save_to = '../Index/area_code.idx', fields = ['A_AREACODE'] ) # col name in area schema # foreign key is defined as follows... school_fk = HashedFK( name = ' School code FK', load_from = '../Index/area_code.idx', fields= ['S_AREACODE'] ) # col name in school schema Description for abv code: 1. An index {area_code.idx } is formed on the field AREACODE in the area.txt (i.e.,A_AREACODE) 2. The data values in the S_AREACODE field in the school.txt are checked in the index {area_code.idx} If the area code given in school.txt is not present in the area code, then the record is not validated(as foreign key constraint fails.) Now if the Primary key is on mutiple columns...the foreign key, which is also definedon the same no. of columns works.. for eg.. # primary key for school.txt (index created on the columns AREACODE SCHOOLCODE as per the # schema defined earlier ) school_pk = PartitionedPK( name = 'School PK ', save_to = '../Index/school.idx', fields = ['S_AREACODE','S_SCHOOLCODE'] ) # col names in school schema # foreign key for students is defined as follows... student_fk = HashedFK( name = ' STUDENT code FK', load_from = '../Index/student.idx', fields= ['STUD_AREACODE','STUD_SCHOOLCODE'] ) # col name in student schema Now if I hv to define foreign key on student.txt but with only one field, school code, so as to make sure that the school name given in the student.txt exists in the school.txt whatever be the area code... I am unable to do this... Say, if the AREACODE field is not present in the student.txt file then??? I tried using the foll code student_fk = HashedFK( name = ' Student FK', load_from = '../Index/school.idx', fields= ['STUD_SCHOOLCODE'] ) Its showing an AttributeError : 'list' object has no attribute 'has_key' I also tried making another index with only SCHOOLCODE field (another PK for school.txt) and the foreign key on student.txt to be loaded from this index... it still shows the same error That's may be becoz... one SCHOOLCODE may repeat often, with a different AREACODE... so may be we need to index on distinct SCHOOLCODES in school.txt... how do i do that?? I hope i am not confusing the genious' ... plz help me... till get my hands on python... :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in Chain of Function calls
Girish Sahani wrote: Girish Sahani wrote: However i am getting an error at the line marked with ***. what error ? ...line 266, in colocationMiner Great. We now know at which line of an unknown file an unknown error happens. Will use my PythonPsychicPowers(tm) now to see waht's there... Also,i am getting a ValueError in the code below: (snip) The error is: prunedNew.remove(s) ValueError: list.remove(x): x not in list the ValueError means exactly what it says -- have you verified that the value of s really is present in the list? did you really mean to remove s and not, say, string ? Yes. I want to remove s from the prunedNew list if that condition is not satisfied. Anyway the error message is very clear : you're trying to remove a non-existant item from a list. Don't try to remove non-existent items, and you'll be fine. Hint 1 : in-place modifying a list you're iterating upon is a sure way to get into trouble Hint 2 : once you removed an item from that list, you shouldn't have to worry about deciding once again if you need to remove it... -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Large Dictionaries
Marcin Ciura wrote: Duncan Booth wrote: Marcin Ciura wrote: See Figure 8 in http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf That isn't what the reference says. It only covers N up to a few thousand. Practical values of N need to at least go up into the millions. Please look at the performance graph of Tokuda's increment sequence. You can see that it scales pretty well at least up to 100 million. Ah sorry, I misread it. It was sequences with several thousand elements, which corresponds to N of 100 million. -- http://mail.python.org/mailman/listinfo/python-list
Re: Short questions wrt Python Unicode
On 9/06/2006 10:04 PM, KvS wrote: 2) How do I get a representation of a unic. object in terms of Unicode code points? repr() doesn't do that, it sometimes parses or encodes the code points right: | s=u\u0040\u0166\u00e6 | s u'@\u0166\xe6' | ' '.join('U+%04X % ord(c) for c in s) 'U+0040 U+0166 U+00E6' If you'd prefer it more Pythonic than unicode.orgic, adjust the format string and separator to suit your taste. (does this latter \xe6 have to do with the internal representation of unic. objects, maybe with this UCS-2 encoding?) | u'\xe6' == u'\u00e6' == unichr(0xe6) True | hex(ord(u'\u00e6')) '0xe6' U+nn is represented internally as the integer 0xnn -- except if it won't fit, but you can pretend that surrogate pairs don't exist, for the moment :-) Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Hello, Sybren Stuvel wrote: I think it's ugly to begin with. In math, one would write simply 'x' to denote an unsubscribed (ubsubscripted?) 'x'. And another point, why would one call __getitem__ without an item to call? I think that in this case, mathematical notation is different from python concepts. If I create a zero-dimensional array, with the value 5, like this: a = array(5) I refer to the array object as a, and to the int it stores as a[]. For example, I can change the value it holds by writing a[] = 8 Writing a = 8 would have a completely different meaning - create a new name, a, pointing at a new int, 8. Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: wddx problem with entities
Tim Arnold [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I'm confused about why I get this error: UnicodeError: ASCII encoding error: ordinal not in range(128) when I try to load a wddx file containing this string: stringThe image file, gif/aper#231;u.png, does not exist./string When I loop through the file as if it's text and check the ord() value of each character, of course it's clean. Do I have to replace numbered entities in the wddx file before I can wddx.load() it? thanks! --tim example program: --- from xml.marshal import wddx datastring = '''?xml version=1.0? !DOCTYPE wddxPacket SYSTEM wddx_0090.dtd wddxPacket version=0.9 header/ datastruct stringThe image file, gif/aper#231;u.png,does not exist./string /struct/data/wddxPacket''' data = wddx.loads(datastring) Replying to my own post. I got around this problem, which *looks* like a bug to me, (although I'm sure I don't understand the internals of xml.marshal) with this: self.data = wddx.loads(''.join(codecs.open(self.filename, errors='ignore',encoding='ascii').readlines())) where self.filename contains the numbered entity. just in case anyone else out there is using wddx to communicate between python and php. --Tim Arnold -- http://mail.python.org/mailman/listinfo/python-list
Re: Short questions wrt Python Unicode
KvS wrote: s=u\u0040\u0166\u00e6 s u'@\u0166\xe6' (does this latter \xe6 have to do with the internal representation of unic. objects, maybe with this UCS-2 encoding?) no, it's simply the shortest way to represent U+00E6 as Python Unicode string literal, when limited to ASCII only. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Hello, Fredrik Lundh wrote: (but should it really result in an empty tuple? wouldn't None be a bit more Pythonic?) I don't think it would. First of all, x[()] already has the desired meaning in numpy. But I think it's the right thing - if you think of what's inside the brackets as a list of subscripts, one for each dimension, which is translated to a call to __getitem__ or __setitem__ with a tuple of objects representing the subscripts, then an empty tuple is what you want to represent no subscripts. Of course, one item without a comma doesn't make a tuple, but I see this as the special case - just like parentheses with any number of commas are interpreted as tuples, except for parentheses with one item without a comma. (By the way, thanks for the tips for posting a PEP - I'll try to do it quickly.) Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is the ucs-32 codec?
Méta-MCI wrote: Hi! Look at: http://cjkpython.berlios.de (iconvcodec) (Serge Orlov has built a version for Python 2.4 special for me; thanks to him). Thanks for the pointer. iconvcodec should do the job, but I still want a native implementation to be included with any python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Short questions wrt Python Unicode
John Machin wrote: On 9/06/2006 10:04 PM, KvS wrote: 2) How do I get a representation of a unic. object in terms of Unicode code points? repr() doesn't do that, it sometimes parses or encodes the code points right: | s=u\u0040\u0166\u00e6 | s u'@\u0166\xe6' | ' '.join('U+%04X % ord(c) for c in s) 'U+0040 U+0166 U+00E6' If you'd prefer it more Pythonic than unicode.orgic, adjust the format string and separator to suit your taste. (does this latter \xe6 have to do with the internal representation of unic. objects, maybe with this UCS-2 encoding?) | u'\xe6' == u'\u00e6' == unichr(0xe6) True | hex(ord(u'\u00e6')) '0xe6' U+nn is represented internally as the integer 0xnn -- except if it won't fit, but you can pretend that surrogate pairs don't exist, for the moment :-) Cheers, John Thanks to you and Fredrik! What about q1? I know it's silly since for integers e.g. one doesn't give such an issue any thought at all, it's just that this understanding of en/decodings etc. make things a bit more blurry to me. It should be the case that a package may do internally (en-/decodign etc.) what it wants to represent/manipulate unic. strings but should always communicate to the outside world via the interchangable uniform Python unicode object right? -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is the ucs-32 codec?
Martin v. Löwis wrote: Erik Max Francis wrote: The only reason is that nobody has needed one so far, and because it is quite some work to do if done correctly. Why do you need it? Somebody asked me about generating UTF-32 (he didn't have choice of the output format). I was about to propose the obvious ``u.encode('utf-32')`` but discovered it's missing. Someone proposed 'unicode-internal' but it depends on the build and is an ugly answer. Next time, I want Guido's Time Machine to just work, so I have to fix this ;-). Why would it be quite some work? Converting from UTF-16 to UTF-32 is pretty straightforward, and UTF-16 is already supported. I would like to see it correct, unlike the current UTF-16 codec. Perhaps whoever contributes an UTF-32 codec could also deal with the defects of the UTF-16 codec. Now this is interesting, as I hoped to base my code on UTF-16 (and perhaps UTF-8 for combining surrogates)... Can you elaborate? I could attempt to fix UTF-16 as well but I don't have the expertise to choose the right behaviour, so you'll have to specify precisely what it should do (that it doesn't do now). -- http://mail.python.org/mailman/listinfo/python-list
Re: better Python IDE? Mimics Maya's script editor?
On Thu, 08 Jun 2006 16:40:48 -0700 warpcat [EMAIL PROTECTED] wrote: # I'm using PythonWin right now and trying to find something better, # mainly with this functionality: *Assuming* I understood your description correctly, python-mode in Emacs does what you want. Emacs is hardly a substitute for PythonWin, though: the learning curve is quite steep. -- Best wishes, Slawomir Nowaczyk ( [EMAIL PROTECTED] ) If you're constantly looking behind you, you may miss the frontal attack. -- http://mail.python.org/mailman/listinfo/python-list
Re: secure xmlrpc server?
Laszlo Nagy wrote: But I do not know how to create an XML RPC server in Python that uses HTTPS for XML transports. This recent recipe seems to do exactly what you want: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496786 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Select hangs after some reads
Grant Edwards escreveu: On 2006-06-08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Well, actually I´m using a very simple protocol wich sends only strings ended by newline. I need to send 3 chunks of information and a newline after them. On the reader side I make 3 readline(), this way I wouldn´t have to care about this problem, but maybe that´s where I´m falling. If that´s the case, I´ll have to use a more complex protocol. You can't use readline() with select(). Select tells you whether recv() called on the underlying socket will block or not. What's probably happening is that all of the data has been read from the underlying socket and is being held in a buffer waiting to be read by readline(). Yes, as I expected, its the buffers. In my opinion the problem is that the socket module doesn't provide a way of reading all its internal buffer. What internal buffer? readlines() just make subsequent calls to readline and readline may call recv, so we have a locked scene. I want to know if I will block anyway. I'm lost. Of course I can clean the buffer myself, but I think the socket module should provide a way of doing this. I'm afraid I don't understand what you mean. Since you talked about calling readline(), I assumed that you had called the socket object's makefile() method to create a file-object. The select system call can only tell you whether a recv on the socket will block or not. It knows nothing about the state of the file object on which you're calling readline(). Yes, that's right. The problem I was having and discussing is that, if you read one request at a time, using a readline, and used select to check for the incoming of new ones, you will block and the other unread requests will rest in the socket buffer (_rbuf class attribute, wich is a string). If you use several readline() (that's readlines()), to try to read all the buffer, and use select to check for the new ones, you will block because after the buffer is empty readline() will try a recv(). So the problem: readline() and readlines() can block and there's nothing (given by the module) to prevent you from it happening. There are solutions to this of course, but what I was arguing is that the module and the documentation don't warn and dont treat this case. -- Grant Edwards grante Yow! Is this an out-take at from the BRADY BUNCH? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is the ucs-32 codec?
[EMAIL PROTECTED] wrote: Somebody asked me about generating UTF-32 (he didn't have choice of the output format). I was about to propose the obvious ``u.encode('utf-32')`` but discovered it's missing. hint 1: u = uHello a = array.array(I, map(ord, u)) a.tostring() 'H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00' a.byteswap() a.tostring() '\x00\x00\x00H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o' hint 2: import sys sys.byteorder 'little' /F -- http://mail.python.org/mailman/listinfo/python-list
Re: secure xmlrpc server?
Kent Johnson wrote: Laszlo Nagy wrote: But I do not know how to create an XML RPC server in Python that uses HTTPS for XML transports. This recent recipe seems to do exactly what you want: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496786 It was gently pointed out to me that the OP is the author of the recipe...well I guess he figured it out! That will teach me to get two days behind on reading c.l.py... -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Op 2006-06-08, [EMAIL PROTECTED] schreef [EMAIL PROTECTED]: Hello, Terry Reedy wrote: In a few more words: Currently, an object can be subscripted by a few elements, separated by commas. It is evaluated as if the object was subscripted by a tuple containing those elements. It is not 'as if'. 'a,b' *is* a tuple and the object *is* subcripted by a tuple. Adding () around the non-empty tuple adds nothing except a bit of noise. It doesn't necessarily matter, but technically, it is not a tuple. Yes it is. The 1, 2 in x[1, 2] isn't evaluated according to the same rules as in x = 1, 2 I was pretty sure it was. - for example, you can have x[1, 2:3:4, ..., 5], which isn't a legal tuple outside of square braces Yes it is, it just is illegal notation outside square brackets. You could have approximate the same effect by I = 1, slice(2,3,4), Ellipsis, 5 x[I] - in fact, it even isn't legal inside parens: x[(1, 2:3:4, ..., 5)] isn't legal syntax. But what is illegal is the notation, not the value. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Getting start/end dates given week-number
I've been trying to come up with a good algorithm for determining the starting and ending dates given the week number (as defined by the strftime(%W) function). My preference would be for a Sunday-Saturday range rather than a Monday-Sunday range. Thus, startDate, stopDate = weekBoundaries(2006, 23) would yield a start-date of June 4, 2006 and an end-date of June 10, 2006 in this hypothetical function (as strftime(%W) for today, June 9th, 2006 returns 23). I've posted my first round of code below, but I'm having problems with dates early in 2005, as the tests show. Any thoughts/improvements/suggestions would be most welcome. Thanks, -tkc from datetime import date, timedelta from time import strptime DEBUG = False tests = [ #test datestart end (date(2006,1,1), (date(2006,1,1), date(2006,1,7))), (date(2006,1,2), (date(2006,1,1), date(2006,1,7))), (date(2006,1,3), (date(2006,1,1), date(2006,1,7))), (date(2006,1,4), (date(2006,1,1), date(2006,1,7))), (date(2006,1,5), (date(2006,1,1), date(2006,1,7))), (date(2006,1,6), (date(2006,1,1), date(2006,1,7))), (date(2006,1,7), (date(2006,1,1), date(2006,1,7))), (date(2006,1,8), (date(2006,1,8), date(2006,1,14))), (date(2005,1,1), (date(2004,12,26), date(2005,1,1))), (date(2005,1,2), (date(2005,1,2), date(2005,1,8))), ] def weekBoundaries(year, week): startOfYear = date(year, 1, 1) now = startOfYear + timedelta(weeks=week) # isoweekday() % 7 returns Sun=0 ... Sat=6 sun = now - timedelta(days=now.isoweekday() % 7) sat = sun + timedelta(days=6) if DEBUG: print DEBUG: now = %s/%s % (now, now.strftime(%a)) print DEBUG: sun = %s/%s % (sun, sun.strftime(%a)) print DEBUG: sat = %s/%s % (sat, sat.strftime(%a)) return sun, sat for test, expectedResult in tests: print Testing %s % test year = test.year # jigger it so that %W is Sun-Sat rather than Mon-Sun weekNum = int((test + timedelta(days=1)).strftime(%W)) - 1 results = weekBoundaries(year, weekNum) passed = (expectedResult == results) print Week#%s: %s % (weekNum, passed) print = * 50 -- http://mail.python.org/mailman/listinfo/python-list
Re: UltraEdit and Python
Check out the following link: http://gurno.com/adam/python_wordfile.txt gregory diaczok wrote: How do I sent up Ultra Edit to work w/ Python? How do I get Ultra Edit to run a Python script currently in the edit window and supply results? I can't figure out how to get Ultra Edit to invoke the Python debugger to allow stepping through a Python script and view each line reults? How do I set pause / break points in Ultra Edit for a Python script? -- Thanks, Greg [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to link foreign keys primary keys using python?
Your post is confusing. Here is my advice: investigate the use of dictionaries. Dictionaries can allow you to define data in the form { key:data }, e.g. { area_code : area_data } { (area_code,school_code) : school_data } { (school_code,student_code) : student_data } -- http://mail.python.org/mailman/listinfo/python-list
removing dictionary key-pair
Hello, I try to remove a dictionary key-pair (remove an entry), but I'm unsuccessful. Does anyone know how to achieve this? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting start/end dates given week-number
see the calendar faq http://www.faqs.org/faqs/calendars/faq/part3/, look especially in section 6.7. Tim Chase wrote: I've been trying to come up with a good algorithm for determining the starting and ending dates given the week number (as defined by the strftime(%W) function). My preference would be for a Sunday-Saturday range rather than a Monday-Sunday range. Thus, startDate, stopDate = weekBoundaries(2006, 23) would yield a start-date of June 4, 2006 and an end-date of June 10, 2006 in this hypothetical function (as strftime(%W) for today, June 9th, 2006 returns 23). I've posted my first round of code below, but I'm having problems with dates early in 2005, as the tests show. Any thoughts/improvements/suggestions would be most welcome. Thanks, -tkc from datetime import date, timedelta from time import strptime DEBUG = False tests = [ #test datestart end (date(2006,1,1), (date(2006,1,1), date(2006,1,7))), (date(2006,1,2), (date(2006,1,1), date(2006,1,7))), (date(2006,1,3), (date(2006,1,1), date(2006,1,7))), (date(2006,1,4), (date(2006,1,1), date(2006,1,7))), (date(2006,1,5), (date(2006,1,1), date(2006,1,7))), (date(2006,1,6), (date(2006,1,1), date(2006,1,7))), (date(2006,1,7), (date(2006,1,1), date(2006,1,7))), (date(2006,1,8), (date(2006,1,8), date(2006,1,14))), (date(2005,1,1), (date(2004,12,26), date(2005,1,1))), (date(2005,1,2), (date(2005,1,2), date(2005,1,8))), ] def weekBoundaries(year, week): startOfYear = date(year, 1, 1) now = startOfYear + timedelta(weeks=week) # isoweekday() % 7 returns Sun=0 ... Sat=6 sun = now - timedelta(days=now.isoweekday() % 7) sat = sun + timedelta(days=6) if DEBUG: print DEBUG: now = %s/%s % (now, now.strftime(%a)) print DEBUG: sun = %s/%s % (sun, sun.strftime(%a)) print DEBUG: sat = %s/%s % (sat, sat.strftime(%a)) return sun, sat for test, expectedResult in tests: print Testing %s % test year = test.year # jigger it so that %W is Sun-Sat rather than Mon-Sun weekNum = int((test + timedelta(days=1)).strftime(%W)) - 1 results = weekBoundaries(year, weekNum) passed = (expectedResult == results) print Week#%s: %s % (weekNum, passed) print = * 50 -- http://mail.python.org/mailman/listinfo/python-list
Re: removing dictionary key-pair
JD wrote: Hello, I try to remove a dictionary key-pair (remove an entry), but I'm unsuccessful. Does anyone know how to achieve this? Thanks mydict = {key : value} del mydict(key) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: removing dictionary key-pair
JD wrote: Hello, I try to remove a dictionary key-pair (remove an entry), but I'm unsuccessful. Does anyone know how to achieve this? Thanks d = {1: one, 2: two, 3: three} del d[2] d {1: 'one', 3: 'three'} regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: removing dictionary key-pair
JD wrote: Hello, I try to remove a dictionary key-pair (remove an entry), but I'm unsuccessful. Does anyone know how to achieve this? Thanks Assuming you know the key: d = {foo:1,bar:2} print d del(d[foo]) print d -- http://mail.python.org/mailman/listinfo/python-list
Re: removing dictionary key-pair
bruno at modulix wrote: JD wrote: Hello, I try to remove a dictionary key-pair (remove an entry), but I'm unsuccessful. Does anyone know how to achieve this? Thanks mydict = {key : value} del mydict(key) grmf... Typo. This is: del mydict['key'] of course... -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: removing dictionary key-pair
JD wrote: Hello, I try to remove a dictionary key-pair (remove an entry), but I'm unsuccessful. Does anyone know how to achieve this? Thanks d = dict(a=1, b=2, c=3) print d del d['a'] print d -- http://mail.python.org/mailman/listinfo/python-list
Re: UltraEdit and Python
gregory diaczok wrote: How do I sent up Ultra Edit to work w/ Python? What do you mean? How do I get Ultra Edit to run a Python script currently in the edit window and supply results? With much help from Kent Johnson, I have the following line set up in a custom Tool Configuration: C:\Python24\pythonw C:\Python24\Lib\idlelib\idle.pyw -r %f So I just press F5 and the script gets run in IDLE. I get the nice error messages, or hopefully it just works! :) I can't figure out how to get Ultra Edit to invoke the Python debugger to allow stepping through a Python script and view each line reults? Not sure about the debugger. Do you mean using the pdb module? How do I set pause / break points in Ultra Edit for a Python script? I don't think you can normally, but maybe you can write a macro to do this. Not sure how though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing PNG with pure Python
You should really also include the alpha channel. Without that, PNG is crippled IMHO. I have now added simple transparency (marking one color as transparent with a tRNS chunk). If anybody wants full alpha channel support, ask kindly or send me a patch. I would like to avoid duplicating all the functions, so maybe we should introduce a parameter to switch between 3 and 4 bytes per pixel. Cheers, Johann -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Xah Lee wrote: in March, i posted a essay What is Expressiveness in a Computer Language, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf Has anyone read this paper? And, would anyone be interested in giving a summary? The gist of the paper is this: Some computer languages seem to be `more expressive' than others. But anything that can be computed in one Turing complete language can be computed in any other Turing complete language. Clearly the notion of expressiveness isn't concerned with ultimately computing the answer. Felleisen's paper puts forth a formal definition of expressiveness in terms of semantic equivilances of small, local constructs. In his definition, wholescale program transformation is disallowed so you cannot appeal to Turing completeness to claim program equivalence. Expressiveness isn't necessarily a good thing. For instance, in C, you can express the addresses of variables by using pointers. You cannot express the same thing in Java, and most people consider this to be a good idea. -- http://mail.python.org/mailman/listinfo/python-list
Interacting with a process that I ran with subprocess module
Hi folks, I'm trying to use the nmap runtime interaction feature while using it with the subprocess module. For those not familiar with nmap, the runtime interaction feature allow users to get informations about the scan stats during the nmap execution. More at: http://www.insecure.org/nmap/man/man-runtime-interaction.html If someone want to try, just run nmap and try to type some keys to see what happens. This only works with nmap 4.00 and above. Ok.. What I've tried is shown below: from subprocess import Popen, PIPE nmap = Popen(nmap -T3 -A 10.0.0.1-254, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True, bufsize=1) To interact with nmap, I tried: nmap.communicate(?) And I tried this, also: nmap.stdin.write(?) nmap.stdout.read() What's wrong? Is that suposed to be this way? Is there a better way to interact with it that I've missed? Any help is very welcome. Thanks in advance! Cheers! -- http://mail.python.org/mailman/listinfo/python-list
Re: Interacting with a process that I ran with subprocess module
[EMAIL PROTECTED] schrieb: Hi folks, I'm trying to use the nmap runtime interaction feature while using it with the subprocess module. For those not familiar with nmap, the runtime interaction feature allow users to get informations about the scan stats during the nmap execution. More at: http://www.insecure.org/nmap/man/man-runtime-interaction.html If someone want to try, just run nmap and try to type some keys to see what happens. This only works with nmap 4.00 and above. Ok.. What I've tried is shown below: from subprocess import Popen, PIPE nmap = Popen(nmap -T3 -A 10.0.0.1-254, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True, bufsize=1) To interact with nmap, I tried: nmap.communicate(?) And I tried this, also: nmap.stdin.write(?) nmap.stdout.read() What's wrong? Is that suposed to be this way? Is there a better way to interact with it that I've missed? Any help is very welcome. Thanks in advance! Programs that interact with users usually require a terminal to be run from. This is not the case when using pipes. Use pexpect. Diez -- http://mail.python.org/mailman/listinfo/python-list
[noob question] References and copying
Hello! Where can I find a good explanation when does an interpreter copy the value, and when does it create the reference. I thought I understand it, but I have just typed in following commands: a=[[1,2],[3,4]] b=a[1] b=[5,6] a [[1, 2], [3, 4]] b [5, 6] And I don't understand it. I thought, that b will be a reference to a, so changing b should change a as well. What do I do wrong. And a second question - can I create a reference to element of a list of floating points and use this reference to change that element? Greets to all PyFans zefciu -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
I've removed the massive cross-posting - I wouldn't presume this message is all that interesting to folks in those other NG's, and I'm sure they'd be saying, who the heck is Paul McGuire, and who gives a @#*$! what he thinks? Joe Marshall [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Expressiveness isn't necessarily a good thing. For instance, in C, you can express the addresses of variables by using pointers. You cannot express the same thing in Java, and most people consider this to be a good idea. For those who remember the bad old days of COBOL, its claim to fame was that it was more like English prose, with the intent of making a programming language that was as readable as English, assuming that this was more expressive, and not requiring as much of a mental mapping exercise for someone trying to read a program. Even the language terminology itself strived for this: statements were sentences; blocks were paragraphs. The sentence model may have ended up being one of COBOL's Achilles Heel's - the placement of terminating periods for an IF THEN ELSE block was crucial for disambiguating which ELSE went with which IF. Unfortunately, periods are one of the least visible printed characters, and an extra or missing period could cause hours of extra debugging. (Of course, at the time of COBOL's inception, the only primary languages to compare with were assembly or FORTRAN-60, so this idea wasn't totally unfounded.) -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How to extract 2 integers from a string in python?
In article [EMAIL PROTECTED], Klaus Alexander Seistrup [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] skrev: how can I extract 2 integers from a string in python? for example, my source string is this: Total size: 173233 (371587) I want to extract the integer 173233 and 371587 from that soource string, how can I do that? E.g.: #v+ import re re.findall(r'\d+', 'Total size: 173233 (371587)') ['173233', '371587'] . . . Nicely expressed. People doing a lot of report-scraping might also want to consider one of the scanf implementations for Python. URL: http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ has an example. -- http://mail.python.org/mailman/listinfo/python-list
Re: [noob question] References and copying
zefciu wrote: Hello! Where can I find a good explanation when does an interpreter copy the value, and when does it create the reference. I thought I understand it, but I have just typed in following commands: a=[[1,2],[3,4]] b=a[1] b=[5,6] a [[1, 2], [3, 4]] b [5, 6] And I don't understand it. I thought, that b will be a reference to a, so changing b should change a as well. It would if you had written b[:]=[5,6] What do I do wrong. And a second question - can I create a reference to element of a list of floating points and use this reference to change that element? not like that. Greets to all PyFans zefciu -- http://mail.python.org/mailman/listinfo/python-list
Re: CONSTRUCT - Python's way of Ruby's alias_method
Maric Michaud wrote: Le Jeudi 08 Juin 2006 14:28, Ilias Lazaridis a écrit : Another possibility is to enlink (hook?) the functionality into an existent function Is there any way (beside a patch) to alter the behaviour to an existing function. Is ther a python construct similar to the alias_method of Ruby: No, there is no special construct to do this, but we do things very similar every day in Zope, it's called monkey patch : #patch_service.py from toto import service def my_impl(self, *args) : old_result = self._old_method(*args) # ... return new_result if not hasattr(service, '_old_method') : service._old_method = service.method service.method = my_impl once this file is imported, all future calls to method of service instances will use my_impl. Ok, just a small problem when a _function_ is to be hooked. Looking a the code in the debugger shows that the function syncdb is correctly overridden. But when the code returns, syncdb has again it's original value. Can I import syncdb by reference instead by value, thus the change 'survives'? #-- #syncdb_hook.py from django.rework.evolve import evolvedb from django.core.management import syncdb def syncdb_new(*args) : evolvedb() syncdb_result = syncdb_old(*args) return syncdb_result if syncdb != syncdb_new: syncdb_old = syncdb syncdb = syncdb_new . -- http://lazaridis.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in Chain of Function calls (Code Attached)
Girish Sahani wrote: Hi, There is a code in my main function which is something like: while prunedFinal != []: prunedNew = genColocations(prunedK) *** tableInstancesNew = genTableInstances(prunedNew,tableInstancesK) tiCountDict = tiCount(tableInstancesNew) tiDict = findPI(tableInstancesNew) prunedFinal = pruneTI(tiDict,pi) rulesDict = genRules(prunedFinal) cpDict = findCP(rulesDict) prunedRulesList = pruneCP(cpDict,cp) prunedK = prunedFinal tableInstancesK = tableInstancesNew else: return prunedRulesList prunedK and tableInstancesK are defined in the main function. defined as what ? functions, strings, lists, classes, ... ? PrunedK is a list that contains 2 length strings and tableInstancesK is a dictionary,its keys are 2 length strings and values are lists of lists Before the main function, i have defined the other functions such as genColocations,genTableInstances,etc. Output of genColocations is to be given to the next function genTableInstances,output of this function to tiCount and findPI, and so on. However i am getting an error at the line marked with ***. Which error ? How do you hope us to be of any help here if you don't *at least* provide the full traceback ? FWIW, the canonical way to do things is to: - provide minimal *runnable* code exposing the problem - explain what you hoped to get - explain what you got instead (including full traceback) As a matter of fact, it's often the case that one solves the problem when working on the first point !-) (snip) Ohh...I was thinking that posting the whole code would not be a good idea. The error i get above is: line 266, in colocationMiner prunedNew = genColocations(prunedK) Anyways, i've attached the file colocations.py. The expected output is a List of rules (prunedRulesList).These rules are themselves lists.e.g ['ab','c'] denotes the rule ab=c. Please do have a look if you have time :). -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list #convert the input file into a dictionary (global ids mapped to feature type) and a list of global id pairs def get_colocations(filename): lines = open(filename).read().split(\n) colocnDict = {} for line in lines: n1, b1, n2, b2 = line.split(,) n1 = int(n1) n2 = int(n2) a1 = b1.strip(') a2 = b2.strip(') colocnDict[n1] = a1 colocnDict[n2] = a2 return colocnDict #get pairs of feature ids which are colocated def getPairs(filename): lines = open(filename).read().split(\n) pairList = [] for line in lines: n1, b1, n2, b2 = line.split(,) pairList.append([n1, n2]) return pairList #count number of occurences of each feature in the feature list and store in featueCountDict def getFeatureCount(): colocnDict = get_colocations(colocations.txt) featureList= colocnDict.values() featureListUnique = [] [featureListUnique.append(word) for word in featureList if not featureListUnique.count(word)] featureCountDict = {} for feature in featureListUnique: featureCountDict[feature] = featureList.count(feature) return featureCountDict def k2k1(string1, string2): for c in string1: string2 = string2.replace(c,,1) if len(string2) == 1: string1 += string2 else: pass return string1 def dictInvert(d): dictInv = {} for k, v in d.iteritems(): keys = dictInv.setdefault(v, []) keys.append(k) return dictInv #Generate candidate co-locations of size k+1 from size k #get lower level subsets and prune it by antimonotone property def genColocations(prunedK): prunedNew = substringList = [] for string1 in prunedK: for string2 in prunedK: k = len(string2) if string1 != string2: string1 = k2k1(string1, string2) if len(string1) == k+1: prunedNew.append(string1) for s in prunedNew: substrings = [s[:i]+s[i+1:] for i in range(len(s))] for string in substrings: if string not in prunedK: prunedNew.remove(s) continue continue #tableInstancesNew is a dictionary with keys as k level colocations and values as table instances def genTableInstances(prunedNew,tableInstancesK): colocnDict = get_colocations(colocations.txt) tableInstancesNew = {} for s in p: substring1 = s[:len(s)-1] substring2 = s[:len(s)-2]+s[len(s)-1:] #get 2 substrings list1 = tableInstancesK(substring1) list2 =
Re: [noob question] References and copying
zefciu wrote: Hello! Where can I find a good explanation when does an interpreter copy the value, and when does it create the reference. I thought I understand it, but I have just typed in following commands: a=[[1,2],[3,4]] b=a[1] b=[5,6] a [[1, 2], [3, 4]] b [5, 6] And I don't understand it. I thought, that b will be a reference to a, so changing b should change a as well. What do I do wrong. And a second question - can I create a reference to element of a list of floating points and use this reference to change that element? Greets to all PyFans zefciu Nope, b is a reference to the same object referenced by a[1], but only until you rebind it. Think of assignment (binding) as storing a pointer to an object in a name. So a = [[2,3],[3,4]] stores a pointer to a list in a. The list itself holds two pointers to (otherwise anonymous) lists. Then b = a[1] make b point to the same object as a[1] does. At this point you could, for example, execute b[0] = 42 Then when you printed the value of a you would see [[1, 2], [42, 4]] and you would see [42, 4] as the value of b. But you don't do that, you next do b = [5, 6] This stores a reference to an entirely different new list in b, with the results you observe. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: References and copying
Where can I find a good explanation when does an interpreter copy the value, and when does it create the reference. Any good Python book. I have Learning Python and Programming Python 2nd edition and they are very good IMO. I thought I understand it, but I have just typed in following commands: a=[[1,2],[3,4]] b=a[1] b=[5,6] a [[1, 2], [3, 4]] b [5, 6] And I don't understand it. I thought, that b will be a reference to a, so changing b should change a as well. No, you've set the name b to reference a slice of a. Slicing a list always returns a new list. To change a via b, do this: a = [[1,2],[3,4]] b = a print a print b b[1] = [5,6] print a print b -- http://mail.python.org/mailman/listinfo/python-list
About sizers..
Hi, Im build a cross platform application develop with Python and wxPython and I ask for your opinions about if is a good choice use sizers for my frames design? or not? Other techniques? Thanks in advance! Mi configuracion/My config: Ubuntu Dapper 6.06 Linux Kernel 2.6.15.23.386 Python 2.4.3 wxPython 2.6.1.2Pre -- Saludos / Best regards Mario Lacunza Vásquez Desarrollador de Software - Webmaster Desarrollador 2 Estrellas VS2005 Website: http://mlacunzav.cogia.net Email : mlacunza[AT]gmail[DOT]com Email : mario_lacunza[AT]yahoo[DOT]es Blog : http://mlacunza.blogspot.com Lima - Peru -- http://mail.python.org/mailman/listinfo/python-list
About sizers..
Hi, Im build a cross platform application develop with Python and wxPython and I ask for your opinions about if is a good choice use sizers for my frames design? or not? Other techniques? Thanks in advance! Mi configuracion/My config: Ubuntu Dapper 6.06 Linux Kernel 2.6.15.23.386 Python 2.4.3 wxPython 2.6.1.2Pre -- Saludos / Best regards Mario Lacunza Vásquez Desarrollador de Software - Webmaster Desarrollador 2 Estrellas VS2005 Website: http://mlacunzav.cogia.net Email : mlacunza[AT]gmail[DOT]com Email : mario_lacunza[AT]yahoo[DOT]es Blog : http://mlacunza.blogspot.com Lima - Peru -- http://mail.python.org/mailman/listinfo/python-list
Re: How to link foreign keys primary keys using python?
sonal [EMAIL PROTECTED] writes: Hi all, I hv started with python just recently... and have been assigned to make an utility which would be used for data validations... ,snip] plz help me... till get my hands on python... :) 1. This sure looks like a school assignment. 2. till get my... Do you actually not have python installed yet? It is hopeless to tackle this problem if you haven't done a few simple hello, world tasks. 3. Do you have a data model? In this case, you need to think carefully about what a RDBMS, PK, and FK are. In otherwords, a metamodel. Generally, once you understand the data structures you should implement them pretty much verbatim in a model module. Then do reader/writer modules so you can load that model from your data sources and dump out to your data sinks. 4. Do you have a testsuite and test harness? Put together your test harness, then develop for the simplest case, then add complexity. E.g., no FK, FK with 1 attr, FK with multiple attrs, FKs with shared attrs. -- Harry George PLM Engineering Architecture -- http://mail.python.org/mailman/listinfo/python-list
Thread specific singleton
Hi, I'm tring to implement a Singleton object that should be specific for every thread who create it, not global. I tried a solution that seems to work, but I have a very poor knowledge of concurrent programming, so I'd like someone to help me find some problems in my implementation. Here is the code: - import thread class ThreadLock(object): locks = {} def __new__(cls): id = thread.get_ident() try: lock = cls.locks[id] except KeyError: lock = thread.allocate_lock() cls.locks[id] = lock return lock @classmethod def clear(cls, id=None): Clear the lock associated with a given id. If the id is None, thread.get_ident() is used. if id is None: id = thread.get_ident() try: del cls.locks[id] except KeyError: pass class ThreadedSingleton(object): pool = {} def __new__(cls, *args, **kw): lock = ThreadLock() lock.acquire() id = thread.get_ident() try: obj = cls.pool[id] except KeyError: obj = object.__new__(cls, *args, **kw) if hasattr(obj, '__init_singleton__'): obj.__init_singleton__(*args, **kw) cls.pool[id] = obj lock.release() return obj def __del__(self): id = thread.get_ident() ThreadLock.clear(id) try: del cls.pool[id] except KeyError: pass if __name__ == '__main__': import time import random class Specific(ThreadedSingleton): def __init_singleton__(self): print Init singleton self.a = None def test(a): s = Specific() s.a = a print %d: %s %(thread.get_ident(), Specific().a) time.sleep(1) print %d: %s %(thread.get_ident(), Specific().a) time.sleep(random.randint(1, 5)) print %d: %s %(thread.get_ident(), Specific().a) time.sleep(2) print %d: %s %(thread.get_ident(), Specific().a) for x in range(4): thread.start_new_thread(test, (x, )) time.sleep(10) - using the thread module should be fine even if threads are created trought the threading module, right ? Thanks, Gabriele -- http://mail.python.org/mailman/listinfo/python-list
Re: Win XP: Problem with shell scripting in Python
I dare hardly suggest this, but might it not be better to use Python's database functionality to perform the task? The language can access both databases, and you might find it quicker. Then again, if your database experience is limited, you may not ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden Hi Steven, Based on my experience, the fastest possible way to import raw data into Oracle is SQL*Loader. Similarly, the fastest way to extract raw data from SQL server is BCP. My script transfers 40,000,000 records (actually big records) from sql server to oracle in 20 Min. I tried ODBC to do the same work. I turned off all record locking and transactions through query hints. The actual program was a C# program. After 12 hours, I just stopped the program. I created DOS batch files to control BCP and SQL*Loader steps. It is faster than any fancy GUI tools. Now I am using Python. I am thinking to add comprehensive logging to the ETL (extract transform load) process. All details command line outputs will be stored in database. System administrators can query database and watch how the ETL job is working. At this point I have quite challenge with capturing BCP's stdout/stderr output to string variables in Python program. I'll post the final outcome here. Regards, Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in Chain of Function calls (Code Attached)
Girish Sahani wrote: However i am getting an error at the line marked with ***. Which error ? How do you hope us to be of any help here if you don't *at least* provide the full traceback ? FWIW, the canonical way to do things is to: - provide minimal *runnable* code exposing the problem - explain what you hoped to get - explain what you got instead (including full traceback) As a matter of fact, it's often the case that one solves the problem when working on the first point !-) (snip) Ohh...I was thinking that posting the whole code would not be a good idea. And what changed your mind ? Please note the word minimal in bruno's sentence about submitting your code. And also the request for explanations. The error i get above is: line 266, in colocationMiner prunedNew = genColocations(prunedK) OTOH, bruno asked for the full traceback, that's not it - that's not the error in any constructive sense, neither its type nor its real location. -- http://mail.python.org/mailman/listinfo/python-list
Re: Win XP: Problem with shell scripting in Python
A.M wrote: I dare hardly suggest this, but might it not be better to use Python's database functionality to perform the task? The language can access both databases, and you might find it quicker. Then again, if your database experience is limited, you may not ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden Hi Steven, Based on my experience, the fastest possible way to import raw data into Oracle is SQL*Loader. Similarly, the fastest way to extract raw data from SQL server is BCP. My script transfers 40,000,000 records (actually big records) from sql server to oracle in 20 Min. I tried ODBC to do the same work. I turned off all record locking and transactions through query hints. The actual program was a C# program. After 12 hours, I just stopped the program. I'm not that surprised - it was just an inquiry. Usually the database bulk dump and load utilities take advantage of every trick in their respective books to provide speed. A native driver might have done better than ODBC, but you are probably correct on going that route for speed. I created DOS batch files to control BCP and SQL*Loader steps. It is faster than any fancy GUI tools. Now I am using Python. I am thinking to add comprehensive logging to the ETL (extract transform load) process. All details command line outputs will be stored in database. System administrators can query database and watch how the ETL job is working. At this point I have quite challenge with capturing BCP's stdout/stderr output to string variables in Python program. I'll post the final outcome here. OK, good luck. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Joe Marshall wrote: Xah Lee wrote: On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf The gist of the paper is this: Some computer languages seem to be `more expressive' than others. But anything that can be computed in one Turing complete language can be computed in any other Turing complete language. Clearly the notion of expressiveness isn't concerned with ultimately computing the answer. Felleisen's paper puts forth a formal definition of expressiveness in terms of semantic equivilances of small, local constructs. In his definition, wholescale program transformation is disallowed so you cannot appeal to Turing completeness to claim program equivalence. I suspect that the small, local transformations versus global transformations is also to do with the practice of not saying the same thing twice. Everything from subroutines to LISP macros also helps here, increasing language expressiveness. Expressiveness isn't necessarily a good thing. For instance, in C, you can express the addresses of variables by using pointers. You cannot express the same thing in Java, and most people consider this to be a good idea. Assuming the more-expressive feature does not preclude the less-expressive one, good/bad depends on the programmer. I know *I* can't be trusted with pointers ;-) , but I know many programmers benefit greatly from them. Of course, knowing that the programmer cannot do something does help the compiler stop you shooting yourself in the foot. -- Simon Richard Clarkstone: [EMAIL PROTECTED]/s?m?n.cl?rkst?n?@ hotmail.com ### I have a spelling chequer / it came with my PC / it plainly marks for my revue / Mistake's I cannot sea ... by: John Brophy (at: http://www.cfwf.ca/farmj/fjjun96/) -- http://mail.python.org/mailman/listinfo/python-list
Re: capture video from camera
K.S.Sreeram wrote: dan wrote: I hope you won't be deterred from posting further questions to the group by Fredrik's somewhat terse and unfriendly reply. comp.lang.python is a forum generally noted for its pleasing admixture of erudition and encouragement. Fredrik is uncommonly distinguished in the scope and depth of his knowledge. He does himself, and the group in general, an injustice by the intolerance of his response. People need to learn to be precise and to-the-point in their posts. If not, its a waste of time for a lot of people.. more so for frequent contributors like fredrik. I hope criticism like yours does not deter him! Hi K.S, People learn through encouragement and appropriate example, not through criticism... Best wishes, Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Hello, Following Fredrik's suggestion, I wrote a pre-PEP. It's available on the wiki, at http://wiki.python.org/moin/EmptySubscriptListPEP and I also copied it to this message. Have a good day, Noam PEP: XXX Title: Allow Empty Subscript List Without Parentheses Version: $Revision$ Last-Modified: $Date$ Author: Noam Raphael [EMAIL PROTECTED] Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 09-Jun-2006 Python-Version: 2.5? Post-History: 30-Aug-2002 Abstract This PEP suggests to allow the use of an empty subscript list, for example ``x[]``, which is currently a syntax error. It is suggested that in such a case, an empty tuple will be passed as an argument to the __getitem__ and __setitem__ methods. This is consistent with the current behaviour of passing a tuple with n elements to those methods when a subscript list of length n is used, if it includes a comma. Specification = The Python grammar specifies that inside the square brackets trailing an expression, a list of subscripts, separated by commas, should be given. If the list consists of a single subscript without a trailing comma, a single object (an ellipsis, a slice or any other object) is passed to the resulting __getitem__ or __setitem__ call. If the list consists of many subscripts, or of a single subscript with a trailing comma, a tuple is passed to the resulting __getitem__ or __setitem__ call, with an item for each subscript. Here is the formal definition of the grammar: :: trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] sliceop: ':' [test] This PEP suggests to allow an empty subscript list, with nothing inside the square brackets. It will result in passing an empty tuple to the resulting __getitem__ or __setitem__ call. The change in the grammar is to make subscriptlist in the first quoted line optional: :: trailer: '(' [arglist] ')' | '[' [subscriptlist] ']' | '.' NAME Motivation == This suggestion allows you to refer to zero-dimensional arrays elegantly. In NumPy, you can have arrays with a different number of dimensions. In order to refer to a value in a two-dimensional array, you write ``a[i, j]``. In order to refer to a value in a one-dimensional array, you write ``a[i]``. You can also have a zero-dimensional array, which holds a single value (a scalar). To refer to its value, you currently need to write ``a[()]``, which is unexpected - the user may not even know that when he writes ``a[i, j]`` he constructs a tuple, so he won't guess the ``a[()]`` syntax. If the suggestion is accepted, the user will be able to write ``a[]`` in order to refer to the value, as expected. It will even work without changing the NumPy package at all! In the normal use of NumPy, you usually don't encounter zero-dimensional arrays. However, the author of this PEP is designing another library for managing multi-dimensional arrays of data. Its purpose is similar to that of a spreadsheet - to analyze data and preserve the relations between a source of a calculation and its destination. In such an environment you may have many multi-dimensional arrays - for example, the sales of several products over several time periods. But you may also have several zero-dimensional arrays, that is, single values - for example, the income tax rate. It is desired that the access to the zero-dimensional arrays will be consistent with the access to the multi-dimensional arrays. Just using the name of the zero-dimensional array to obtain its value isn't going to work - the array and the value it contains have to be distinguished. Rationale = Passing an empty tuple to the __getitem__ or __setitem__ call was chosen because it is consistent with passing a tuple of n elements when a subscript list of n elements is used. Also, it will make NumPy and similar packages work as expected for zero-dimensional arrays without any changes. Another hint for consistency: Currently, these equivalences hold: :: x[i, j, k] -- x[(i, j, k)] x[i, j] -- x[(i, j)] x[i, ] -- x[(i, )] x[i]-- x[(i)] If this PEP is accepted, another equivalence will hold: :: x[] -- x[()] Backwards Compatibility === This change is fully backwards compatible, since it only assigns a meaning to a previously illegal syntax. Reference Implementation Available as SF Patch no. 1503556. (and also in http://python.pastebin.com/768317 ) It passes the Python test suite, but currently doesn't provide additional tests or documentation. Copyright = This document has been placed in the public domain. -- http://mail.python.org/mailman/listinfo/python-list
regexp questoin
hi i created a script to ask user for an input that can be a pattern right now, i use re to compile that pattern pat = re.compile(r%s %(userinput) ) #userinput is passed from command line argument if the user key in a pattern , eg [-] , and my script will search some lines that contains [-] pat.findall(lines) but the script produce some error: sre_constants.error: unexpected end of regular expression how can i successful catch patterns such as [-] in my regexp compilation where input is unknown...? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: [noob question] References and copying
zefciu wrote: Hello! Where can I find a good explanation when does an interpreter copy the value, and when does it create the reference. Unless you explicitely ask for a copy (either using the copy module or a specific function or method), you'll get a reference. I thought I understand it, but I have just typed in following commands: a=[[1,2],[3,4]] - creates a list object containing 2 list objects, the first one containing 2 integer objects with respective values 1 and 2, the second one containing 2 integer objects with respective values 3 and 4 - associates ('binds') the name 'a' with the list object. Now in the current namespace, 'a' refers to this list. b=a[1] - binds the name 'b' with the second element of [the list bound to] 'a' b=[5,6] - *re*binds 'b' to a new list containing two integer objects with respective values 5 and 6. a [[1, 2], [3, 4]] b [5, 6] Which is exactly what you asked for (while not being what you thought you asked for...). And I don't understand it. I thought, that b will be a reference to a, It was - before you rebind it to another object. so changing b should change a as well. To be pedantic, you don't change 'b'. You can either modify the object bound to 'b' (which you did not) or rebind 'b' to another object (which you did). What do I do wrong. confusing rebinding a name and modifying an object. Try this to better see what happens NB : - id() returns the unique identifier of an object - actually, in CPython, it's memory address, - 'is' test for identity ( a is b = id(a) == id(b) a = [[1, 2], [3, 4]] id(a) 46912496884192 id(a[1]) 46912496914656 b = a[1] id(b) 46912496914656 b is a[1] True b = [5, 6] id(b) 46912496915520 b is a[1] False Now to modify a[1] thru b : b = a[1] id(b) 46912496914656 b is a[1] True # add an item b.append(5) b [3, 4, 5] b is a[1] True a[1] [3, 4, 5] # remove the first item del b[0] a[1] [4, 5] # replace actual content with something else b[:] = [5, 6] b [5, 6] b is a[1] True a [[1, 2], [5, 6]] And a second question - can I create a reference to element of a list of floating points and use this reference to change that element? Not directly - but this has nothing to do with a reference-or-value problem. It's just that floats (like ints, strings and tuples) are immutable. You'll need either to work with indices or to wrap your floats in mutable objects. I'd recommand the first solution. Greets to all PyFans zefciu -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list