Python in a strange land: IronPython and ASP.NET at the next PyGTA
IronPython is a native implementation of Python on the Microsoft .NET platform. The implementation is from Microsoft and the language is well supported by the Visual Studio development environment which has always been one of the Microsoft platform's strengths. Though Python is often associated with the Free and Open Source communities, consultants and developers frequently need to solve real-world problems using Python on the .NET platform. IronPython makes using Python in these situations a natural choice for the Python programmer. Our speaker for the evening is Myles Braithwaite, a local consultant and developer. He is going to give us an idea of how developing a web application using ASP.NET looks when using IronPython instead of C#, as well as his impressions of the platform. As usual, we will hold the presentation at Linux Caffe, gathering for introductions at 6:30 PM, with the formal presentation beginning at 7:00 PM. We normally head out around 8:30 PM for beer, coffee and/or ice cream. You can find directions and maps to Linux Caffe on the wiki: http://web.engcorp.com/pygta/wiki/NextMeeting Hope to see you all there, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Problem with algorithm
Charles Sanders [EMAIL PROTECTED] writes: Forgive any silly mistakes I have made (I've been teaching myself python for about 1 week) but there is a moderately well known algorithm for this that extends to arbitrary lengths of both the list of alternatives and the length of the required output, and avoids deeply nested loops. s = abcd def a(n): if n==0: yield '' return for c in s: for r in a(n-1): yield c+r print list(a(3)) -- http://mail.python.org/mailman/listinfo/python-list
Databases with python
Hi All, I am interested in playing with python some more and am looking at writing an app with data stored in a database. I have experience with mysql but thought that their may be other better databases that can be more easily distributed with the program does anyone have any suggestions here? I only use linux myself but I can foresee some windows people wanting to use what I create and if I am going to support windows then I might as well support mac too. (this is to say that the database should support the 3 main platforms in use) Also is wxpython the best cross platform gui library it seems to be the best I have seen so far. -- Kind Regards, Anthony Irwin http://www.irwinresources.com email: anthony at the above domain, - www. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
Paul Rubin wrote: [snip] def a(n): if n==0: yield '' return for c in s: for r in a(n-1): yield c+r print list(a(3)) Of course, obvious in retrospect, recursion instead of iteration. I have yet to completely wean myself off Fortran style thinking. Charles -- http://mail.python.org/mailman/listinfo/python-list
Python and JMS?
Hello, I would like to write some Python to monitor a JMS middleware software bus. JMS being Java Messaging Service. Can anyone recommend a Python wrapper to JMS for this? My goal is to listen for XML being transfered over a JMS implementation. All the applications so far are in Java. Thanks for any replies? Len -- === Leonard J. Reder Home office email : [EMAIL PROTECTED] Lab email : [EMAIL PROTECTED] Lab web page : http://reder.jpl.nasa.gov === -- http://mail.python.org/mailman/listinfo/python-list
Python and XML?
Hello, What is the best way to process a Relax NG Schema and auto generate XML Python parser/generator code? Any suggestions? Thanks for all replies, Len -- === Leonard J. Reder Home office email : [EMAIL PROTECTED] Lab email : [EMAIL PROTECTED] Lab web page : http://reder.jpl.nasa.gov === -- http://mail.python.org/mailman/listinfo/python-list
Re: output of top on a linux box
Can you pull the same information from /proc/stat as opposed to using a pipe to top? The first line(s) should contain (at least): cpu usermode, lowprio, system, idle, hz. Thanks a lot for the help. I finally decided to go with your suggestion. -- warm regards, Pradnyesh Sawant -- Be yourself..everyone else is taken. --Anon -- http://mail.python.org/mailman/listinfo/python-list
Re: doubt with importing module, given module name
module_name = module mod = __import__(module_name) class_name = module_name.capitalize() cls = getattr(mod, class_name) inst = cls() Worked like a magic charm :) Also helped me understand the concept of getattr :D Thanks a million! -- warm regards, Pradnyesh Sawant -- Be yourself..everyone else is taken. --Anon -- http://mail.python.org/mailman/listinfo/python-list
help
hello (I hope my english is not so bad), I'm doing a training course and I'm a newbie in Python. My problem : I have a form, and when I click, I make an update. But all the parameters are all required to make the update. So I'd like to put in my code something like [optional]... My code (simplyfied) : prg.ev_ind_update(wf_pk_ev_ind=wf_pk_ev_ind,wf_fonction=wf_fonction,wf_nom=wf_nom) and so, when I put nothing in wf_nom, it put me that error :the parameter wf_nom...was omitted from the request But sometimes, wf_nom is not required ! Thanks to help a poor young boy _ Personnalisez votre Messenger avec Live.com http://www.windowslive.fr/livecom/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
for m in test: for n in test: for o in test: for p in test: print m+n+o+p Thanx for your anwser. But if I consider about a combination of over 26 letter's list just like: abcdefssdzxcvzxcvzcv asllxcvxcbbedfgdfgdg . Need I write 26 for loops to do this? Thanx Jia LU -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling private base methods
7stud [EMAIL PROTECTED] wrote: Really, it does work (probably). There are other ways to get at private members in C++ but this is the easiest. I can also access private methods of a class if my sister backspaces over private and types public instead. In your example, no private methods were ever created, and therefore you are not accessing private methods. Are you being deliberately obtuse? The methods are private throughout the program *except* for the one source file where you do this trick. It won't work if the compiler mangles the protection into the name, but I have used this successfully with a C++ library where I absolutely couldn't do what I needed without getting at a private method. The fact that I had to resort to this trick is a big indication of course that genuinely private members (as opposed to a 'keep off' naming convention) are a bad idea in general. If the name does get mangled then you may of course have to do other much messier tricks to get at the address of the function and then call it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling private base methods
Dan Bishop [EMAIL PROTECTED] wrote: I have a job as a C++ programmer and once tried this trick in order to get at a private member function I needed. Didn't work: Apparently, VC ++ includes the access level in its name mangling, so you get linker errors. I don't have a copy of VC to hand to test, but I might have tried something along these lines: somheader contains: class Whatever { private: void ohnoyoudont(int); } My C file: #define ohnoyoudont blah(){};public: \ inline void sneak(int x){this.ohnoyoudont(x);};private:void ohnoyoudont #include someheader #undef ohnoyoudont ... Whatever foo = new Whatever(); int ohyesido = 42; foo.sneak(ohyesido); I don't think injecting another couple of non-virtual methods into the class ought to break anything. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-12, Carsten Haese [EMAIL PROTECTED] wrote: On Thu, 2007-04-12 at 14:10 +, Antoon Pardon wrote: People are always defending duck-typing in this news group and now python has chosen to choose the option that makes duck-typing more difficult. Au contraire! The inconsistent behavior of in is precisely what duck-typing is all about: Making the operator behave in a way that makes sense in its context. No it isn't. Ducktyping is about similar objects using a similar interface to invoke similar behaviour and getting similar result. So that if you write a function you don't concern yourself with the type of the arguments but depend on the similar behaviour. Suppose someone writes a function that acts on a sequence. The algorithm used depending on the following invariant. i = s.index(e) = s[i] = e Then this algorithm is no longer guaranteed to work with strings. On the other hand I subclass list and add a sub method to check for the argument being a sublist of the object. Now I write a function that depends on this functionality. But although strings have the functionality I can't use them as argument because the functionality is invoked in a different way. Nobody seems to be complaining about + behaving inconsistently depending on whether you're adding numbers or sequences. You are wrong. I already mentioned problems with it. The problem is that there are structures that are numbers and sequences at the same time. So I have a choice. Either I overload the + to get an addition or to get a concatanation. In the first case I can't trust my structure to work with functions that expect a general sequence because they may depend on the fact that + concatenates. In the other case I can't trust my structure to work with numbers because they may depend on the fact that + behaves like an addition. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Databases with python
Anthony Irwin wrote: Hi All, I am interested in playing with python some more and am looking at writing an app with data stored in a database. I have experience with mysql but thought that their may be other better databases that can be more easily distributed with the program does anyone have any suggestions here? with SQLObject ( http://www.sqlobject.org/ ) or SQLAlchemy ( http://www.sqlalchemy.org/ ) you can use any of the supported (sqlite, mysql, postgresql, firebird) databases in an object oriented way without worrying about the details of the database you use. sqlite ( http://www.sqlite.org/ ) is a database which stores its data directly into a file, while all other databases require a server to be installed prior to using it, so if you want to distribute your application it might be the easiest way to use sqlite as your database. Python 2.5 and newer has sqlite already included, thus it seems the database of choice. I only use linux myself but I can foresee some windows people wanting to use what I create and if I am going to support windows then I might as well support mac too. (this is to say that the database should support the 3 main platforms in use) Also is wxpython the best cross platform gui library it seems to be the best I have seen so far. Happy pythoning Herbert ps: if you want to create a web-application i can recommend TurboGears ( http://www.turbogears.org/ ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and JMS?
Leonard J. Reder napisał(a): I would like to write some Python to monitor a JMS middleware software bus. JMS being Java Messaging Service. Can anyone recommend a Python wrapper to JMS for this? My goal is to listen for XML being transfered over a JMS implementation. All the applications so far are in Java. Quick googling for python jms yields http://hjb.python-hosting.com/ as 1st result and for a long time this seems the only solution that works. Unfortuantely, it's functionality is severely limited. If you happen to use ActiveMQ, you can try to use stomp protocol, but this isn't a standard (I don't know any other implementation of queuing software that uses this). -- Jarek Zgoda We read Knuth so you don't have to. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-12, Steven D'Aprano [EMAIL PROTECTED] wrote: On Thu, 12 Apr 2007 07:37:38 +, Antoon Pardon wrote: I once had a problem I like to solve by having a dictionary where the keys were multidimensional points on an integer grid. For a number of reasons I thought it would be easier if I could use lists, but most people argued that would be a bad idea and that I should use tuples, because they are immutable. Also because code that raises TypeError: list objects are unhashable is probably not going to work very well. Of course if I now would want to find out if the point is on an axis and which axis that is, I cannot use index because that is not available. If memory is more important to you than speed: class IndexTuple(tuple): def index(self, target): for i, x in enumerate(self): if x == target: return i raise ValueError Or if speed is more important to you than memory: class IndexTuple2(tuple): def index(self, target): return list(self).index(target) If you prefer not to subclass, you can write an index function: def index(sequence_or_mapping, target): try: return sequence_or_mapping.index(target) except AttributeError: return list(sequence_or_mapping).index(target) So much fuss over such a little thing... yes it would be nice if tuples grew an index method, but it isn't hard to work around the lack. Yes it is a little thing. But if it is such a little thing why do the developers don't simply add it? Python like any other human product has it shortcomings. I can live with them. If a wart turns up and the general answer would be, yes we know it is a wart but it is the result of how python grew or it was the best compromise we could think of and too much depends on it now to change it. This kind of threads would die quickly. Instead we often enough see the warts getting defended as good design. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
which version libpcap
hi from the web, i found 2 kinds of wrappers for libpcap, one is pylibpcap, the other is pcapy. may i know which is more popularly used? thanks -- http://mail.python.org/mailman/listinfo/python-list
split and regexp on textfile
Hi, i have a problem with the split function and regexp. I have a file that i want to split using the date as token. Here a sample: - Mon Apr 9 22:30:18 2007 text text Mon Apr 9 22:31:10 2007 text text I'm trying to put all the lines in a one string and then to separate it (could be better to not delete the \n if possible...) while 1: line = ftoparse.readline() if not line: break if line[-1]=='\n': line=line[:-1] file_str += line matchobj=re.compile('[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ][0-9] [ ][0-9][0-9][:]') matchobj=matchobj.split(file_str) print matchobj i have tried also matchobj=re.split(r^[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ] [0-9][ ][0-9][0-9][:],file_str) and reading all with one: file_str=ftoparse.readlines() but the split doesn't work...where i am wronging? -- http://mail.python.org/mailman/listinfo/python-list
Re: Databases with python
On Apr 13, 1:02 am, Anthony Irwin [EMAIL PROTECTED] wrote: Hi All, I am interested in playing with python some more and am looking at writing an app with data stored in a database. I have experience with mysql but thought that their may be other better databases that can be more easily distributed with the program does anyone have any suggestions here? Specially if your program is going to be multi plattform, check out BuzHug http://buzhug.sourceforge.net/ It is a pure python database. Its performance may not be that high, but it will be very easily distributed with your program. The interface is pythonic, with no SQL to write. -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Pythonistas in Mexico?
On Apr 12, 8:56 am, Marcpp [EMAIL PROTECTED] wrote: Yo vivo en España. Usas el pyqt? Hola! no, no lo he usado, aunque ahorita estoy más bien haciendo mis experimentos con wxPython... Hugo -- http://mail.python.org/mailman/listinfo/python-list
HELP PARAMETERS IN SQL QUERY
hello, I'm doing a training course and I'm a newbie in Python. My problem : I have a form, and when I click, I make an update. But all the parameters are all required to make the update. So I'd like to put in my code something like [optional]... My code (simplyfied) : prg.ev_ind_update(wf_pk_ev_ind=wf_pk_ev_ind,wf_fonction=wf_fonction,wf_nom=wf_nom) and so, when I put nothing in wf_nom, it put me that error :the parameter wf_nom...was omitted from the request But sometimes, wf_nom is not required ! Thanks for your help _ Découvrez le Blog heroic Fantaisy d'Eragon! http://eragon-heroic-fantasy.spaces.live.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
I think that this would be very silly to do. bad kung foo. The recoursion technique would be more satisfying. You sholud consider that this would take about 4 lines to write. Also be avare of the default recoursion depth in python wich is 1000. you can get and set the recoursion limit hrough importing the sys module and using getrecoursionlimit() and setrecoursionlimit(). On Apr 13, 9:16 am, Jia Lu [EMAIL PROTECTED] wrote: for m in test: for n in test: for o in test: for p in test: print m+n+o+p Thanx for your anwser. But if I consider about a combination of over 26 letter's list just like: abcdefssdzxcvzxcvzcv asllxcvxcbbedfgdfgdg . Need I write 26 for loops to do this? Thanx Jia LU -- http://mail.python.org/mailman/listinfo/python-list
Re: split and regexp on textfile
On Apr 13, 3:59 pm, Flyzone [EMAIL PROTECTED] wrote: Hi, i have a problem with the split function and regexp. I have a file that i want to split using the date as token. Here a sample: - Mon Apr 9 22:30:18 2007 text text Mon Apr 9 22:31:10 2007 text text I'm trying to put all the lines in a one string and then to separate it (could be better to not delete the \n if possible...) while 1: line = ftoparse.readline() if not line: break if line[-1]=='\n': line=line[:-1] file_str += line matchobj=re.compile('[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ][0-9] [ ][0-9][0-9][:]') matchobj=matchobj.split(file_str) print matchobj i have tried also matchobj=re.split(r^[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ] [0-9][ ][0-9][0-9][:],file_str) and reading all with one: file_str=ftoparse.readlines() but the split doesn't work...where i am wronging? you trying to match the date part right? if re is what you desire, here's one example: data = open(file).read() pat = re.compile([A-Z][a-z]{2} [A-Z][a-z]{2} \d{,2}\s+\d{,2}:\d{,2}:\d{,2} \d{4},re.M|re.DOTALL) print pat.findall(data) ['Mon Apr 9 22:30:18 2007', 'Mon Apr 9 22:31:10 2007'] -- http://mail.python.org/mailman/listinfo/python-list
Re: split and regexp on textfile
On 13 Apr, 10:40, [EMAIL PROTECTED] wrote: you trying to match the date part right? if re is what you desire, here's one example: Amm..not! I need to get the text-block between the two data, not the data! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from sys.stdin
Hi, Thanks for the responses. My book, Beginning Python: From Novice to Professional(p. 266) says that sys.stdin is iterable, just like other files, so I thought I would test it out. However, I don't see how it is acting similar to a file in my example. I assume all input is buffered by default, so I'm not sure how it explains things to say that input from sys.stdin is buffered. I typed many lines, but lst contains only one item, as expected. Same as your regular file example: the file contains many lines, but only the first goes into the list. Interesting example--not as I expected! But there is a difference in the two examples isn't there? When you iterate over a file, the whole file isn't put into an internal buffer first, is it? I don't know if this a python or OS thing, but I know that iterating over a file is not like applying successive call to readline method. You should try to use readline instead. I've wondered what the differences were. Thanks for bringing that up. I searched around on google, and PEP 234 has this to say about that: - Files implement a tp_iter slot that is equivalent to iter(f.readline, ). This means that we can write for line in file: ... as a shorthand for for line in iter(file.readline, ): ... which is equivalent to, but faster than while 1: line = file.readline() if not line: break ... ... Because the file iterator uses an internal buffer, mixing this with other file operations (e.g. file.readline()) doesn't work right. Also, the following code: for line in file: if line == \n: break for line in file: print line, doesn't work as you might expect, because the iterator created by the second for-loop doesn't take the buffer read-ahead by the first for-loop into account. A correct way to write this is: it = iter(file) for line in it: if line == \n: break for line in it: print line, You may want to look at a related issue: http://www.python.org/sf/1633941 Bad link. This should be f = iter(raw_input,) and this will end in a EOFError and stop on blank line. So you need a wrapper Why a wrapper? This example seems to work without error: lst = [] f = iter(raw_input, ) for line in f: lst.append(line) print lst -- http://mail.python.org/mailman/listinfo/python-list
Try problem
import sys try: s=1 if s==1: sys.exit(0) else: sys.exit(1) except SystemExit,s: if (s==0): print s else: print Hello How come i always end up getting the Hello printed on the screen as logically i should a '0' printed? -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from sys.stdin
7stud wrote: I assume all input is buffered by default, so I'm not sure how it explains things to say that input from sys.stdin is buffered. The difference with sys.stdin is that it has indeterminate length until you signal EOF. I believe you'd get the same problem reading from, say, a named pipe. I typed many lines, but lst contains only one item, as expected. Same as your regular file example: the file contains many lines, but only the first goes into the list. Interesting example--not as I expected! But there is a difference in the two examples isn't there? When you iterate over a file, the whole file isn't put into an internal buffer first, is it? It is if the file is smaller than the buffer size. This should be f = iter(raw_input,) and this will end in a EOFError and stop on blank line. So you need a wrapper Why a wrapper? Because without a wrapper you'll get EOFError, while the file iterator would ordinarily give you StopIteration. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: split and regexp on textfile
On Apr 13, 4:55 pm, Flyzone [EMAIL PROTECTED] wrote: On 13 Apr, 10:40, [EMAIL PROTECTED] wrote: you trying to match the date part right? if re is what you desire, here's one example: Amm..not! I need to get the text-block between the two data, not the data! :) change to pat.split(data) then. I get this: ['', '\ntext\ntext\n', '\ntext\ntext '] -- http://mail.python.org/mailman/listinfo/python-list
Re: Try problem
SamG wrote: import sys try: s=1 if s==1: sys.exit(0) else: sys.exit(1) except SystemExit,s: if (s==0): print s else: print Hello How come i always end up getting the Hello printed on the screen as logically i should a '0' printed? After the exception is raised, s is not an int. It is an exception object. You want s.message. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Try problem
On Apr 13, 5:14 pm, SamG [EMAIL PROTECTED] wrote: import sys try: s=1 if s==1: sys.exit(0) else: sys.exit(1) except SystemExit,s: if (s==0): print s else: print Hello How come i always end up getting the Hello printed on the screen as logically i should a '0' printed? if you put a debug print statement, eg ... except SystemExit,s: print s in exception , s, type(s) if (s==0): you will notice 's' is an instance. so when it reaches the if (s==0), which you are comparing with a number, it will fail and then hello is printed. -- http://mail.python.org/mailman/listinfo/python-list
Re: split and regexp on textfile
On 13 Apr, 11:14, [EMAIL PROTECTED] wrote: change to pat.split(data) then. next what i have tried originally..but is not working, my result is here: [Mon Feb 26 11:25:04 2007\ntext\n text\ntext\nMon Feb 26 11:25:16 2007\ntext\n text\n text\nMon Feb 26 17:06:41 2007\ntext] all together :( -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from sys.stdin
On Apr 13, 3:13 am, Michael Hoffman [EMAIL PROTECTED] wrote: 7stud wrote: I assume all input is buffered by default, so I'm not sure how it explains things to say that input from sys.stdin is buffered. The difference with sys.stdin is that it has indeterminate length until you signal EOF. I believe you'd get the same problem reading from, say, a named pipe. Couldn't you say the same thing about a file you are iterating over? I typed many lines, but lst contains only one item, as expected. Same as your regular file example: the file contains many lines, but only the first goes into the list. Interesting example--not as I expected! But there is a difference in the two examples isn't there? When you iterate over a file, the whole file isn't put into an internal buffer first, is it? It is if the file is smaller than the buffer size. How is that relevant? This should be f = iter(raw_input,) and this will end in a EOFError and stop on blank line. So you need a wrapper Why a wrapper? Because without a wrapper you'll get EOFError, while the file iterator would ordinarily give you StopIteration. Did you run my example? Did you get an error? I don't get an error. -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from sys.stdin
On Apr 13, 3:36 am, 7stud [EMAIL PROTECTED] wrote: It is if the file is smaller than the buffer size. How is that relevant? If I put 100 lines of text in a file with each line having 50 characters, and I run this code: import sys lst = [] for line in open(aaa.txt): print an iteration lst.append(line) break print lst The output is: $ python test1.py an iteration ['helleo haljdfladj ahdflasdjf ds hdljfalsdjfdsljfds \n'] It seems clear to me that the whole file wasn't first read into a buffer before the code started processing the data. -- http://mail.python.org/mailman/listinfo/python-list
Re: split and regexp on textfile
Flyzone: i have a problem with the split function and regexp. I have a file that i want to split using the date as token. My first try: data = error text Mon Apr 9 22:30:18 2007 text text Mon Apr 9 22:31:10 2007 text text Mon Apr 10 22:31:10 2007 text text import re date_find = re.compile(r\d\d:\d\d:\d\d \d{4}$) section = [] for line in data.splitlines(): if date_find.search(line): if section: print \n + - * 10 + \n, \n.join(section) section = [line] else: if line: section.append(line) print \n + - * 10 + \n, \n.join(section) itertools.groupby() is fit to split sequences like: 1000110001110010101 as: 1 000 11 000 111 00 1 0 1 0 1 While here we have a sequence like: 11000101110001 that has to be splitted as: 1 1000 10 1 1 1000 1 A standard itertool can be added for such quite common situation too. Along those lines I have devised this different (and maybe over- engineered) version: from itertools import groupby import re class Splitter(object): # Not tested much def __init__(self, predicate): self.predicate = predicate self.precedent_el = None self.state = True def __call__(self, el): if self.predicate(el): self.state = not self.state self.precedent_el = el return self.state date_find = re.compile(r\d\d:\d\d:\d\d \d{4}$) splitter = Splitter(date_find.search) sections = (\n.join(g) for h,g in groupby(data.splitlines(), key=splitter)) for section in sections: if section: print \n + - * 10 + \n, section The Splitter class + the groupby can become a single simpler generator, like in this this version: def grouper(seq, key=bool): # A fast identity function can be used instead of bool() # Not tested much group = [] for part in seq: if key(part): if group: yield group group = [part] else: group.append(part) yield group import re date_find = re.compile(r\d\d:\d\d:\d\d \d{4}$) for section in grouper(data.splitlines(), date_find.search): print \n + - * 10 + \n, \n.join(section) Maybe that grouper can be modified to manage group lazily, like groupby does, instead of building a true list. Flyzone (seen later): Amm..not! I need to get the text-block between the two data, not the data! :) Then you can modify the code like this: def grouper(seq, key=bool): group = [] for part in seq: if key(part): if group: yield group group = [] # changed else: group.append(part) yield group Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Try problem
On Apr 13, 2:25 pm, [EMAIL PROTECTED] wrote: On Apr 13, 5:14 pm, SamG [EMAIL PROTECTED] wrote: import sys try: s=1 if s==1: sys.exit(0) else: sys.exit(1) except SystemExit,s: if (s==0): print s else: print Hello How come i always end up getting the Hello printed on the screen as logically i should a '0' printed? if you put a debug print statement, eg ... except SystemExit,s: print s in exception , s, type(s) if (s==0): you will notice 's' is an instance. so when it reaches the if (s==0), which you are comparing with a number, it will fail and then hello is printed. Then how do we check the value of the s's instance? -- http://mail.python.org/mailman/listinfo/python-list
Re: split and regexp on textfile
On 13 Apr, 11:30, Flyzone [EMAIL PROTECTED] wrote: all together :( Damn was wrong mine regexp: pat = re.compile([A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ][0-9][ ] [0-9][0-9][:][0-9][0-9],re.M|re.DOTALL) now is working! :) Great! really thanks for the helps! A little question: the pat.split can split without delete the date? -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from sys.stdin
In [EMAIL PROTECTED], 7stud wrote: On Apr 13, 3:36 am, 7stud [EMAIL PROTECTED] wrote: It is if the file is smaller than the buffer size. How is that relevant? If I put 100 lines of text in a file with each line having 50 characters, and I run this code: import sys lst = [] for line in open(aaa.txt): print an iteration lst.append(line) break print lst The output is: $ python test1.py an iteration ['helleo haljdfladj ahdflasdjf ds hdljfalsdjfdsljfds \n'] It seems clear to me that the whole file wasn't first read into a buffer before the code started processing the data. How is that clear to you? Why do you think the file was not loaded completely into a buffer and only the first line from this buffer ends up in `lst`? Let's try this: def main(): test_file = open('test.txt', 'w') for i in xrange(100): test_file.write('%d %s\n' % (i, 'x' * 50)) test_file.close() test_file = open('test.txt', 'r') for line in test_file: print line break print '%s' % test_file.read(75) test_file.close() Output: 0 xx You see the read after the loop doesn't read anything because the file content is in the buffer of the iterator. If the test file has more lines, I tested it with 1000, the output looks like this: 0 xx xx 151 xx 152 x Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
On Apr 13, 8:16 am, Jia Lu [EMAIL PROTECTED] wrote: for m in test: for n in test: for o in test: for p in test: print m+n+o+p Thanx for your anwser. But if I consider about a combination of over 26 letter's list just like: abcdefssdzxcvzxcvzcv asllxcvxcbbedfgdfgdg . Need I write 26 for loops to do this? Thanx Jia LU Try this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502199 You could then write something like: import string for thiscomb in comb2( *([string.lowercase]*26) ): ... Mind you, it generates a lot of combinations. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from sys.stdin
On Apr 13, 2007, at 4:47 AM, 7stud wrote: On Apr 13, 3:36 am, 7stud [EMAIL PROTECTED] wrote: It is if the file is smaller than the buffer size. How is that relevant? If I put 100 lines of text in a file with each line having 50 characters, and I run this code: import sys lst = [] for line in open(aaa.txt): print an iteration lst.append(line) break print lst The output is: $ python test1.py an iteration ['helleo haljdfladj ahdflasdjf ds hdljfalsdjfdsljfds \n'] It seems clear to me that the whole file wasn't first read into a buffer before the code started processing the data. The break statement causes it to bail after the first iteration, so that doesn't really prove your point. For example: lst = [] for line in ['we', 'all live', 'in a yellow', 'submarine']: print an iteration lst.append(line) break print lst The output is: an iteration ['we'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Try problem
SamG schrieb: On Apr 13, 2:25 pm, [EMAIL PROTECTED] wrote: On Apr 13, 5:14 pm, SamG [EMAIL PROTECTED] wrote: import sys try: s=1 if s==1: sys.exit(0) else: sys.exit(1) except SystemExit,s: if (s==0): print s else: print Hello How come i always end up getting the Hello printed on the screen as logically i should a '0' printed? if you put a debug print statement, eg ... except SystemExit,s: print s in exception , s, type(s) if (s==0): you will notice 's' is an instance. so when it reaches the if (s==0), which you are comparing with a number, it will fail and then hello is printed. Then how do we check the value of the s's instance? By not naming the caught exception like a variable you used beforehand? The character 'e' comes to my mind... Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Lists and Tuples and Much More
On Thu, 12 Apr 2007 16:01:51 -0700, bearophileHUGS wrote: [1, 2, 3, 4, 5, 6, [7, 9, 8, 10]] Such sorting may be impossible in Python 3.0 (comparing the order of lists with integers may be seen as meaningless. Otherwise you can see single numbers as lists of len=1, like another language does). And such sorting may be impossible in ten billion years when the sun explodes, but is it really necessary to confuse a newbie who is having problems with basic concepts with what may happen in some future version of Python? It would be one thing if sorting such lists was depreciated, but it isn't, so I think as far as the Original Poster is concerned, that's just muddying the water. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Fri, 13 Apr 2007 07:46:58 +, Antoon Pardon wrote: So much fuss over such a little thing... yes it would be nice if tuples grew an index method, but it isn't hard to work around the lack. Yes it is a little thing. But if it is such a little thing why do the developers don't simply add it? Perhaps because they've got better things to do than spend all their time adding little things that are the work of thirty seconds for a developer like yourself to create when you need it. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Try problem
[EMAIL PROTECTED] a écrit : On Apr 13, 5:14 pm, SamG [EMAIL PROTECTED] wrote: import sys try: s=1 if s==1: sys.exit(0) else: sys.exit(1) except SystemExit,s: if (s==0): print s else: print Hello How come i always end up getting the Hello printed on the screen as logically i should a '0' printed? if you put a debug print statement, eg ... except SystemExit,s: print s in exception , s, type(s) if (s==0): you will notice 's' is an instance. Not with Python 2.5.x (exceptions are now new-style classes too). so when it reaches the if (s==0), which you are comparing with a number, Actually, with an instance of class int. Everything in Python is an object. But the comparison will fail, indeed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang or Hashbang for modules or not?
On Thu, 12 Apr 2007 00:24:12 +0200, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Chris Lasher a écrit : Should a Python module not intended to be executed have shebang/ hashbang (e.g., #!/usr/bin/env python) or not? The shebang is only useful for files that you want to make directly executable on a *n*x system. They are useless on Windows, Probably (unless setup.py uses them for something meaningful there, too). But of course often you don't know that the file will always be used only on Windows, or that the Windows user won't prefer Cygwin. and not technically required to use the file as a main program -ie: you can always run it like this: $ /path/to/python filename.py You can, but sometimes it's not appropriate. If you distribute a Python program to Unix users in that form, they may not want to know or care which language it's written in. Especially if you decide, a few releases later, that you want to switch to Perl or something. I realise that you took a more narrow view than I do above, so please see this as additional notes rather than critisism. It's just that I am struggling with people at work who feel program names should encode whatever language they happen to be written in, and so I am a bit oversensitive ... I'm used to having a shebang in every .py file An encoding declaration might be more useful IMHO !-) They are not mutually exclusive, if that is what you mean. I always use both. /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython, mac, wx.HSCROLL not working
7stud wrote: Thanks. It looks like someone asked the same question yesterday. No -- it looks like I was a bit stressed and the first google hit or a direct jump to wxpython.org would have provided the solution :) Regards, Björn -- BOFH excuse #14: sounds like a Windows problem, try calling Microsoft support -- http://mail.python.org/mailman/listinfo/python-list
Re: Lists and Tuples and Much More
7stud [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Yes. Tuples are immutable - once created, they can't change. Just to explain that statement a little better. If you do this: t = (1, 2, [red, white]) t[2].append(purple) print t#(1, 2, ['red', 'white', 'purple']) It sure looks like t changed, and therefore t is NOT immutable--and the whole tuples are immutable mantra is a lie. However, the list itself isn't actually stored inside t. What's stored inside t is python's internal id for the list. So suppose python gave the list the internal id: 10008. The tuple really looks like this: t = (1, 2, 10008) And no matter what you do to the list: append() to it, sort() it, etc., the list's id remains the same. In that sense, the tuple is immutable because the id stored in the tuple never changes. In actuality, the numbers 1 and 2 aren't stored in the list either-- python has internal id's for them too, so the tuple actually looks like this: t = (56687, 93413, 10008) | || | || | || V VV 1 2[red, white, purple] Because of that structure, you can create situations like this: lst = [red, white] t1 = (1, 2, lst) t2 = (15, 16, lst) print t1 (1, 2, ['red', 'white']) print t2 (15, 16, ['red', 'white']) lst.append(purple) print lst ['red', 'white', 'purple'] print t1 (1, 2, ['red', 'white', 'purple']) print t2 (15, 16, ['red', 'white', 'purple']) lst, t1, and t2 all refer to the same list, so when you change the list, they all see that change. In other words, the names lst, t1[2], and t2[2] all were assigned the same python id for the original list [red, white]. Since all those names refer to the same list, any of those names can be used to change the list. * This is exactly the type of explaination I'm looking for. Thank you much!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython, mac, wx.HSCROLL not working
On Apr 13, 4:54 am, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: 7stud wrote: Thanks. It looks like someone asked the same question yesterday. No -- it looks like I was a bit stressed and the first google hit or a direct jump to wxpython.org would have provided the solution :) Huh? Are you saying you found a solution? -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang or Hashbang for modules or not?
On 13 Apr 2007 10:54:18 GMT, Jorgen Grahn [EMAIL PROTECTED] wrote: On Thu, 12 Apr 2007 00:24:12 +0200, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Chris Lasher a écrit : Should a Python module not intended to be executed have shebang/ hashbang (e.g., #!/usr/bin/env python) or not? The shebang is only useful for files that you want to make directly executable on a *n*x system. They are useless on Windows, Probably (unless setup.py uses them for something meaningful there, too). There's another, secondary, reason to use a shebang on Python source which isn't executable: the Unix file(1) command and friends can see that it's Python code. (Of course, such files will almost always be named foo.py.) /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading the first line of a file (in a zipfile)
On Apr 11, 4:20 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 11 Apr 2007 17:15:48 -0300, [EMAIL PROTECTED] escribió: The file contents have leading whitespace, then a number: 123456 \n I expect to return '123456' And nothing following the number? py line = 123456 \n py print line.strip() 123456 -- Gabriel Genellina That works fine if I am using the interpreter, but I get 'cannot open file' when i try to read from an archive.. Does that make sense? Sorry, this is my 2nd python script. -- http://mail.python.org/mailman/listinfo/python-list
Arrays, Got Me Confused
Hello Guys, I'm struggling to get my head into arrays in python, I've used them plenty in other languages but I'm struggling to find any decent documentation for them in python. I'm looking to build a list of network MAC address's into an array, which will probably be used for logging and firewalling and things. I've build the basic class, the idea is that the class represents the firewall, and I have functions for the firewall like addDevice() and isFirewalled() where I pass in the address and it returns a value or updates the array. However I'm getting an error when trying to create an empty array on the init. #!/usr/bin/python # Filename: Firewall.py class Firewall: def __init__(self): Self.FireArray = array(c) p = Firewall() print p Throws: Traceback (most recent call last): File ./firewall.py, line 9, in ? p = Firewall() File ./firewall.py, line 7, in __init__ Self.FireArray = array(c) NameError: global name 'array' is not defined How can I solve this problem? From what I've seen writing I can't see anything wrong with my syntax, perhaps you can shed some light on the situation. Whilst I'm writing there is also another question I would like to pose briefly. How do a create an object from an external file? Obviously in my one above all I need do is call Firewall() and it creates an instance, but I'm used to creating my class's as separate files, how do I create them as an object in my main application? Thanks, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Arrays, Got Me Confused
On Apr 13, 2007, at 7:04 AM, Robert Rawlins - Think Blue wrote: #!/usr/bin/python # Filename: Firewall.py class Firewall: def __init__(self): Self.FireArray = array(c) p = Firewall() print p Throws: Traceback (most recent call last): File ./firewall.py, line 9, in ? p = Firewall() File ./firewall.py, line 7, in __init__ Self.FireArray = array(c) NameError: global name 'array' is not defined How can I solve this problem? from array import array -- http://mail.python.org/mailman/listinfo/python-list
Re: Arrays, Got Me Confused
HI, You will have to import Numeric module Add from Numeric import * to the script For the second question: Suppose you wrote the code for your class in firewall.py and your main script is main.py Put the file firewall.py in the directory where you have main.py Then in main.py do : import firewall.py To create an object of class Firewall firewallDemo=firewall.Firewall() May be this will help On 4/13/07, Robert Rawlins - Think Blue [EMAIL PROTECTED] wrote: Hello Guys, I'm struggling to get my head into arrays in python, I've used them plenty in other languages but I'm struggling to find any decent documentation for them in python. I'm looking to build a list of network MAC address's into an array, which will probably be used for logging and firewalling and things. I've build the basic class, the idea is that the class represents the firewall, and I have functions for the firewall like addDevice() and isFirewalled() where I pass in the address and it returns a value or updates the array. However I'm getting an error when trying to create an empty array on the init. #!/usr/bin/python # Filename: Firewall.py class Firewall: def __init__(self): Self.FireArray = array(c) p = Firewall() print p Throws: Traceback (most recent call last): File ./firewall.py, line 9, in ? p = Firewall() File ./firewall.py, line 7, in __init__ Self.FireArray = array(c) NameError: global name 'array' is not defined How can I solve this problem? From what I've seen writing I can't see anything wrong with my syntax, perhaps you can shed some light on the situation. Whilst I'm writing there is also another question I would like to pose briefly. How do a create an object from an external file? Obviously in my one above all I need do is call Firewall() and it creates an instance, but I'm used to creating my class's as separate files, how do I create them as an object in my main application? Thanks, Rob -- http://mail.python.org/mailman/listinfo/python-list -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from sys.stdin
7stud wrote: On Apr 13, 3:13 am, Michael Hoffman [EMAIL PROTECTED] wrote: 7stud wrote: I assume all input is buffered by default, so I'm not sure how it explains things to say that input from sys.stdin is buffered. The difference with sys.stdin is that it has indeterminate length until you signal EOF. I believe you'd get the same problem reading from, say, a named pipe. Couldn't you say the same thing about a file you are iterating over? Only if the file has indeterminate length. Regular files have a length. This should be f = iter(raw_input,) and this will end in a EOFError and stop on blank line. So you need a wrapper Why a wrapper? Because without a wrapper you'll get EOFError, while the file iterator would ordinarily give you StopIteration. Did you run my example? Did you get an error? I don't get an error. Yes I did. I did get an error. lst = [] f = iter(raw_input, ) for line in f: ... lst.append(line) ... abc def Ctrl-DTraceback (most recent call last): File stdin, line 1, in module EOFError -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
azrael wrote: I think that this would be very silly to do. bad kung foo. The recoursion technique would be more satisfying. You sholud consider that this would take about 4 lines to write. Also be avare of the default recoursion depth in python wich is 1000. you can get and set the recoursion limit hrough importing the sys module and using getrecoursionlimit() and setrecoursionlimit(). Well, you'd have to spell sys.getrecursionlimit() correctly, but yes ;) At least in the past, raising the recursion limit past a certain point would result in the CPython interpreter crashing, so it's not completely scalable. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Arrays, Got Me Confused
Michael Bentley wrote: On Apr 13, 2007, at 7:04 AM, Robert Rawlins - Think Blue wrote: #!/usr/bin/python # Filename: Firewall.py class Firewall: def __init__(self): Self.FireArray = array(c) p = Firewall() print p Throws: Traceback (most recent call last): File ./firewall.py, line 9, in ? p = Firewall() File ./firewall.py, line 7, in __init__ Self.FireArray = array(c) NameError: global name 'array' is not defined How can I solve this problem? from array import array Well, also the line referencing Self.FireArray is not going to work, unless there's some global Self knocking around. Python is case-sensitive. More importantly, I suspect, is that the OP's almost certainly looking for a Python *list*, not an array in this case. It's hard to tell, since we've no idea what's in the c which is being passed to the array. Robert - can you explain what you're trying to do and/or post a wider fragment of code? TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP PARAMETERS IN SQL QUERY
pierre-yves guido wrote: hello, I'm doing a training course and I'm a newbie in Python. My problem : I have a form, and when I click, I make an update. But all the parameters are all required to make the update. So I'd like to put in my code something like [optional]... My code (simplyfied) : prg.ev_ind_update(wf_pk_ev_ind=wf_pk_ev_ind,wf_fonction=wf_fonction,wf_nom=wf_nom) and so, when I put nothing in wf_nom, it put me that error :the parameter wf_nom...was omitted from the request But sometimes, wf_nom is not required ! Thanks for your help user None? Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite3 question
Thanks, This is how I did it in the end as well. Yes i use the connection object, abbreviated as 'c' for ease of typing. In my real app the connection is kept inside a singleton object and I use the DB like result = GuitarDB().connection.execute('select * from song where id = 1').fetchone() if result: print 'Found a song' else: print 'Found nothing' I know there will always be a cursor object back from connection.execute, so for ease of use and sparing a temp var, I put the .fetchone() behind the connection.execute() Thanks everyone for their help! - Jorgen On 4/12/07, Carsten Haese [EMAIL PROTECTED] wrote: On Thu, 2007-04-12 at 13:43 +0200, Marc 'BlackJack' Rintsch wrote: In [EMAIL PROTECTED], Jorgen Bodde wrote: r = c.execute('select * from song where id = 1') for s in r: ... print s ... (1, u'Spikedrivers Blues', u'Mississippi John Hurt') That works. But when I can't restore the row by e.g. an ID that does not exist, I cannot see any method in 'r' (which is a SQLite.Cursor) that can tell me if I have rows. As explained in the help, r.rowcount does not give a valid result because it can't determine how many rows are restored in advance. This should not work because `r` should not be a `Cursor` object. The `execute()`-Method returns an integer with the number of affected rows. It does work if 'c' is a connection object with a poorly chosen name. According to http://docs.python.org/lib/sqlite3-Connection-Objects.html , sqlite3 connection objects have a non-standard execute method that creates a cursor, executes a query on that cursor, and returns that cursor. Anyway, if you expect a query to return at most one row, such as when you're filtering on the table's primary key, this is how I would do it: cur.execute(select * from song where id = ?, (wanted_id,) ) song_row = cur.fetchone() if song_row: # Do something with song_row else: # Song not found HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list On 4/12/07, Carsten Haese [EMAIL PROTECTED] wrote: On Thu, 2007-04-12 at 13:43 +0200, Marc 'BlackJack' Rintsch wrote: In [EMAIL PROTECTED], Jorgen Bodde wrote: r = c.execute('select * from song where id = 1') for s in r: ... print s ... (1, u'Spikedrivers Blues', u'Mississippi John Hurt') That works. But when I can't restore the row by e.g. an ID that does not exist, I cannot see any method in 'r' (which is a SQLite.Cursor) that can tell me if I have rows. As explained in the help, r.rowcount does not give a valid result because it can't determine how many rows are restored in advance. This should not work because `r` should not be a `Cursor` object. The `execute()`-Method returns an integer with the number of affected rows. It does work if 'c' is a connection object with a poorly chosen name. According to http://docs.python.org/lib/sqlite3-Connection-Objects.html , sqlite3 connection objects have a non-standard execute method that creates a cursor, executes a query on that cursor, and returns that cursor. Anyway, if you expect a query to return at most one row, such as when you're filtering on the table's primary key, this is how I would do it: cur.execute(select * from song where id = ?, (wanted_id,) ) song_row = cur.fetchone() if song_row: # Do something with song_row else: # Song not found HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Cloning file attributes and permissions
If you know what the permissions are going to be then you can use umask to set the default file creation permissions to match. Then any files created in that directory will have the correct permissions. I think the pythonic way to solve this problem would be to code up your own module which handles all the dirty parts in the background. It would create the new file, stat the original, and chmod/chown the new file as needed to match the original. All you would have to do after creating the module is pass the new function the original and new file information. -- Kevin Kelley On 4/12/07, Paulo da Silva [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] escreveu: On Apr 12, 5:19 pm, [EMAIL PROTECTED] wrote: On Apr 12, 4:09 pm, Paulo da Silva [EMAIL PROTECTED] wrote: ... After poking around a bit I also discovered the shutil module. It looks like you can use shutil.copy2. More Pythonic, yes? I have seen that in the index but I thought it was a different thing because it was referenced as high-level operations. Anyway that helps but I still need to copy the whole file or to use stat and chown for the user/group ids. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Function arguments [was: help]
pierre-yves guido wrote: hello (I hope my english is not so bad), Your English is quite good. In future, though, please try to make your subject line say a bit more about the problem - we *all* need help! I'm doing a training course and I'm a newbie in Python. My problem : I have a form, and when I click, I make an update. But all the parameters are all required to make the update. So I'd like to put in my code something like [optional]... My code (simplyfied) : prg.ev_ind_update(wf_pk_ev_ind=wf_pk_ev_ind,wf_fonction=wf_fonction,wf_nom=wf_nom) and so, when I put nothing in wf_nom, it put me that error :the parameter wf_nom...was omitted from the request But sometimes, wf_nom is not required ! Thanks to help a poor young boy When you define a function or a method (using the def statement) you can specify default values for arguments. A simple example: def fun(a, b=3): ... return a*b ... fun(3) 9 fun(7) 21 fun(7, 4) 28 fun(a=7) 21 fun(a=3, b=12) 36 fun(b=99) Traceback (most recent call last): File stdin, line 1, in module TypeError: fun() takes at least 1 non-keyword argument (0 given) You can see several things here: 1. When you call a function you do not *have* to give thte names of the arguments - they can be matched by position. 2. When you define a function you can specify a default value for one or more arguments (these argument have to appear *after* the ones for which no default is defined) 3. If you don't provide a value for an argument that has no default then you will receive an exception, which normally results in a traceback. Hope this helps. Welcome to Python, and its friendly community. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: treating str as unicode in legacy code?
Ben wrote: I'm left with some legacy code using plain old str, and I need to make sure it works with unicode input/output. I have a simple plan to do this: - Run the code with python -U so all the string literals become unicode litrals. - Add this statement str = unicode to all .py files so the type comparison (e.g., type('123') == str) would work. Did I miss anything? Does this sound like a workable plan? Thanks! Well, don't forget that the assignment to str *shadows* the built-in rather than replacing it, so there may be places (imported modules being the example that most readily springs to mind) where that replacement won't be effective. Plus which in CPython the C parts of the code may well be creating and expecting objects of type str but they won't use the Python naming mechanism at all, so you will have no way to effect changes in those behaviors. This will probably account for about 95% of any strangeness you see, but it's probably a good first step in the conversion process. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Arrays, Got Me Confused
Hello Guys, Wider fragments of code don't really exists at this moment in time :-D this is just a bit of a 'tester' class for me to get used to the methods. Basically I'm trying to create a class that contains an array of MAC address, these look something like this 'FD:E4:55:00:FG:A9. I want the class to have the following methods for easy manipulation of the array. addDevice(Address) - Pass in the MAC address and have it add it to the array. removeDevice(Address) - Finds a device with that address in the array and removes it. isFirewalled(Address) - looks for that address in the array and returns true/false dependant on whether it finds it. Clear() - empty the array of all its contents. Sorry for the sloppy code so far, I'm really new to Python so it's a steep learning curve for me, I'm by no means a programming numpty and allot of the principles are the same, but the languages I'm used to are more robust and vague so I don't have to define what type of data i'm storing the array and things. Thanks guys, Rob -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Tim Golden Sent: 13 April 2007 13:27 Cc: [EMAIL PROTECTED] Subject: Re: Arrays, Got Me Confused Michael Bentley wrote: On Apr 13, 2007, at 7:04 AM, Robert Rawlins - Think Blue wrote: #!/usr/bin/python # Filename: Firewall.py class Firewall: def __init__(self): Self.FireArray = array(c) p = Firewall() print p Throws: Traceback (most recent call last): File ./firewall.py, line 9, in ? p = Firewall() File ./firewall.py, line 7, in __init__ Self.FireArray = array(c) NameError: global name 'array' is not defined How can I solve this problem? from array import array Well, also the line referencing Self.FireArray is not going to work, unless there's some global Self knocking around. Python is case-sensitive. More importantly, I suspect, is that the OP's almost certainly looking for a Python *list*, not an array in this case. It's hard to tell, since we've no idea what's in the c which is being passed to the array. Robert - can you explain what you're trying to do and/or post a wider fragment of code? TJG -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with the get() method of a Text entry
Chad wrote: On Apr 12, 5:03 pm, James Stroud [EMAIL PROTECTED] wrote: James Stroud wrote: Chad wrote: I have a simple little program that brings up asks the user to enter a note, then is supposed to place that note into a text file when the user hits the submit button. However, when the user hits the submit button, absolutely nothing happens. IDLE doesn't give an error message and the note is not entered into the text file. For troubleshooting puposes, I wanted to see if IDLE would at least print the user's input; it doesn't do that either. Can someone please help me? [...] [James second-guesses himself twice] Thank you, that worked very well. I thought it was particularly helpful of James to do the debugging for you without waiting for you to point out the errors in his first and second submissions. You just don't *get* help like that most places nowadays. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
list of datasaources with pyodbc
How do I get a list of datasources with pyodbc? I know that with mx.ODBC.Windows I can use the DataSources method to get a dictionay containing the datasources. Is there a similar way to do this with pyodbc? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: VB6 To Python
Michael Bentley wrote: On Apr 12, 2007, at 1:11 PM, Sampson, David wrote: Any experience or insight would be great. It has been my experience that when migrating to a dissimilar system, avoiding the rewrite is a mistake. And futile. This is good advice. Since your original project had such a clean separation between GUI code and the rest of the logic, however, you might want to investigate the methods discussed in Robinson and Hammond's Programming Win32 in Python, where they explain how Python logic can make use of COM interfaces to interact with VB (or other COM) GUIs. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Arrays, Got Me Confused
Robert Rawlins - Think Blue wrote: Hello Guys, Wider fragments of code don't really exists at this moment in time :-D this is just a bit of a 'tester' class for me to get used to the methods. Basically I'm trying to create a class that contains an array of MAC address, these look something like this 'FD:E4:55:00:FG:A9. I want the class to have the following methods for easy manipulation of the array. addDevice(Address) - Pass in the MAC address and have it add it to the array. removeDevice(Address) - Finds a device with that address in the array and removes it. isFirewalled(Address) - looks for that address in the array and returns true/false dependant on whether it finds it. Clear() - empty the array of all its contents. OK, it's easy enough to do this, but you might find that you don't actually need to do too much of it yourself. Python has two central datastructures built in: lists and dictionaries. There are loads of tutorials around (and if you join the python-tutor list, the welcome message points you towards several) so I won't go into the details, but it looks like you want a dict here. You could wrap it in a class if you wanted, but the great thing about Python is that you don't have to. *Very* rough example code: code macs = {} # create an empty dict incoming_mac = 'FD:E4:55:00:FG:A9' macs[incoming_mac] = True example_mac = 'a:b:c:d' if example_mac in macs: mac_is_firewalled = macs[example_mac] /code If you really wanted to go with a class (for the exercise or because of wider requirements) you could do something like this: code class Firewalled: def __init__ (self): self.macs = {} def addDevice (address): self.macs[address] = True def removeDevice (address): del self.macs[address] def isFirewalled (address): return address in self.macs # or return self.macs.get (address, False) /code but as you can see, in this form you're just wrapping Python with Python. Sorry for the sloppy code so far, I'm really new to Python so it's a steep learning curve for me, I'm by no means a programming numpty and allot of the principles are the same, but the languages I'm used to are more robust and vague so I don't have to define what type of data i'm storing the array and things. Ummm... in Python you don't have to define what type of data you're storing. Welcome to the language in any case: you'll find that people around here are generally quite friendly but if you want, you might try the tutor list where people are very used to dealing with newcomers: http://mail.python.org/mailman/listinfo/tutor TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Arrays, Got Me Confused
Robert Rawlins - Think Blue [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Wider fragments of code don't really exists at this moment in time No but specifying the problem too narrowly tends to get you an unidiomatic solution. Basically I'm trying to create a class that contains an array of MAC address, these look something like this 'FD:E4:55:00:FG:A9. You rarely want to use 'array' in the standard library; there are some use cases for it but they are rare. More often you want to use the list type. However, here you really want to use a set: having decided that, the code is so trivial, it's hardly worth making a new class. s = set() s.add('FD:E4:55:00:FG:A9') s.remove('FD:E4:55:00:FG:A9') s = set() s.add('FD:E4:55:00:FG:A9') 'FD:E4:55:00:FG:A9' in s True s.remove('FD:E4:55:00:FG:A9') 'FD:E4:55:00:FG:A9' in s False s.clear() Of course, you might want to add sanity checks like 'G' is not a hex digit in a real implementation. -- http://mail.python.org/mailman/listinfo/python-list
Re: favourite IDE
azrael wrote: Some time ago I posted a question about the favourite IDE. I finally found it. WING IDE i the best I've ever seen for python. Code completition is amazing, automated help, python comand line. evrything i need. Who didnt try, doesnt know what he is missing. just one word: Amazing respect to the developers While I too am a (very happy) Wing user I feel I should remind everyone that best here is a misleading term for two reasons: 1. Evaluations like this are notoriously subjective, and 2. Any IDE has many dimensions, so they can't be laid out on a linear path between worst and best. Having said this, I *am* looking forward to using the new features in 3.0 for debugging threaded code. That sounds like a major step forward. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Arrays, Got Me Confused
On Fri, 2007-04-13 at 13:50 +0100, Robert Rawlins - Think Blue wrote: Hello Guys, Wider fragments of code don't really exists at this moment in time :-D this is just a bit of a 'tester' class for me to get used to the methods. Basically I'm trying to create a class that contains an array of MAC address, these look something like this 'FD:E4:55:00:FG:A9. I want the class to have the following methods for easy manipulation of the array. addDevice(Address) - Pass in the MAC address and have it add it to the array. removeDevice(Address) - Finds a device with that address in the array and removes it. isFirewalled(Address) - looks for that address in the array and returns true/false dependant on whether it finds it. Clear() - empty the array of all its contents. Unless your class is going to grow more hair than what you specify above, such as the ability to specify ranges of addresses, I think you'll want to use a set. See http://docs.python.org/lib/types-set.html HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Creating Lists
Scott wrote: Please forgo the psychological self analysis from your future posts. Unfortunately I can't, that's how I am, love it or leave it. But if your going to be condescending about it, please leave your future replies in your outbox. Now don't take that as I don't appreciate your reply. I just don't appreciate the tone of that statement. I wouldn't say something about your pseudonym possibly making up for some personal deficiency only because it wouldn't be right. Email etiquette is a beautiful thing. And that's a really sideways way to take a swipe at someone while pretending to be too high-minded to do it (plus see James's comments about other possible explanations). If you kiddies would take this fight out into the playground perhaps the rest of the class can continue. It *would* be helpful if you just asked the question. You said in your original post that ... I need to know the petty just because I need to know, but that's an abuse of the word need unless you suffer from a quite unusual psychological compulsion. Another psychological compulsion, of course, is the inability to ignore the irrelevant in other people's posts. The two apparently don't combine well. And I'm sorry if you didn't mean it that way, but that's the way it read. To you. Get over it, this is Usenet. You will experience worse if you stick at it long enough. I don't think your question has anything to do with lists. Maybe this will help: there is a distinction between what are called literals and variables. My question was in fact about lists and their proper syntax (I'm guessing that's the right word). Basically all I was asking was if I had the idea down or not, which was meant to be implied when I wrote: Am I safe in assuming Maybe I didn't write it the exact way to get the response I needed, and if it read differently I'm sorry. But that's all I was asking. You can't really separate the syntax of lists from the syntax of the rest of Python. Maybe you didn't mean syntax, it's hard to know. There are, as has been pointed out, names and values. Names are references to values. So after you say five = 5 the following conditions are true: [1, 2, 3, 4, 5] == [1, 2, 3, 4, five] [1, 2, 3, 4, 'five'] != [1, 2, 3, 4, five] Then execute five = 'five' and the truth value of both conditions flips, so the first is false and the second is true. The value referenced by the name five changes as new values are assigned (in Python we tend to prefer to say bound, to remind us that names are really references) to it. The values represented by the literals 5 and 'five' will never change. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: where to report bug/get help for wxpython
On Apr 12, 9:35 pm, alf [EMAIL PROTECTED] wrote: Hi, I have another problem with wxpython - that is the best place to report bug - evident memory leak on Linux and win32. -- alf You'll need to go to the official wxPython website, here: http://wxpython.org/ There's a link to the mailing list (for help) and a link on how to report a bug. I would recommend reporting your problem to the users group mailing list first to find out if your problem is a known bug or not. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: where to report bug/get help for wxpython
alf wrote: Hi, I have another problem with wxpython - that is the best place to report bug - evident memory leak on Linux and win32. Google for wxpython mailing list and see if you still need help after that. Bug reports on c.l.py will almost certainly go unregarded. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Cloning file attributes and permissions
This is what I (just now) put together as an example: from os import stat,mknod,chown def match_perms(org_fname,new_fname): # Get information on old file st = stat(org_fname) st_mode = st.st_mode st_uid = st.st_uid st_gid = st.st_gid # Create the new file mknod(new_fname,st_mode) # Matching permissions chown(new_fname,st_uid,st_gid) if __name__ == __main__: match_perms('old_filename','new_filename') On 4/13/07, Kevin Kelley [EMAIL PROTECTED] wrote: If you know what the permissions are going to be then you can use umask to set the default file creation permissions to match. Then any files created in that directory will have the correct permissions. I think the pythonic way to solve this problem would be to code up your own module which handles all the dirty parts in the background. It would create the new file, stat the original, and chmod/chown the new file as needed to match the original. All you would have to do after creating the module is pass the new function the original and new file information. -- Kevin Kelley On 4/12/07, Paulo da Silva [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] escreveu: On Apr 12, 5:19 pm, [EMAIL PROTECTED] wrote: On Apr 12, 4:09 pm, Paulo da Silva [EMAIL PROTECTED] wrote: ... After poking around a bit I also discovered the shutil module. It looks like you can use shutil.copy2. More Pythonic, yes? I have seen that in the index but I thought it was a different thing because it was referenced as high-level operations. Anyway that helps but I still need to copy the whole file or to use stat and chown for the user/group ids. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Arrays, Got Me Confused
Thanks for that Tim and Steve, greatly appreciated. I know that the class method is just a wrapper and it seems a little silly, but it is partly for the exercise. I'm pretty well savvy with the OOP stuff but its something my business partner is yet to venture into, so by working like this it helps him understand the concepts. I also feel more at home if i can wrap this stuff up in nice user friendly methods that I can access universally throughout the application. I will have plenty of other class's and methods throughout the application that will call upon this firewall stuff, and being able to universally reference it as Firewall.addDevice() makes things more logical in my mind, I find trying to go back to a more procedural method pretty tricky now. Thanks again guys, Rob -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Tim Golden Sent: 13 April 2007 14:03 Cc: [EMAIL PROTECTED] Subject: Re: Arrays, Got Me Confused Robert Rawlins - Think Blue wrote: Hello Guys, Wider fragments of code don't really exists at this moment in time :-D this is just a bit of a 'tester' class for me to get used to the methods. Basically I'm trying to create a class that contains an array of MAC address, these look something like this 'FD:E4:55:00:FG:A9. I want the class to have the following methods for easy manipulation of the array. addDevice(Address) - Pass in the MAC address and have it add it to the array. removeDevice(Address) - Finds a device with that address in the array and removes it. isFirewalled(Address) - looks for that address in the array and returns true/false dependant on whether it finds it. Clear() - empty the array of all its contents. OK, it's easy enough to do this, but you might find that you don't actually need to do too much of it yourself. Python has two central datastructures built in: lists and dictionaries. There are loads of tutorials around (and if you join the python-tutor list, the welcome message points you towards several) so I won't go into the details, but it looks like you want a dict here. You could wrap it in a class if you wanted, but the great thing about Python is that you don't have to. *Very* rough example code: code macs = {} # create an empty dict incoming_mac = 'FD:E4:55:00:FG:A9' macs[incoming_mac] = True example_mac = 'a:b:c:d' if example_mac in macs: mac_is_firewalled = macs[example_mac] /code If you really wanted to go with a class (for the exercise or because of wider requirements) you could do something like this: code class Firewalled: def __init__ (self): self.macs = {} def addDevice (address): self.macs[address] = True def removeDevice (address): del self.macs[address] def isFirewalled (address): return address in self.macs # or return self.macs.get (address, False) /code but as you can see, in this form you're just wrapping Python with Python. Sorry for the sloppy code so far, I'm really new to Python so it's a steep learning curve for me, I'm by no means a programming numpty and allot of the principles are the same, but the languages I'm used to are more robust and vague so I don't have to define what type of data i'm storing the array and things. Ummm... in Python you don't have to define what type of data you're storing. Welcome to the language in any case: you'll find that people around here are generally quite friendly but if you want, you might try the tutor list where people are very used to dealing with newcomers: http://mail.python.org/mailman/listinfo/tutor TJG -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting Stack Trace on segfault
GDB would could work. Here's how I use it to track down problems in a C ++ program controlled by python. $ gdb python GDB starts up, now at the gdb prompt, set the program args (gdb) set arg testscript.py (gdb) run ... program running until crash (gdb) where gives you the backtrace if you compiled you're module code with debug options Cheers! Bernhard On Apr 11, 10:51 pm, [EMAIL PROTECTED] (John J. Lee) wrote: James Stroud [EMAIL PROTECTED] writes: Hello All, The built-in mac osx vecLib is segfaulting in some cases--A very fun fact to find out the hard way over two nights of work. I also spent an embarrassing amount of time figuring out just where. Although I'm in quite a self-congratulatory mood right now, in the future, I feel like I could save a lot of time by coercing the interpreter to spew forth method calls to stderr. Is this possible? I would hope to produce something hauntingly reminiscent of [] my_function [my_function] another_function [my_function - another_function] yet_a_deeper_function [...] I remember David Beazley (of SWIG fame) wrote something called WAD that claimed to turn segfaults into Python exceptions (hence tracebacks). IIRC it was Linux-specific, and I have no idea how it worked. I guess it could be ported to Windows with SEH, but no idea about OS X. John -- http://mail.python.org/mailman/listinfo/python-list
Re: mx.ODBC minor problem
Greg Corradini wrote: Hello all, In a script i just wrote, my code calls a function createTables(), which checks for an existing table and then creates it, and then immediately calls selectSQL(), which selects from a different table and inserts on the table I just created (see below). However, I continue to get an Interface Error (see below) when i run it. And yet, if I allow the code to call createTables() and then manually call selectSQL() after a couple seconds, the thing works fine. In short, there's no mismatch in the number of parameters. Why would this be? I've never experienced this before. How can i restructure my code to resolve this problem? --- CODE --- def createTables(): # Drop AddScript Table try: curse.execute('Drop table ' +countyname+'ADD_SCRIPT_TABLE') conn.commit It may not make any difference, but you should *call* commit() in the statement above rather than just referencing it. except: pass # Create AddScript Table curse.execute('Create table ' +countyname+'ADD_SCRIPT_TABLE'+ ' (TISCODE TEXT(12), STATUS TEXT(4))') conn.commit() def selectSQL(): sql = Select TISCODE,STATUS from +countyname+0+ where STATUS = 'AS' curse.execute(sql) a = curse.fetchall() curse.executemany('Insert into ' +countyname+'ADD_SCRIPT_TABLE'+ ' (TISCODE,STATUS) values (?,?)',x) Shouldn't the second argument to executemany() be a, not x? conn.commit() --- ERROR --- InterfaceError: mismatch in number of parameters; expected 2, found none I find this whole thing a little disturbing. I keep asking myself why you are apparently maintaining entirely separate data structures for each county instead of having the county as a data item that can be used to select appropriate rows in the normal SQL way. I suspect the correct way to proceed otherwise is to rectify the database design before going too much further. If there is any intention to be able to compare data across different counties, for example, you will be dead in the water doing it this way. If this is someone else's crappy database design that you are obliged to deal with then please accept my apologies. If it's your crappy design then fix it ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
sorry for the bad grammar. I didn't investigate the StackLess Python, but as I have been reading about it (so if it was correct), the recursionlimit should not be the problem using StackLess Python. From my expirience with python and recursions, it works well to the depth of about 200 to 500 (depending od algorithm and purpose). I think that in this case it should work well with about 500. If you need a bigger string, then lett it repeat and merge the different strings. You could also generate multidimensional hash. Best Regards On Apr 13, 2:24 pm, Michael Hoffman [EMAIL PROTECTED] wrote: azrael wrote: I think that this would be very silly to do. bad kung foo. The recoursion technique would be more satisfying. You sholud consider that this would take about 4 lines to write. Also be avare of the default recoursion depth in python wich is 1000. you can get and set the recoursion limit hrough importing the sys module and using getrecoursionlimit() and setrecoursionlimit(). Well, you'd have to spell sys.getrecursionlimit() correctly, but yes ;) At least in the past, raising the recursion limit past a certain point would result in the CPython interpreter crashing, so it's not completely scalable. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: split and regexp on textfile
On Apr 13, 6:08 pm, Flyzone [EMAIL PROTECTED] wrote: On 13 Apr, 11:30, Flyzone [EMAIL PROTECTED] wrote: all together :( Damn was wrong mine regexp: pat = re.compile([A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ][0-9][ ] [0-9][0-9][:][0-9][0-9],re.M|re.DOTALL) now is working! :) Great! really thanks for the helps! A little question: the pat.split can split without delete the date? not that i know of. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
Jia Lu wrote: for m in test: for n in test: for o in test: for p in test: print m+n+o+p Thanx for your anwser. But if I consider about a combination of over 26 letter's list just like: abcdefssdzxcvzxcvzcv asllxcvxcbbedfgdfgdg . Need I write 26 for loops to do this? Thanx Jia LU Your new example uses 20-byte strings anyway, so to produce those using the specified method you would need 20 nested for loops, not 26. I'm pretty sure you could give a separate name to each atom ont he known universe with a scheme like this. Do you really need 20-byte strings? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
On Apr 13, 8:53 am, Steve Holden [EMAIL PROTECTED] wrote: Jia Lu wrote: for m in test: for n in test: for o in test: for p in test: print m+n+o+p Thanx for your anwser. But if I consider about a combination of over 26 letter's list just like: abcdefssdzxcvzxcvzcv asllxcvxcbbedfgdfgdg . Need I write 26 for loops to do this? Thanx Jia LU Your new example uses 20-byte strings anyway, so to produce those using the specified method you would need 20 nested for loops, not 26. I'm pretty sure you could give a separate name to each atom ont he known universe with a scheme like this. Do you really need 20-byte strings? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenwebhttp://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com- Hide quoted text - - Show quoted text - If you just expand the length to five million* or so, one of those strings will contain all the works of Shakespeare. -- Paul * ref: Project Gutenberg - http://www.gutenberg.org/etext/100 - unzipped plaintext is ~5.3Mb -- http://mail.python.org/mailman/listinfo/python-list
Re: Using python to delta-load files into a central DB
Gabriel, I think that would work well. Also, thank you for suggesting the use of filecmp. I have never used this module, but it looks like a much better solution than what I had been doing previously--using os.stat and performing a DB lookup in order to verify that the filename and timestamp existed in a 'file update' table. Also, if the only limitation to difflib is that both files reside in memory, I should be fine. The largest of all of these files is just over 200k, which should be fine. If memory serves me right, I can't use more than 4MB, so I should be fine. And, if I spawn separate processes for generating the delta files, I should be able to speed things up even more. Thanks again for your help! Best Regards, Christopher Nethery Gabriel Genellina [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] En Thu, 12 Apr 2007 23:51:22 -0300, Chris Nethery [EMAIL PROTECTED] escribió: Yes, they are tab-delimited text files that will change very little throughout the day. But, this is messy, antiquated 80s junk, nonetheless. Ugh... Rows are designated either by a row type or they contain a comment. Each row type has an identity value, but the 'comment' rows do not. The comment rows, however, are logically associated with the last occurring row type. When I generate my bulk insert file, I add the identity of the last occurring row type to the comment rows, and generate and populate an additional identity column in order to retain the order of the comments. Generally rows will either be added or changed, but sometimes rows will be removed. Typically, only 1-5 new rows will be added to a file in a given day, but users sometimes make manual corrections/deletions to older rows and sometimes certain column values are recalculated. http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html You could keep a copy of all files - let's say, as they were yesterday. When you want to process the changes, iterate over all files and see if they are newer than your copy. You could use the filecmp module: http://docs.python.org/lib/module-filecmp.html For each modified file: load it, and process the comments adding the associated row type and the identity. Just do the same with the yesterday file. (I assume they're not so big that you can keep both in memory). You have then two lists of lines; then, use the functions in module difflib to detect the changed lines; based on those results, generate your database inserts/deletes/updates. This way you will not process the unchanged files, and inside each file, you will ignore unchanged lines. At least in principle it should be faster than redoing all from scratch each time... Did I mention that the header contains another implied hierarchy? Fortunately, I can just ignore it and strip it off. good - I imagine it's enough work as it is now... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
If you just expand the length to five million* or so, one of those strings will contain all the works of Shakespeare. Oops, you have this formula in math? Actually I want to scan a range of network for some certain files. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-13, Steve Holden [EMAIL PROTECTED] wrote: Antoon Pardon wrote: On 2007-04-12, Carsten Haese [EMAIL PROTECTED] wrote: On Thu, 2007-04-12 at 14:10 +, Antoon Pardon wrote: People are always defending duck-typing in this news group and now python has chosen to choose the option that makes duck-typing more difficult. Au contraire! The inconsistent behavior of in is precisely what duck-typing is all about: Making the operator behave in a way that makes sense in its context. No it isn't. Ducktyping is about similar objects using a similar interface to invoke similar behaviour and getting similar result. So that if you write a function you don't concern yourself with the type of the arguments but depend on the similar behaviour. Please note that similar does not mean exact. That is because I don't want to get down in an argument about whether tp[:3] and ls[:3] is similar behaviour or exact the same behaviour when tp is a tuple and ls is a list. The behavior of str.__contains__ and list.__contains__ is similar. That would depend on how much you find things may differ and still call them similar. IMO they are not similar enough since 12 in 123 doesn't behave like [1,2] in [1,2,3] Duck-typing allows natural access to polymorphism. You appear to be making semantic distinctions merely for the sake of continuing this rather fatuous thread. I gave an argument that showed that the specific way the in functionality was extended in strings makes duck-typing (and by extention natural access to polymorphism) more difficult. although it may do so in a way that is not significant to you and the other developers. Now if you don't agree with the argument presented that is fine with me. If you think the problem is not big enough to bother with, that is fine with me too. But the argument doesn't disappear simply because you think ill of my intentions. And consider that each small inconsistency in itself may be not important enough to remove. But if you have enough of them remembering all these special cases can become tedious. Suppose someone writes a function that acts on a sequence. The algorithm used depending on the following invariant. i = s.index(e) = s[i] = e Then this algorithm is no longer guaranteed to work with strings. Because strings have different properties than other sequences. I can't help pointing out that your invariant is invalid for tuples also, because tuples don't have a .index() method. Strings have some properties that are different and some properties that are similar with other sequences. My argument is that if you want to facilitate duck typing and natural access to polymorphism in peoples functions that work with sequences in general you'd better take care that the sequence api of strings resembles the sequence api of other sequences as good as possible. You on the other hand seem to argue that since strings have properties where they differ from other sequences it no longer is so important that the sequence api of strings resembles those of other sequences. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Pydoc Rewrite Discussion at doc-sig list.
If anyone is interested in participating in discussing the details of the PyDoc rewrite/refactoring I've been working on, a discussion is being started on the doc-sig list. [EMAIL PROTECTED] The goal of this discussion will be to get it to a final finished form so a patch can be submitted and a final discussion can take place on the python-dev list at a later date. Thanks and Regards, Ron Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
Antoon Pardon wrote: On 2007-04-13, Steve Holden [EMAIL PROTECTED] wrote: Antoon Pardon wrote: On 2007-04-12, Carsten Haese [EMAIL PROTECTED] wrote: On Thu, 2007-04-12 at 14:10 +, Antoon Pardon wrote: People are always defending duck-typing in this news group and now python has chosen to choose the option that makes duck-typing more difficult. Au contraire! The inconsistent behavior of in is precisely what duck-typing is all about: Making the operator behave in a way that makes sense in its context. No it isn't. Ducktyping is about similar objects using a similar interface to invoke similar behaviour and getting similar result. So that if you write a function you don't concern yourself with the type of the arguments but depend on the similar behaviour. Please note that similar does not mean exact. That is because I don't want to get down in an argument about whether tp[:3] and ls[:3] is similar behaviour or exact the same behaviour when tp is a tuple and ls is a list. The behavior of str.__contains__ and list.__contains__ is similar. That would depend on how much you find things may differ and still call them similar. IMO they are not similar enough since 12 in 123 doesn't behave like [1,2] in [1,2,3] And it never will, because of the property of strings I mentioned previously. Unless you want to introduce a character type into Python there is no way that you are ever going to be be satisfied. Duck-typing allows natural access to polymorphism. You appear to be making semantic distinctions merely for the sake of continuing this rather fatuous thread. I gave an argument that showed that the specific way the in functionality was extended in strings makes duck-typing (and by extention natural access to polymorphism) more difficult. although it may do so in a way that is not significant to you and the other developers. I am not a developer. Now if you don't agree with the argument presented that is fine with me. If you think the problem is not big enough to bother with, that is fine with me too. But the argument doesn't disappear simply because you think ill of my intentions. Apparently. And consider that each small inconsistency in itself may be not important enough to remove. But if you have enough of them remembering all these special cases can become tedious. But not as tedious as this eternal discussion of already-decided issues. Suppose someone writes a function that acts on a sequence. The algorithm used depending on the following invariant. i = s.index(e) = s[i] = e Then this algorithm is no longer guaranteed to work with strings. Because strings have different properties than other sequences. I can't help pointing out that your invariant is invalid for tuples also, because tuples don't have a .index() method. Strings have some properties that are different and some properties that are similar with other sequences. My argument is that if you want to facilitate duck typing and natural access to polymorphism in peoples functions that work with sequences in general you'd better take care that the sequence api of strings resembles the sequence api of other sequences as good as possible. This is just a bald restatement of the same argument you feel makes it desirable to add an index() method to tuples. If taken to its logical (and ridiculous) extreme there should only be one sequence type in Python. You on the other hand seem to argue that since strings have properties where they differ from other sequences it no longer is so important that the sequence api of strings resembles those of other sequences. Well, of course. Programming languages are for human users, and they should do what human users find most natural. Since humans can disagree the developers (amongst who I do not count myself, although I *am* concerned about the development of Python) have to try and go by consensus, which by and large they do reasonably successfully. So what I suppose I *am* saying is that your opinions would seem to differ from the consensus. While you are not in a minority of one you are in a minority, and it would be nice if we could proceed without having to continually revisit each small design decision on a continuous basis. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
On Apr 13, 9:27 am, Jia Lu [EMAIL PROTECTED] wrote: If you just expand the length to five million* or so, one of those strings will contain all the works of Shakespeare. Oops, you have this formula in math? Actually I want to scan a range of network for some certain files. Sorry, Jia Lu, I don't. I was actually just joking, alluding to the old saying that goes if you had an infinite number of monkeys typing randomly on an infinite number of typewriters, they will eventually type out the works of Shakespeare. Typewriters! who uses typewriters any more?! -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
Antoon Pardon said unto the world upon 04/13/2007 02:46 AM: On 2007-04-12, Steven D'Aprano [EMAIL PROTECTED] wrote: snip So much fuss over such a little thing... yes it would be nice if tuples grew an index method, but it isn't hard to work around the lack. Yes it is a little thing. But if it is such a little thing why do the developers don't simply add it? It's wafer thin! -- Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
On Apr 13, 2007, at 9:19 AM, Paul McGuire wrote: If you just expand the length to five million* or so, one of those strings will contain all the works of Shakespeare. Not likely, even with a tiny sampling of the works of Shakespeare: # :-) import string import random def main(bardText, maxTries=500): tries = 0 while tries maxTries: tries += 1 attempt = [] for letter in bardText.lower(): if random.choice( string.lowercase[:26] + string.punctuation + ' ' ) == letter: attempt.append(letter) else: break if len(attempt) = 4: print '%d: %s' % ( tries, ''.join(attempt) ) if __name__ == __main__: main(Alas, poor Yorick!) -- http://mail.python.org/mailman/listinfo/python-list
Re: Databases with python
Anthony Irwin wrote: Also is wxpython the best cross platform gui library it seems to be the best I have seen so far. IMO, it's an extremely mature and well-supported library. I have no experience with others (except a brief stint with Tkinter) but the consensus I hear seems to be that wxPython is probably the most popular choice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
On Apr 13, 10:22 am, Michael Bentley [EMAIL PROTECTED] wrote: On Apr 13, 2007, at 9:19 AM, Paul McGuire wrote: If you just expand the length to five million* or so, one of those strings will contain all the works of Shakespeare. Not likely, even with a tiny sampling of the works of Shakespeare: # :-) import string import random def main(bardText, maxTries=500): tries = 0 while tries maxTries: tries += 1 attempt = [] for letter in bardText.lower(): if random.choice( string.lowercase[:26] + string.punctuation + ' ' ) == letter: attempt.append(letter) else: break if len(attempt) = 4: print '%d: %s' % ( tries, ''.join(attempt) ) if __name__ == __main__: main(Alas, poor Yorick!) 500 infinity Keep tryin'! Also, the OP's technique was not doing random string permutations, but generating an exhaustive list of all possible sequences from aaa... to zzz... . So I think the works of Shakespeare are *bound* to be in there somewhere. For proof, here's an extract from my sample code from running this exhaustive program with length=14: ... ALASPOORYORICG ALASPOORYORICH ALASPOORYORICI ALASPOORYORICJ ALASPOORYORICK ALASPOORYORICL ALASPOORYORICM ALASPOORYORICN ALASPOORYORICO ... -- Paul :) (too late for April 1, unfortunately) -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
Brian van den Broek wrote: Antoon Pardon said unto the world upon 04/13/2007 02:46 AM: On 2007-04-12, Steven D'Aprano [EMAIL PROTECTED] wrote: snip So much fuss over such a little thing... yes it would be nice if tuples grew an index method, but it isn't hard to work around the lack. Yes it is a little thing. But if it is such a little thing why do the developers don't simply add it? It's wafer thin! Quite. [The Python language adds an index() method to tuples and promptly EXPLODES]. Thank you, Mr. Creosote. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
On Fri, 2007-04-13 at 10:22 -0500, Michael Bentley wrote: On Apr 13, 2007, at 9:19 AM, Paul McGuire wrote: If you just expand the length to five million* or so, one of those strings will contain all the works of Shakespeare. Not likely, even with a tiny sampling of the works of Shakespeare: Actually, the OP seems to be interested in generating *all* strings of length N. If you generate the set of *all* strings of 5 million characters length, at least one of them will contain all works of Shakespeare. That statement is utterly true and utterly impractical, which is, of course, the point of Paul's joke. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Class Dependancy Injection
Hey again guys, I'm looking to get an answer about dependency injection in python classes, what is the best way to deal with this? For instance, in my application I have a configuration bean which contains all the applications configuration information. Now in one of other classes I need access to those configuration settings. What I would have done in my ColdFusion/JAVA type applications is create an instance of the configuration bean, and then pass that in as an argument to the constructor for my other class, then have the other class set that as a 'self' variable. Then from within my class I can access the configuration details like self.config.getName() and it would return the name of the application. How is this best handled in python, can I still inject dependencies as a constructor argument like that? If so then is there anything in particular I need to watch out for that may cause me trouble? Thanks, Rob -- http://mail.python.org/mailman/listinfo/python-list
function/method assigment
I have a confusion when I do some practice, the code and output are as following, def fun(): print 'In fun()' testfun = fun() In fun() print testfun None testfun2 = fun print testfun2 function fun at 0x00CC1270 print testfun2() In fun() None what is 'testfun'? Why it is 'None'? And print testfun2(), what is the meaning of 'None'? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: mac IDLE problems
7stud wrote: Hi, In the IDLE, I can't get most shortcut keys that are listed next to the menu items to work. For instance, under the Format menu item only the shortcuts for indent region and undent region work. If I highlight some text and use Shift+3 to comment out the region I highlighted, the code is erased and I get the # symbol. When I use the option(alt key) and type a character, I get things like this: ƒ,¢,º,˚ I looked under Options/Configure IDLE/Keys and tried the various built in key sets, and none seem to work. I also can't use my mouse to copy(or cut) and paste. When I highlight something and right click(in an attempt to bring up the context menu that has copy, cut, paste, etc.), the text that is highlighted is doubled when I right click, e.g.: some text becomes: some textsome text And, sometimes when I try to highlight a line, the line 7 lines below the cursor gets highlighted. intel mac, os 10.4.7, python 2.4.4 IDLE under 2.5 has been much improved on the Mac; all the standard Mac keyboard shortcuts are supported, and in general it's more stable. With 2.5, IDLE replaces the old PythonIDE that used to ship with MacPython. Can you update to 2.5? -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Class Dependancy Injection
Robert Rawlins - Think Blue wrote: Hey again guys, I’m looking to get an answer about dependency injection in python classes, what is the best way to deal with this? For instance, in my application I have a configuration bean which contains all the applications configuration information. Now in one of other classes I need access to those configuration settings. What I would have done in my ColdFusion/JAVA type applications is create an instance of the configuration bean, and then pass that in as an argument to the constructor for my other class, then have the other class set that as a ‘self’ variable. Then from within my class I can access the configuration details like self.config.getName() and it would return the name of the application. How is this best handled in python, can I still inject dependencies as a constructor argument like that? If so then is there anything in particular I need to watch out for that may cause me trouble? That indeed sounds like the best way to proceed. You should find that, modulo the language differences, the technique works in just the same way. You shouldn't anticipate trouble. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: function/method assigment
[EMAIL PROTECTED] wrote: I have a confusion when I do some practice, the code and output are as following, def fun(): print 'In fun()' testfun = fun() In fun() print testfun None testfun2 = fun print testfun2 function fun at 0x00CC1270 print testfun2() In fun() None what is 'testfun'? Why it is 'None'? And print testfun2(), what is the meaning of 'None'? Thanks! When a function does not specifically return a value then its return value is a particular value known as None, the only instance of the None type. So testfun is the result of calling the fun function, and it's None because fun() does not return a value. Since testfun2 is just another reference to the fun function, testfun2() is None for exactly the same reasons. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Class Dependancy Injection
Thanks Steve that's good to here. I'll give it a shot this evening and if I have any problems then 'I'll be back';-) Rawlins -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Steve Holden Sent: 13 April 2007 17:32 To: [EMAIL PROTECTED] Subject: Re: Class Dependancy Injection Robert Rawlins - Think Blue wrote: Hey again guys, I'm looking to get an answer about dependency injection in python classes, what is the best way to deal with this? For instance, in my application I have a configuration bean which contains all the applications configuration information. Now in one of other classes I need access to those configuration settings. What I would have done in my ColdFusion/JAVA type applications is create an instance of the configuration bean, and then pass that in as an argument to the constructor for my other class, then have the other class set that as a 'self' variable. Then from within my class I can access the configuration details like self.config.getName() and it would return the name of the application. How is this best handled in python, can I still inject dependencies as a constructor argument like that? If so then is there anything in particular I need to watch out for that may cause me trouble? That indeed sounds like the best way to proceed. You should find that, modulo the language differences, the technique works in just the same way. You shouldn't anticipate trouble. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with algorithm
On Apr 13, 10:49 am, Carsten Haese [EMAIL PROTECTED] wrote: On Fri, 2007-04-13 at 10:22 -0500, Michael Bentley wrote: On Apr 13, 2007, at 9:19 AM, Paul McGuire wrote: If you just expand the length to five million* or so, one of those strings will contain all the works of Shakespeare. Not likely, even with a tiny sampling of the works of Shakespeare: Actually, the OP seems to be interested in generating *all* strings of length N. If you generate the set of *all* strings of 5 million characters length, at least one of them will contain all works of Shakespeare. That statement is utterly true and utterly impractical, which is, of course, the point of Paul's joke. -Carsten But even random typing will *eventually* get there (where eventually = several gazillion times the age of the universe) - see http://en.wikipedia.org/wiki/Infinite_monkey_theorem. -- Paul If I see farther, it is because I stand on the shoulders of an infinite number of monkeys. -- http://mail.python.org/mailman/listinfo/python-list
Re: function/method assigment
On Apr 13, 6:14 pm, [EMAIL PROTECTED] wrote: I have a confusion when I do some practice, the code and output are as following, def fun(): print 'In fun()' testfun = fun() In fun() print testfun None testfun2 = fun print testfun2 function fun at 0x00CC1270 print testfun2() In fun() None what is 'testfun'? Why it is 'None'? And print testfun2(), what is the meaning of 'None'? Thanks! Your 'fun' is the sam as: def fun(): print 'In fun()' return None So testfun = fun() First prints message and then assign None to testfun. -- http://mail.python.org/mailman/listinfo/python-list
Re: function/method assigment
[EMAIL PROTECTED] a écrit : I have a confusion when I do some practice, the code and output are as following, def fun(): print 'In fun()' Function fun doesn't explicitelly return something, so it's return value defaults to None (nb: None is a builtin object representing 'nothing'). testfun = fun() This calls fun, and binds the returned value (in this case, None) to name testfun In fun() and this is a side-effect of the execution of function fun. print testfun None Which is the expected result testfun2 = fun This binds the function object fun to the name testfun2 (IOW, testfun2 is now an alias for fun). Remember that in Python, the parens are not optional if you want to call a function - they are in fact the 'call operator'. If you forget them, you get a reference to the function object, not the result of calling the function. print testfun2 This prints the representation of the object bound to name testfun2 - here, function fun. function fun at 0x00CC1270 print testfun2() In fun() None This first calls testfun2 (which is now another name for function fun), triggering the printing of the string in fun()... as a side effects, then print the return value of testfun2 (aka fun), which is still None. HTH -- http://mail.python.org/mailman/listinfo/python-list