MDP-2.0 released
MDP version 2.0 has been released! What is it? --- Modular toolkit for Data Processing (MDP) is a data processing framework written in Python. From the user's perspective, MDP consists of a collection of trainable supervised and unsupervised algorithms that can be combined into data processing flows. The base of readily available algorithms includes Principal Component Analysis, two flavors of Independent Component Analysis, Slow Feature Analysis, Gaussian Classifiers, Growing Neural Gas, Fisher Discriminant Analysis, and Factor Analysis. From the developer's perspective, MDP is a framework to make the implementation of new algorithms easier. MDP takes care of tedious tasks like numerical type and dimensionality checking, leaving the developer free to concentrate on the implementation of the training and execution phases. The new elements then automatically integrate with the rest of the library. As its user base is increasing, MDP might be a good candidate for becoming a common repository of user-supplied, freely available, Python implemented data processing algorithms. Resources - Download: http://sourceforge.net/project/showfiles.php?group_id=116959 Homepage: http://mdp-toolkit.sourceforge.net Mailing list: http://sourceforge.net/mail/?group_id=116959 What's new in version 2.0? -- MDP 2.0 introduces some important structural changes. It is now possible to implement nodes with multiple training phases and even nodes with an undetermined number of phases. This allows for example the implementation of algorithms that need to collect some statistics on the whole input before proceeding with the actual training, or others that need to iterate over a training phase until a convergence criterion is satisfied. The ability to train each phase using chunks of input data is maintained if the chunks are generated with iterators. Nodes that require supervised training can be defined in a very straightforward way by passing additional arguments (e.g., labels or a target output) to the 'train' method. New algorithms have been added, expanding the base of readily available basic data processing elements. MDP is now based exclusively on the NumPy Python numerical extension. -- Tiziano Zito Institute for Theoretical Biology Humboldt-Universitaet zu Berlin Invalidenstrasse, 43 D-10115 Berlin, Germany Pietro Berkes Gatsby Computational Neuroscience Unit Alexandra House, 17 Queen Square London WC1N 3AR, United Kingdom -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Pydev 1.2.1 Released
Hi All, Pydev and Pydev Extensions 1.2.1 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Important 1. This release is still not available in the sourceforge downloads session because of some problems at sourceforge, but it is already placed in the update sites (and should be added to the sourceforge downloads as soon as the sourceforge release works again. 2. Eclipse 3.2: The final Eclipse 3.2 should be available (according to http://eclipse.org) in 1 day. Release Highlights in Pydev Extensions: - - Bug-Fixes Release Highlights in Pydev: -- - The user is asked for which paths should be added to the system pythonpath - Go to previous method now works with decorators - Stack-trace link now opens in correct line for external files - Variables now show in the variables view while debugging - If an invalid interpreter is selected to run a file (old interpreter or wrong project type), a warning is given to the user - Ctrl+w is removed as the default for select word (the action is still there, but its keybinding is removed, so, users have to configure themselves which keybinding they want for it) - Assign to local or field variable now enters in linked mode - Added dependency to Eclipse 3.2 features, as version 1.2.0 of pydev and newer are only Eclipse 3.2 compatible. What is PyDev? --- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny -- Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: SciPy 2006 Conference Reminder
The *SciPy 2006 Conference* is scheduled for Thursday and Friday, August 17-18, 2006 at CalTech with Sprints and Tutorials Monday-Wednesday, August 14-16. Conference details are at http://www.scipy.org/SciPy2006 The deadlines for submitting abstracts and early registration are approaching... Call for Presenters --- If you are interested in presenting at the conference, you may submit an abstract in Plain Text, PDF or MS Word formats to abstracts at scipy.org http://mail.python.org/mailman/listinfo/python-announce-list -- the deadline for abstract submission is July 7, 2006. Papers and/or presentation slides are acceptable and are due by August 4, 2006. Registration: - Early registration ($100.00) is still available through July 14. You may register online at http://www.enthought.com/scipy06. Registration includes breakfast and lunch Thursday Friday and a very nice dinner Thursday night. After July 14, 2006, registration will cost $150.00. Tutorials and Sprints - This year the Sprints (Monday and Tuesday, August 14-15) and Tutorials (Wednesday, August 16) are no additional charge (you're on your own for food on those days, though). Remember to include these days in your travel plans. The following topics are presented as Tutorials Wednesday (more info here: http://www.scipy.org/SciPy2006/TutorialSessions): - 3D visualization in Python using tvtk and MayaVi - Scientific Data Analysis and Visualization using IPython and Matplotlib. - Building Scientific Applications using the Enthought Tool Suite (Envisage, Traits, Chaco, etc.) - NumPy (migration from Numarray Numeric, overview of NumPy) The Sprint topics are under discussion here: http://www.scipy.org/SciPy2006/CodingSprints See you in August! Travis -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Reddit broke - should have remained on Lisp?
Alok wrote: While posting a comment on http://www.reddit.com I got an error page with the following curious statement on it. reddit broke (sorry) looks like we shouldn't have stopped using lisp... See screenshot at http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg Whether they truly repent not using lisp or otherwise, their site appears to be 3 times slower ... since when? don't you think that the massive growth in usage that they've been seeing lately might have something to do with that ? /F -- http://mail.python.org/mailman/listinfo/python-list
Import: Multiple modules with same name
Hello All, I have multiple modules with same name in different directories (well I guess thats may not be a good practise, but i needed it for debugging and working with various versions). Now how do I import a module with specifying a path. Few minutes of googling suggested: import ihooks import os def my_import(filename): loader = ihooks.BasicModuleLoader() path, file = os.path.split(filename) name, ext = os.path.splitext(file) module = loader.find_module_in_dir(name, path) if not module: raise ImportError, name module = loader.load_module(name, module) return module But It looked like an overkill, Is there a more elegant and better way of doing it ? Thanks in advance, cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLLIB
Heavy wrote: I need to know if the 'xmllib' module have some method able to transform a data structure in a xml file and viceversa, thanks define data structure and xml file (format). /F -- http://mail.python.org/mailman/listinfo/python-list
conecting with a MsAcces DB by dao
Hi I'm using activestate python 2.4 on win xp 2 ed. and Ms Access 2002 (reading first http://starship.python.net/crew/bwilk/access.html) I have writed the following code def append_from_Access(self): try: import ... conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:/Afile.mdb; conn.Open(DSN) except Exception, inst: ... try: sql_statement='SELECT * FROM Mytable' rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(sql_statement, conn, 1, 3) while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() except Exception, inst: ... I'm using it for reading tables or queries in a mdb file. With some mdb it works fine and return a no empty recordset, but with others mdb files, the recordsets are void (opening the tables or recorsets with Ms Access are not void). Some help is welcome, Thanks in advance Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: Bug reporting impossible
Nick Maclaren wrote: | Why would you have a file named 'stdin' in your current directory? Why would Python search for one? :-) In both cases, the normal answer is Someone made a mistake but, if you have a script that creates a files of the same names specified in the current directory, what name should it use if you specify stdin? given that stdin is an invalid filename on some platforms, why would any serious programmer use stdin for an external file ? It is one of the standard conventions, which is (after all) why Python is searching for it. the only reason Python's searching for it is that the CLI implementation passes stdin as the second argument to compile: http://pyref.infogami.com/compile /F -- http://mail.python.org/mailman/listinfo/python-list
Re: String Question
Iain King [EMAIL PROTECTED] wrote: You probably want: s.sendto('\xff'*6 + ('\x%s\x%s\x%s\x%s\x%s\x%s' % (str01, str02, str03, sttr04, str05, str06))*16, ('192.168.1.255', 80)) You probably should TRY suggestions before you post them. That will get an invalid \x escape. \x must be followed by exactly two hex digits. You can't build up an escape sequence like this. -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running DocTest on Strings
André wrote: Paddy wrote: notanotheridiot wrote: Hi, I have two strings - a docstring containing doctests and a code string containing code to be tested with those doctests. I've been trying for a day now to run the test without concatenating the two strings, adding: import doctest doctest.testmod to the bottom, writing it all to a file and executing it using popen(). There must be some way of doing this without writing to a temporary file, any ideas? thanks in advance, johannes Woolard Create the concatenated string then exec it? I know from experience that this approach does not work. When you do that, the entire module from which it is run turns out to be scanned for doctests - not only the string being executed by exec. However, I understand that Johannes found a solution. André - Pad. Got it, I've blogged about it here: http://pytute.blogspot.com/2006/06/say-no-to-temporary-files.html Basically the trick is to pass the docstring ino the exec environment as a variable and use the advanced doctest api to get a doctest. Johannes -- http://mail.python.org/mailman/listinfo/python-list
Re: Import: Multiple modules with same name
Amit Khemka wrote: But It looked like an overkill, Is there a more elegant and better way of doing it ? try: path = sys.path[:] sys.path.insert(0, mypath) # or something import mymodule finally: sys.path = path /F -- http://mail.python.org/mailman/listinfo/python-list
Py2exe make wxPython window looks bad
Dear all: I made a window program by wxPython. Split windows, treectrl, listctrl and textctrl are used. When I program in python, the look feel of the window controls are like the windos XP look feel, with thin and flat border (My os is window XP). It's natural because, as I know, wxPython use native look and feel. But when I convert the program to EXE file by Py2exe, and run it, the look feel is bad. It's just like the windows 9x. All controls has a thick and emboss border. However, the scrollbars look good, same as the window XP. So I'm puzzled. What's the problem and how can I get a XP look feel window program? Should I add some code in my program to set the look and feel, or, set some options in py2exe script to force the generated exe has specified look and feel? The setup.py is very simple as following: -setup.py- import sys, os from distutils.core import setup import py2exe import glob setup( name = mainframe, windows = [mainframe.py] ) -- http://mail.python.org/mailman/listinfo/python-list
Re: python for windows internet filter / firewall
[EMAIL PROTECTED] wrote: Greetings, I'm interested in a simple content-based internet firewall/filter, similar to dansguardian (http://dansguardian.org/), Firewall and filter are two things totally separated! - If you want to do something like a page filtering, like dansguard and squidguard, you can simple do it with python, because you have to act like a proxy that leave of not visit a page. - If you have to do a firewall... I think you can't, especially if you are on win. Take a look at wipfw (wipfw.sf.net) that do what you want but written in python, Of course :) and for windows. Why? All that work with networking (and not only that) work better with *nix OS! I assumed such a project would already exist, Firewall I don't think, and the same for the filtering (I know only something like a plugin for squid, so for *nix platform). but my searches on freshmeat, and google turned up empty. I would be interested in starting my own project if necessary, so I have two questions: 1) Does any one no of such a project? 2) Is this even reasonable in python and how might I get started? (e.g. win32 COM?) win32COM for do what? You can do it in not so difficult manner: Take twisted and its proxy class, make some outline code (for filter the pages) and enjoy! (work also on win) Thanks much -- matthew P.s. Don't forgot to share your code, when it'll work :) Bye, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2exe make wxPython window looks bad
zdp wrote: Dear all: I made a window program by wxPython. Split windows, treectrl, listctrl and textctrl are used. When I program in python, the look feel of the window controls are like the windos XP look feel, with thin and flat border (My os is window XP). It's natural because, as I know, wxPython use native look and feel. [snip] http://wiki.wxpython.org/index.cgi/FAQ#head-4cc058aed6216dd200d55a6e4c077ccbe82bd142 Regards, Ray Smith http://RaymondSmith.com -- http://mail.python.org/mailman/listinfo/python-list
Re: String Question
Tim Roberts wrote: Iain King [EMAIL PROTECTED] wrote: You probably want: s.sendto('\xff'*6 + ('\x%s\x%s\x%s\x%s\x%s\x%s' % (str01, str02, str03, sttr04, str05, str06))*16, ('192.168.1.255', 80)) You probably should TRY suggestions before you post them. That will get an invalid \x escape. \x must be followed by exactly two hex digits. You can't build up an escape sequence like this. -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. You're right. I'd foolishly assumed that \x was just another character code, like \t or \n. Apologies. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get indices of a two dimensional list
[EMAIL PROTECTED] wrote: I have a list x = [0] * 2 x = x * [2] x[1,1] = 7 This gives me the x value [[0,0] [0,0] [0,0] [0,7]] I want to get the indices of the value 7. i.e. something like i = a.index(max(a)) gives me '1' This only gives me the index in one dimension. Is there any method by which I can get (1,1) as the answer. Thanks in advance. If you post code that doesn't work, people won't treat you seriously. I have some code that might help if you'd like to try again. All the best Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: conecting with a MsAcces DB by dao
luis wrote: Hi I'm using activestate python 2.4 on win xp 2 ed. and Ms Access 2002 (reading first http://starship.python.net/crew/bwilk/access.html) I have writed the following code def append_from_Access(self): try: import ... conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:/Afile.mdb; conn.Open(DSN) except Exception, inst: ... try: sql_statement='SELECT * FROM Mytable' rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(sql_statement, conn, 1, 3) while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() except Exception, inst: ... I'm using it for reading tables or queries in a mdb file. With some mdb it works fine and return a no empty recordset, but with others mdb files, the recordsets are void (opening the tables or recorsets with Ms Access are not void). Some help is welcome, Thanks in advance Luis I don't know if it's the problem your asking about, but your rs.MoveNext() should be inside the while loop, no? Iain -- http://mail.python.org/mailman/listinfo/python-list
optparse multiple arguments
Hi, I'm having some minor problems with optparse. I'm just worried that someone shouldn't say that multiple argument feature isn't implemented in optpartse. How to tackle multiple arguments to an option ? As far as I dug, I've found that 1 arguments are being ignored. parser.add_option(, --my-option, dest=my_option, action=store, type=string) Now if someone uses it as: ./foo --my-option a b c I want somehow to store all the three arguments but my_option stores only a while ignoring b and c. Any help? Ritesh -- http://mail.python.org/mailman/listinfo/python-list
Re: optparse multiple arguments
Ritesh Raj Sarraf wrote: Hi, I'm having some minor problems with optparse. I'm just worried that someone shouldn't say that multiple argument feature isn't implemented in optpartse. How to tackle multiple arguments to an option ? As far as I dug, I've found that 1 arguments are being ignored. parser.add_option(, --my-option, dest=my_option, action=store, type=string) Now if someone uses it as: ./foo --my-option a b c I want somehow to store all the three arguments but my_option stores only a while ignoring b and c. I just noticed that the args variable is holding values b and c. the args variables comes from: (options, args) = parser.parse_args() I guess I only need to figure out now is why args isn't storing argument a also... Ritesh -- http://mail.python.org/mailman/listinfo/python-list
File naming [was Re: Bug reporting impossible]
In article [EMAIL PROTECTED], Fredrik Lundh [EMAIL PROTECTED] writes: | | | Why would you have a file named 'stdin' in your current directory? | | Why would Python search for one? :-) | | In both cases, the normal answer is Someone made a mistake but, if | you have a script that creates a files of the same names specified in | the current directory, what name should it use if you specify stdin? | | given that stdin is an invalid filename on some platforms, why would any | serious programmer use stdin for an external file ? You can't be serious, surely? Firstly, why does Python? Well, I can answer that :-) Secondly, EVERY string is an invalid filename on some platforms, without exception! As every single (not system-specific) language has done since languages imported the concept of filenames, Python says that the set of strings that are valid filenames is implementation-dependent or perhaps implementation-defined. Thirdly, I had better explain what a LOT of programs and scripts actually do. You have a command 'fred' that takes filenames as arguments and, if there are none, uses stdin; as part of its function, it needs to create a file of the same name as those in its arguments, in the current directory. What filename should it use for stdin? I sincerely HOPE that you are not proposing to use the null filename (which could and probably still can be created on some systems), as it is a gibbering nightmare to handle thereafter, and a poor sod of an ordinary user has little hope of cleaning up the mess. Been there - done that for them :-) It can't use 'stdin', as that is a possible file name, so it uses an obvious derivation that is unlikely to be created by accident. 'stdin' is one of the standard conventions - I am one of perhaps a few hundred (perhaps more) people who invented it independently, 20 years back, but doubt that I was even close to the first. It is quite a good name for Unix, as you can't easily create it by accident in any normal shell. | It is one of the standard conventions, which is (after all) why Python | is searching for it. | | the only reason Python's searching for it is that the CLI implementation passes | stdin as the second argument to compile: | | http://pyref.infogami.com/compile And the reason that it does that is because it is using one of the standard conventions for naming stdin. Python didn't INVENT that convention, you know. The bug isn't in passing an information string stdin but in using that string (which is not meant to represent a real file) to perform a file search. Regards, Nick Maclaren. -- http://mail.python.org/mailman/listinfo/python-list
FIXED: Re: optparse multiple arguments
Ritesh Raj Sarraf wrote: I just noticed that the args variable is holding values b and c. the args variables comes from: (options, args) = parser.parse_args() I guess I only need to figure out now is why args isn't storing argument a also... Ritesh I fixed it, I guess. parser.add_option(, --my-option, dest=my_option, action=store_true) sets my_option to True and the arguments are all stored in the list args. :-) Ritesh -- http://mail.python.org/mailman/listinfo/python-list
Re: FIXED: Re: optparse multiple arguments
Ritesh Raj Sarraf wrote: I guess I only need to figure out now is why args isn't storing argument a also... I fixed it, I guess. parser.add_option(, --my-option, dest=my_option, action=store_true) sets my_option to True and the arguments are all stored in the list args. :-) note that whatever action you're using, args holds the *remaining* arguments, after option processing. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Interprocess communication on multi-user machine
In article [EMAIL PROTECTED], Michael Butscher [EMAIL PROTECTED] wrote: Normally any user could connect to an open socket on a machine regardless which user established the socket (the user's program, to be precise). That's not true. On *nix systems, a socket is a file, and is subject to the usual file ownership and protection mechanisms. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get indices of a two dimensional list
Gerard Flanagan wrote: [EMAIL PROTECTED] wrote: I have a list x = [0] * 2 x = x * [2] x[1,1] = 7 This gives me the x value [[0,0] [0,0] [0,0] [0,7]] I want to get the indices of the value 7. i.e. something like i = a.index(max(a)) gives me '1' This only gives me the index in one dimension. Is there any method by which I can get (1,1) as the answer. Thanks in advance. If you post code that doesn't work, people won't treat you seriously. I have some code that might help if you'd like to try again. All the best Ok, that was mean-spirited. The code is below - it's related to another problem but maybe it can be adapted to your own. Good luck! def irows(n): i=0 while True: yield divmod(i,n) i += 1 x = [0,0,0,7,0,0,0,0] d = dict(zip(enumerate(x), irows(2))) assert d[x.index(7),7] == (1,1) assert d[x.index(0),0] == (0,0) d = dict(zip(irows(2),x)) assert d[1,1] == 7 sudoku = dict(zip(irows(9),[[0]]*81)) -- http://mail.python.org/mailman/listinfo/python-list
Re: No error while sending via TCP Socket
Martin Bürkle wrote: I have writen a programm using TCP sockets. After i get the connection to another socket I cut the Ethernet cable. Then I send a message. The program doesnt raise any exception. Can somebody tell me why and give me a hint how to get an exception Have you tried waiting 30 seconds or so? The connection may just take a while to time out. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2exe make wxPython window looks bad
zdp wrote: But when I convert the program to EXE file by Py2exe, and run it, the look feel is bad. It's just like the windows 9x. All controls has a thick and emboss border. However, the scrollbars look good, same as the window XP. Bear in mind that a lot of WinXP users stick with the old-style theme anyway, so you may want to consider them too when designing your forms. Sadly, WxWidget layouts tend to look bad on the old Windows theme, largely because there are too many unnecessary borders on the various elements, and I don't know if that's an inherent problem with the toolkit or just an oversight on the part of those who only develop under the newer themes. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Entry Widget problem
Hi, I am new in Python and I have no experience in object-oriented programming. I want to make an easy GUI for my application. What is my problem? I have the data-file like this (file ETab_H1.dan): 16 1 13 10 1 0.9 1.1 1 0 0.0 0.0 0.0 2 14 50 2 0.9 1.1 4 2 0.0 0.0 0.0 3 15 10 2 0.9 1.1 1 0 0.0 0.0 0.0 4 16 10 1 0.9 1.1 1 0 0.0 0.0 0.0 5 17 50 2 0.9 1.1 4 2 0.0 0.0 0.0 6 18 10 2 0.9 1.1 1 0 0.0 0.0 0.0 7 19 10 1 0.4 0.9 1 0 0.0 0.0 0.0 8 20 5 2 0.4 0.8 1 0 0.0 0.0 0.0 9 21 40 2 0.2 1.1 0 0 0.0 0.0 0.0 10 22 40 2 0.4 1.5 0 0 0.0 0.0 0.0 11 23 5 2 3.7 1.1 1 0 0.0 0.0 0.0 12 24 10 2 0.9 1.1 1 0 0.0 0.0 0.0 13 25 10 2 0.9 1.1 1 0 0.0 0.0 0.0 14 26 10 2 0.9 1.1 1 0 0.0 0.0 0.0 15 31 10 2 0.9 1.1 1 0 0.0 0.0 0.0 16 32 10 2 0.9 1.1 1 0 0.0 0.0 0.0 The first number is a number of rows in data-block below. These numbers are the coefficients for my functions in FORTRAN program. Before I run my program I must read this file, change some of these coefficients and write this file again in the same form. In the file ETab.py I wrote: file ETab.py: - from Tkinter import * import tkFont import string class ETab(Frame): def __init__(self): Frame.__init__(self,height=40,width=600,relief=RAISED) self.master.title('Data for grid generation') self.grid() ELista=[nr,Egde,nCell,nFun,P,Q,Metoda,WBTyp,Left,Right,sigma] for icol in range(len(ELista)): self.Etykieta(icol,irow=0,EText=ELista[icol]) f=open('ETab_H1.dan', 'r'); self.c=f.readline() c1=int(self.c) self.FieldList=[] self.FieldList.append(c1) k=1 for i in range(c1): c=f.readline() s=c.split() dl=len(s) for j in range(dl): self.Pola(k,j,i,DefaultValue=s[j]) k=k+1 f.close() self.applyBotton = Button(self,text=Apply,command=self.addEntry) self.applyBotton.grid(column=dl-2,row=c1+1) self.quitButton = Button(self, text=Quit,command=self.quit) self.quitButton.grid(column=dl-1,row=c1+1) def addEntry(self): nElem=len(self.FieldList) print nElem ff=open('ETab_H1.spr', 'w'); ff.write(self.c) LL=StringVar() for k in range(nElem): LL=self.FieldList[k] print k,LL ff.close() def Etykieta(self,icol,irow,EText): lab=Label(self,text=EText) lab.grid(column=icol,row=irow) return def Pola(self,k,icol,irow,DefaultValue): self.Tab=StringVar() WLista=[5,5,5,5,10,10,10,10,10,10,10] self.pole=Entry(self,highlightcolor=BLUE,textvariable=self.Tab,justify=RIGHT,width=WLista[icol]) self.pole.grid(column=icol,row=irow+1) self.pole.insert(0,DefaultValue) self.FieldList.append(self.Tab) return self.Tab ETab().mainloop() - This script connects all numbers in my data-file with Entry Widget, but the results are: 177 0 16 1 PY_VAR0 2 PY_VAR1 3 PY_VAR2 ... 174 PY_VAR173 175 PY_VAR174 176 PY_VAR175 And when I change LL into LL.get(): 177 Exception in Tkinter callback Traceback (most recent call last): File /usr/lib/python2.4/lib-tk/Tkinter.py, line 1345, in __call__ return self.func(*args) File ETab.py, line 107, in addEntry print k,LL.get() AttributeError: 'int' object has no attribute 'get' What is wrong? And, how can I take the value of self.Tab? Sorry for my English. M.S. -- http://mail.python.org/mailman/listinfo/python-list
Re: No error while sending via TCP Socket
Martin Bürkle írta: Hi NG, I have writen a programm using TCP sockets. After i get the connection to another socket I cut the Ethernet cable. Then I send a message. The program doesnt raise any exception. Can somebody tell me why and give me a hint how to get an exception Okay, let's suppose you do not cut the ethernet cable and your message arrives on the other side, but the receiver program has a problem (not enough memory, bug in the handling code etc.) so your message is not processed on the other side. Most of the time, you do not only want to check if your message was transferred - you also need to check if that is actually processed. The TCP protocol cannot do this for you.Your clients needs to send back another message that notifies the sender about successful processing. Your sender program can wait for this notification, and then raise an exception after some timeout. In other words, you need to develop your own communication protocol over TCP/IP. You should try to minimize the number of send-receive-notification cycles, because the answer time can be high, compared to the transfer speed of the communication channel. And also because notifications are usually small, and they a buffered for a while... I have seen a paper about designing protocols over TCP/IP, but I do not remember now. Others will help you for sure. Please also consider UDP (if possible), which can be much more efficient. Best, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric help!
Carl Banks wrote: Sheldon wrote: Carl Banks wrote: I'm not sufficiently sure this isn't a homework problem, so here's a partial answer. [snip] My days as a student is over for the most part. I am learning python on my own and Numeric is not properly documented so I am learning by doing and copying from others. Are you aware of this guide? http://numeric.scipy.org/numpydoc/numdoc.htm I've seen better documents but it's fairly complete--I wouldn't call it improper. I thought about the problem and a solution another problem given to me earlier using putmask is the solution but there is a bug that I cannot figure out: index = 0 for z in range_va: wk = msgva # working arrary sattmp = sat_id # working array This appears to be doing something you don't expect. In Python all names are references; assignments don't create new objects but rather new names for the same object. In the above, wk and msvga are the same array: any changes in wk also appear in msvga. So wk[1,1] = 4 also causes msgva[1,1] to be 4. Numeric arrays even share data when slicing. If you were to take a slice of wk, for example, a = wk[0:10,0:10], then modifying a would also show up in wk (and msvga). (However, slicing most other objects copies rather than shares the data.) It's completely different from Matlab, which always copies data. Here's what you should do: wk = array(msgva) # this creates a new array for wk sattmp = array(sat_id) mask = where(equal(wk,z),1,0) # creating a mask of valid data pixs Note that the where is unnecessary here. equal creates an array of ones and zeros. putmask(sattmp,mask==0,-999) # since zero is valid data, -999 is used instead This would overwrite sat_id unless you copy the array as I've shown above. rdata = compress(ravel(not_equal(sattmp,-999)),ravel(sattmp)) I believe you could avoid the above putmask above step and just use ravel(mask) as the first argument of compress here, or even just equal(wk,z). equal(wx,z), mask, and not_equal(sattmp,-999) are all equal arrays. if sum(sum(rdata)) == 0: av = 0 rdata is one-dimensional, so you only need one sum call; but why do this? average will still work if the sum is zero. else: av = average(rdata,axis=None) axis argument isn't necessary here since rdata is one-dimesional. tmparray[0,index] = av tmparray[1,index] = z index += 1 print tmparray *** But the tmparray is returning zeros as averages. When I try just one value for z everything works. I can't see where I going wrong. I am not using the original arrays, only the copies and when a new z is chosen then these are recreated. Care to help out with this? /Sheldon Other than the array sharing mistake, it looks like it should work. Also, note that this group disdains top-posting; replies should go below the quoted text because in these sorts of discussions it's best to keep things in conversational order, especially for the sake of other interested readers. Good luck. Carl Banks Thanks for the tips about the array and how it is copied. I figured this out late yesterday and wrote a dirty solution to this problem but your is more elegant and concise. Yes, where statement is not needed and I removed it. The replacement is the following: average(compress(ravel(equal(wk,z)),ravel(sattmp)),axis=None) This is much more compact and elegant. Thanks for pointing this out. I don't know why average() returned a divide by zero error and to avoid this I inserted this if statement. Now it works much better ! Much obliged, Sheldon -- http://mail.python.org/mailman/listinfo/python-list
Re: Entry Widget problem
Marek S. wrote: def __init__(self): ... self.c=f.readline() c1=int(self.c) self.FieldList=[] self.FieldList.append(c1) here you add an integer to the list. def Pola(self,k,icol,irow,DefaultValue): self.Tab=StringVar() ... self.FieldList.append(self.Tab) and here you add a StringVar. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: No error while sending via TCP Socket
Ben Sizer írta: Martin Bürkle wrote: I have writen a programm using TCP sockets. After i get the connection to another socket I cut the Ethernet cable. Then I send a message. The program doesnt raise any exception. Can somebody tell me why and give me a hint how to get an exception Have you tried waiting 30 seconds or so? The connection may just take a while to time out. I'm not sure if this will help him. He told that the program doesn't raise an exception. I suppose this also means that socket.send() was successful. If his program does not want to send or receive anything else, then he will not get an exception. Otherwise if socket.send() blocks his program, then you are right - he needs to wait. But I think he would have seen that his program is still running, and he would not have written what he wrote. If his program is still running, than he shouldn't have told it did not raise an exception. :-) Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: No error while sending via TCP Socket
Laszlo Nagy írta: Ben Sizer írta: Martin Bürkle wrote: I have writen a programm using TCP sockets. After i get the connection to another socket I cut the Ethernet cable. Then I send a message. The program doesnt raise any exception. Can somebody tell me why and give me a hint how to get an exception Have you tried waiting 30 seconds or so? The connection may just take a while to time out. I'm not sure if this will help him. He told that the program doesn't raise an exception. I suppose this also means that socket.send() was successful. If his program does not want to send or receive anything else, then he will not get an exception. Otherwise if socket.send() blocks his program, then you are right Another idea: probably his message is too small to fit one TCP packet. socket.send() succeeds, but the TCP packet is not sent out. By the time the packet driver tries to send out the (short) TCP packet, the socket.send() call is not active, so it cannot raise an exception. Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: FIXED: Re: optparse multiple arguments
Ritesh Raj Sarraf wrote: Ritesh Raj Sarraf wrote: I just noticed that the args variable is holding values b and c. the args variables comes from: (options, args) = parser.parse_args() I guess I only need to figure out now is why args isn't storing argument a also... Ritesh I fixed it, I guess. parser.add_option(, --my-option, dest=my_option, action=store_true) sets my_option to True and the arguments are all stored in the list args. :-) Ritesh It might do you good to read the documentation instead of blindly experimenting. Anyway, parser.add_option(, --my-option, nargs=3) http://docs.python.org/lib/optparse-standard-option-actions.html -- http://mail.python.org/mailman/listinfo/python-list
delete first line in a file
hello, i am a dummy user in python and new in this programming language and so there will be questions, that´s for you no problem! i never have before programmed in any language! sorry for this! i hope you will help me, that i also could the basics in this language! and later many more, so i hope ! :) the first question for me in this newsgroup will be the follow one: - is there a way to delete in a csv-file the first line?! big thanks, juergen -- http://mail.python.org/mailman/listinfo/python-list
Re: Interprocess communication on multi-user machine
In article [EMAIL PROTECTED], Lawrence D'Oliveiro [EMAIL PROTECTED] writes: | In article [EMAIL PROTECTED], | Michael Butscher [EMAIL PROTECTED] wrote: | | Normally any user could connect to an open socket on a machine | regardless which user established the socket (the user's program, to be | precise). | | That's not true. On *nix systems, a socket is a file, and is subject to | the usual file ownership and protection mechanisms. I am afraid that BOTH answers are badly wrong! Sockets are often accessed via special files, but are not files. They may also be accessed by port numbers, for example. Secondly, even when they are accessed via files, FIFOs generally do NOT use the usual file ownership and protection mechanisms to control access. Blame Berkeley for that :-( It is normal for the actual file ownership and permissions to be ignored, and a similar set (hidden internally) to be used. You are right that there is almost always such control. While any user can attempt to open any socket accessed by port number, the rules for when it is permitted are complicated to a degree, and depend on the system, configuration and program that is listening on that port. Regards, Nick Maclaren. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reddit broke - should have remained on Lisp?
Alok wrote: reddit broke (sorry) looks like we shouldn't have stopped using lisp... See screenshot at http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg Whether they truly repent not using lisp or otherwise, their site appears to be 3 times slower ... Hi Alok, Supposedly, the Reddit team had a bit of remorse (though of course, we should take the following writeup with a grain of salt; maybe there are more in-depth sources online): If we could do it all over again, we'd still be using Lisp. Probably. Reddit: Stick with Lisp. If you want it done right, do it yourself- hosting- Avoid A+.net http://notelab.infogami.com/startupschool2006 The Reddit owners offered to write up their Lisp experiences. Did they? If not, then of course we have no real ability to verify their claims. (Particularly given that companies are far too secretive to let us actually go there and evaulate their claims for ourselves.) The problem was illustrated by Dvorak's admission that he skillfully antagonized the Apple world to drive traffic; I don't know how much Reddit was helped by this little soap opera, if at all, but these are problems. http://www.youtube.com/watch?v=SAWDYaWAVQQ Tayssir -- http://mail.python.org/mailman/listinfo/python-list
Re: Interprocess communication on multi-user machine
In article [EMAIL PROTECTED], Michael Butscher [EMAIL PROTECTED] writes: | | this is not really Python-specific but I need it for Python. | | I'm wanting a method for interprocess communication which is OS- | independent (sockets would be the normal way to go), but which works if | multiple users use the machine at the same time so that one user has no | access to the communication of programs of another user. You're onto a complete loser if you really mean that. But you are probably meaning Unix-like systems (including Microsoft ones), and excluding the systems that are not based on or largely cloned from Unix. You should look at the POSIX facilities, but don't rely on them without checking. Also think very carefully whether you want to separate by user or job - the latter is trickier under Unix. Regards, Nick Maclaren. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reddit broke - should have remained on Lisp?
Luis M. González wrote: Alok wrote: I was merely describing my experience and inviting others' response about theirs. That's exactly what I'm doing. You misinterpret, I was talking about my experience with the site and inviting response from other people about their experience with the site. Now, I don't know much about python or lisp, but I have read about this web-site's history with the two programming languages. And hence I chose to post in comp.lang.lisp and comp.lang.python. Now if there were a reddit.technology.lisp or reddit.technology.python, and if they had the same traction as these usenet groups, then I could have posted there. But that was not an option was it. Please don't misconstrue that as a blame on any language. I think it can be interpreted in many ways. Can you please explain what your interpretation is? Now if you're not ready to read other people's oppinions, don't ask. Now, I think you are unfairly prejudiced about my not wanting to read other people's opinion. I would rather have a 1000 acrid responses to something I write and learn from it, than post into a responseless vacuum. And of course, I disagree with your comments about ridicule etc. Ok. -- http://mail.python.org/mailman/listinfo/python-list
Way for see if dict has a key
Hi ng, what the preferred way for see if the dict has a key? We have a lot of solutions: key in dict key in dict.keys() dict.has_key(key) ... but what the better or the more pythonic? Thanks, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Reddit broke - should have remained on Lisp?
Tayssir John Gabbour wrote: Alok wrote: reddit broke (sorry) looks like we shouldn't have stopped using lisp... See screenshot at http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg Whether they truly repent not using lisp or otherwise, their site appears to be 3 times slower ... Hi Alok, Supposedly, the Reddit team had a bit of remorse (though of course, we should take the following writeup with a grain of salt; maybe there are more in-depth sources online): If we could do it all over again, we'd still be using Lisp. Probably. Reddit: Stick with Lisp. If you want it done right, do it yourself- hosting- Avoid A+.net http://notelab.infogami.com/startupschool2006 Please, since this is a Python+Lisp cross-thread and you seem to have background info: can you explain why Lisp hackers have turned themselves into Python newbies for Reddit impl. and finally complain about the language switch? What was cause for their decision to use Python in the first place? -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Michele Petrazzo wrote: what the preferred way for see if the dict has a key? We have a lot of solutions: key in dict new syntax (2.3 and later). key in dict.keys() inefficient and pointless. dict.has_key(key) old syntax; use for code that needs to be backwards compatible. but what the better or the more pythonic? see above. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: conecting with a MsAcces DB by dao
Iain King ha escrito: luis wrote: Hi I'm using activestate python 2.4 on win xp 2 ed. and Ms Access 2002 (reading first http://starship.python.net/crew/bwilk/access.html) I have writed the following code def append_from_Access(self): try: import ... conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:/Afile.mdb; conn.Open(DSN) except Exception, inst: ... try: sql_statement='SELECT * FROM Mytable' rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(sql_statement, conn, 1, 3) while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() except Exception, inst: ... I'm using it for reading tables or queries in a mdb file. With some mdb it works fine and return a no empty recordset, but with others mdb files, the recordsets are void (opening the tables or recorsets with Ms Access are not void). Some help is welcome, Thanks in advance Luis I don't know if it's the problem your asking about, but your rs.MoveNext() should be inside the while loop, no? Yes, is inside Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: FIXED: Re: optparse multiple arguments
Simon Percivall wrote: It might do you good to read the documentation instead of blindly experimenting. Anyway, parser.add_option(, --my-option, nargs=3) http://docs.python.org/lib/optparse-standard-option-actions.html That won't help because by design of my program, I can't limit the number of arguments a user can pass to it. Ritesh -- http://mail.python.org/mailman/listinfo/python-list
Re: delete first line in a file
Juergen Huber wrote: i am a dummy user in python and new in this programming language and so there will be questions, that´s for you no problem! i never have before programmed in any language! sorry for this! i hope you will help me, that i also could the basics in this language! and later many more, so i hope ! :) the first question for me in this newsgroup will be the follow one: - is there a way to delete in a csv-file the first line?! in general, modern file systems can only remove and add stuff at the end of a file, so the only way to do this is to rewrite the entire file. (you can either load the entire file, fix it up, and write it out again, or copy the file to a new file, skipping the first line or row). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: FIXED: Re: optparse multiple arguments
Ritesh Raj Sarraf wrote: http://docs.python.org/lib/optparse-standard-option-actions.html That won't help because by design of my program, I can't limit the number of arguments a user can pass to it. do you want options, arguments, or are you just somewhat confused ? /F -- http://mail.python.org/mailman/listinfo/python-list
image output in matplotlib
Hey folks, I got a problem in printing images from a matplotlib - FigureCanvas Object (child of a wxFrame, library backend_wx) into jpeg-formatted files. (I like to create a sequence of images that I can assemble to an avi) self.mycanvas.print_figure(test.jpg) merely gives an error stating, that there should be an image handler of type 17, which I didn't come across ever :) No idea about the handles, does anybody has any hint how to proceed ? (or any thread I missed to grab..) thanks a lot and cheers, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Reddit broke - should have remained on Lisp?
Kay Schluehr wrote: Tayssir John Gabbour wrote: Supposedly, the Reddit team had a bit of remorse (though of course, we should take the following writeup with a grain of salt; maybe there are more in-depth sources online): If we could do it all over again, we'd still be using Lisp. Probably. Reddit: Stick with Lisp. If you want it done right, do it yourself- hosting- Avoid A+.net http://notelab.infogami.com/startupschool2006 Please, since this is a Python+Lisp cross-thread and you seem to have background info: can you explain why Lisp hackers have turned themselves into Python newbies for Reddit impl. and finally complain about the language switch? What was cause for their decision to use Python in the first place? Hi Kay, The claim was that their Lisp implementation, CMUCL, had threading problems which regularly crashed their site. http://lemonodor.com/archives/001301.html Also, they had concerns about the user community's size (at least the one surrounding the free Common Lisp implementations). http://xach.livejournal.com/66285.html All right, serious criticism of Lisp is a joy to read, as we're a technical audience... but how serious was this criticism? Apparently the original big announcement of their switch was deleted from the blog (at least the links are dead and I can't find it in a few secs of googling), but I remember they promised to write up their experiences with Lisp to help others if enough people asked. I was among those who encouraged them to do this, but I haven't heard a word more about this writeup. This would've made their claims easier to verify. As it stands, I don't know if they just had weird glitches with shoddy hardware from their service provider, or whether they seriously reached out to the community so it could help them. And they didn't even offer newbies the benefit of a helpful, critical writeup. (If it is indeed true they didn't follow up on the writeup.) For that matter, a nasty side-effect is it prompts some to heavily criticize Python in the same loose manner, out of a defensive feeling. Tayssir -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression - old regex module vs. re module
In article [EMAIL PROTECTED], Steve [EMAIL PROTECTED] wrote: Hi All, I'm having a tough time converting the following regex.compile patterns into the new re.compile format. There is also a differences in the regsub.sub() vs. re.sub() Could anyone lend a hand? import regsub import regex import re# need conversion to this module Convert perl style format symbology to printf tokens. Take a string and substitute computed printf tokens for perl style format symbology. For example: ###.##yields %6.2f yields %8d yields %-5s Perhaps not optimal, but this processes things as requested. Note that all floats have to be done before any integer patterns are replaced. == #!/usr/local/bin/python import re Convert perl style format symbology to printf tokens. Take a string and substitute computed printf tokens for perl style format symbology. For example: ###.##yields %6.2f yields %8d yields %-5s # handle cases where there's no integer or no fractional chars floatPattern = re.compile(r'(?!\\)(#+\.(#*)|\.(#+))') integerPattern = re.compile(r'(?![\\.])(#+)(?![.#])') leftJustifiedStringPattern = re.compile(r'(?!\\)(+)') rightJustifiedStringPattern = re.compile(r'(?!\\)(+)') def float_sub(matchobj): # fractional part may be in either groups()[1] or groups()[2] if matchobj.groups()[1] is not None: return %%%d.%df % (len(matchobj.groups()[0]), len(matchobj.groups()[1])) else: return %%%d.%df % (len(matchobj.groups()[0]), len(matchobj.groups()[2])) def unperl_format(s): changed_things = 1 while changed_things: # lather, rinse and repeat until nothing new happens changed_things = 0 mat_obj = leftJustifiedStringPattern.search(s) if mat_obj: s = re.sub(leftJustifiedStringPattern, %%-%ds % len(mat_obj.groups()[0]), s, 1) changed_things = 1 mat_obj = rightJustifiedStringPattern.search(s) if mat_obj: s = re.sub(rightJustifiedStringPattern, %%%ds % len(mat_obj.groups()[0]), s, 1) changed_things = 1 # must do all floats before ints mat_obj = floatPattern.search(s) if mat_obj: s = re.sub(floatPattern, float_sub, s, 1) changed_things = 1 # don't fall through to the int code continue mat_obj = integerPattern.search(s) if mat_obj: s = re.sub(integerPattern, %%%dd % len(mat_obj.groups()[0]), s, 1) changed_things = 1 return s if __name__ == '__main__': testarray = [integer: , integer # integer at end #, float .## no decimals ###. no int .### at end ###., Left string short left string , right string short right string , escaped chars \\ \\.## ] for s in testarray: print(Testing: %s % s) print Result: %s % unperl_format(s) print == Running this gives Testing: integer: , integer # integer at end # Result: integer: %4d, integer %1d integer at end %1d Testing: float .## no decimals ###. no int .### at end ###. Result: float %7.2f no decimals %4.0f no int %4.3f at end %4.0f Testing: Left string short left string Result: Left string %-6s short left string %-1s Testing: right string short right string Result: right string %6s short right string %1s Testing: escaped chars \ \.## \\ \\ Result: escaped chars \#%3d \#%6.2f \\%-3s \\%-3s -- Jim Segrave ([EMAIL PROTECTED]) -- http://mail.python.org/mailman/listinfo/python-list
Re: delete first line in a file
Fredrik Lundh wrote: Juergen Huber wrote: i am a dummy user in python and new in this programming language and so there will be questions, that´s for you no problem! i never have before programmed in any language! sorry for this! i hope you will help me, that i also could the basics in this language! and later many more, so i hope ! :) the first question for me in this newsgroup will be the follow one: - is there a way to delete in a csv-file the first line?! in general, modern file systems can only remove and add stuff at the end of a file, so the only way to do this is to rewrite the entire file. (you can either load the entire file, fix it up, and write it out again, or copy the file to a new file, skipping the first line or row). /F ok...i thought as much, that i have to copy this file! how will i do that?! how will i fix this file = delete the first line?! with which commands could i do that?! thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: FIXED: Re: optparse multiple arguments
Fredrik Lundh wrote: Ritesh Raj Sarraf wrote: http://docs.python.org/lib/optparse-standard-option-actions.html That won't help because by design of my program, I can't limit the number of arguments a user can pass to it. do you want options, arguments, or are you just somewhat confused ? /F I'm not sure about that. My program will accept user input. The user can input multiple arguments. maybe 1 or maybe 100, that's not definite. I do need option because this particular (multiple) argument criteria is for one single option. Thanks, Ritesh -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
On Fri, 30 Jun 2006 10:19:46 +, Michele Petrazzo wrote: Hi ng, what the preferred way for see if the dict has a key? We have a lot of solutions: key in dict key in dict.keys() dict.has_key(key) ... but what the better or the more pythonic? Thanks, Michele It is a religious call -- http://mail.python.org/mailman/listinfo/python-list
Re: Interprocess communication on multi-user machine
In article [EMAIL PROTECTED], [EMAIL PROTECTED] (Nick Maclaren) wrote: In article [EMAIL PROTECTED], Lawrence D'Oliveiro [EMAIL PROTECTED] writes: | In article [EMAIL PROTECTED], | Michael Butscher [EMAIL PROTECTED] wrote: | | Normally any user could connect to an open socket on a machine | regardless which user established the socket (the user's program, to be | precise). | | That's not true. On *nix systems, a socket is a file, and is subject to | the usual file ownership and protection mechanisms. I am afraid that BOTH answers are badly wrong! Sockets are often accessed via special files, but are not files. They are files. They are not _regular_ files. They may also be accessed by port numbers, for example. UNIX sockets have no ports. Secondly, even when they are accessed via files, FIFOs generally do NOT use the usual file ownership and protection mechanisms to control access. I wasn't talking about FIFOs. Even if I was, they _are_ still subject to regular file permissions (on Linux, at least). While any user can attempt to open any socket accessed by port number... UNIX sockets have no ports. -- http://mail.python.org/mailman/listinfo/python-list
Re: conecting with a MsAcces DB by dao
luis wrote: Iain King ha escrito: luis wrote: while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() I don't know if it's the problem your asking about, but your rs.MoveNext() should be inside the while loop, no? Yes, is inside You mean, it is inside the while loop in your code, but you made a mistake copying it into your post? In the code you posted it is not inside the while loop - it would have to be indented one more level for that. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Fredrik Lundh wrote: Michele Petrazzo wrote: what the preferred way for see if the dict has a key? We have a lot of solutions: key in dict new syntax (2.3 and later). So, following it, it can be used for the operations like len? len(dict) - len(dict.keys()) ? Thanks, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Michele Petrazzo wrote: Hi ng, what the preferred way for see if the dict has a key? We have a lot of solutions: key in dict key in dict.keys() dict.has_key(key) ... try: dict[key] except KeyError: ... else: ... but what the better Depends on the context. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: delete first line in a file
Juergen Huber wrote: ok...i thought as much, that i have to copy this file! how will i do that?! how will i fix this file = delete the first line?! with which commands could i do that?! start here: http://docs.python.org/tut/node9.html#SECTION00920 /F -- http://mail.python.org/mailman/listinfo/python-list
efficiency question
Hi, Suppose I write if x in (abc, def, xyz): doStuff() elif x in (pqr, tuv, 123): doOtherStuff() elif ... etc. When is python building the tuples? Does it need to build the tuple every time it comes through this code? Or does it somehow recognise that they are constant and cache them? In other words, is anything gained (efficiency-wise) by first putting say tuple1 = (abc, def, xyz) tuple2 = (pqr, tuv, 123) somewhere where I know it's executed once, and then writing if x in tuple1: doStuff() elif x in tuple2: doOtherStuff() elif ... (The tuples I have in mind are of course much longer than three elements) Many thanks David -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Michele Petrazzo wrote: key in dict new syntax (2.3 and later). So, following it, it can be used for the operations like len? what's it in this sentence? len(dict) - len(dict.keys()) ? len(dict.keys()) is a lousy way to spell len(dict). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Bruno Desthuilliers wrote: but what the better Depends on the context. If know only one context: see if the key are into the dict... What other context do you know? Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: efficiency question
David Harvey wrote: Suppose I write if x in (abc, def, xyz): doStuff() elif x in (pqr, tuv, 123): doOtherStuff() elif ... When is python building the tuples? Does it need to build the tuple every time it comes through this code? Or does it somehow recognise that they are constant and cache them? when in doubt, ask the compiler: def code(x): if x in (abc, def, xyz): doStuff() elif x in (pqr, tuv, 123): doOtherStuff() import dis dis.dis(code) prints: 2 0 LOAD_FAST0 (x) 3 LOAD_CONST 7 (('abc', 'def', 'xyz')) 6 COMPARE_OP 6 (in) 9 JUMP_IF_FALSE 11 (to 23) 12 POP_TOP 3 13 LOAD_GLOBAL 1 (doStuff) 16 CALL_FUNCTION0 19 POP_TOP 20 JUMP_FORWARD25 (to 48) 23 POP_TOP 4 24 LOAD_FAST0 (x) 27 LOAD_CONST 8 (('pqr', 'tuv', '123')) 30 COMPARE_OP 6 (in) 33 JUMP_IF_FALSE 11 (to 47) 36 POP_TOP 5 37 LOAD_GLOBAL 2 (doOtherStuff) 40 CALL_FUNCTION0 43 POP_TOP 44 JUMP_FORWARD 1 (to 48) 47 POP_TOP 48 LOAD_CONST 0 (None) 51 RETURN_VALUE so the answer is yes, in this specific case. (The tuples I have in mind are of course much longer than three elements) in that case, you should probably use pre-calculated sets instead of tuples. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: delete first line in a file
Fredrik Lundh wrote: Juergen Huber wrote: ok...i thought as much, that i have to copy this file! how will i do that?! how will i fix this file = delete the first line?! with which commands could i do that?! start here: http://docs.python.org/tut/node9.html#SECTION00920 /F that documentation i have already read, but it wouldn`t help me for my problem! i know, how i can read the first line an print them on the screen! but...how can i say python, delete the first line?! thats my problem! in the entry of my posting i wrote, that i am a newbie and so please understand me, that i ask so questions?! :-) thanks for your help! -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Fredrik Lundh wrote: Michele Petrazzo wrote: key in dict new syntax (2.3 and later). So, following it, it can be used for the operations like len? what's it in this sentence? It, is the thought that the new 2.3 introduce. Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Michele Petrazzo wrote: Bruno Desthuilliers wrote: but what the better Depends on the context. If know only one context: see if the key are into the dict... What other context do you know? Michele Perhaps Bruno meant this: try: ... my_dict[key] ... except: ... when we expect that the key will most often be in my_dict so that exception will be raised rarely, otherwise use if key in dict André -- http://mail.python.org/mailman/listinfo/python-list
Re: delete first line in a file
Juergen Huber wrote: but...how can i say python, delete the first line?! thats my problem! You can open the file, read its lines with readlines function ( that return a list), so make your modifies and save to another file. Now, do you know how to work with lists? http://python.org/doc/2.4.2/tut/node5.html#SECTION00514 and now you have only to wrote it http://python.org/doc/2.4.2/tut/node9.html#SECTION00920 Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: delete first line in a file
Juergen Huber wrote: start here: http://docs.python.org/tut/node9.html#SECTION00920 that documentation i have already read, but it wouldn`t help me for my problem! that documentation and a little experimentation should be all you need. i know, how i can read the first line an print them on the screen! but...how can i say python, delete the first line?! thats my problem! read the first line, and ignore it. then read all the other lines, and write them to a new file. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: delete first line in a file
Juergen Huber schrieb: Fredrik Lundh wrote: Juergen Huber wrote: ok...i thought as much, that i have to copy this file! how will i do that?! how will i fix this file = delete the first line?! with which commands could i do that?! start here: http://docs.python.org/tut/node9.html#SECTION00920 /F that documentation i have already read, but it wouldn`t help me for my problem! i know, how i can read the first line an print them on the screen! but...how can i say python, delete the first line?! thats my problem! in the entry of my posting i wrote, that i am a newbie and so please understand me, that i ask so questions?! :-) thanks for your help! simple! f = file(old.file) ignore = f.readline() file(new.file, w+).write(f.read()) hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Interprocess communication on multi-user machine
In article [EMAIL PROTECTED], Lawrence D'Oliveiro [EMAIL PROTECTED] writes: | | Sockets are often accessed via special files, but are not files. | | They are files. They are not _regular_ files. Sigh. Firstly, look at something like: http://www.opengroup.org/onlinepubs/009695399/toc.htm Start at the entry 'socket' and work from there. Yes, I know about UNIX-domain sockets, but even when they give the appearance of being files, 90% of the time that is the API only, and the underlying facility is very different. Dammit, processes are not files just because they happen to have a /proc entry under many systems! | They may also be accessed by port numbers, for example. | | UNIX sockets have no ports. You mean UNIX-domain, not UNIX. So? Many sockets do. Internet- domain ones always do. | I wasn't talking about FIFOs. Even if I was, they _are_ still subject to | regular file permissions (on Linux, at least). They aren't on most Unices - Linux is not UNIX, you know :-) I shall not respond further on this. Regards, Nick Maclaren. -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
André wrote: Michele Petrazzo wrote: Bruno Desthuilliers wrote: but what the better Depends on the context. If know only one context: see if the key are into the dict... What other context do you know? Michele Perhaps Bruno meant this: try: ... my_dict[key] ... except: Yes I see :) when we expect that the key will most often be in my_dict so that exception will be raised rarely I didn't thought this because if I think that a key aren't in a dict, I use dict.get(key, default) otherwise use if key in dict André Thanks to all, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Michele Petrazzo wrote: Michele Petrazzo wrote: key in dict new syntax (2.3 and later). So, following it, it can be used for the operations like len? what's it in this sentence? It, is the thought that the new 2.3 introduce. support for key in dictionary form was added in 2.3 (in earlier versions, in was only supported for sequences, not for mappings). len(dictionary) works in all Python versions. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Michele Petrazzo wrote: Bruno Desthuilliers wrote: but what the better Depends on the context. If know only one context: see if the key are into the dict... What other context do you know? Michele Why do you want to do that ? if key in dict: value = dict[key] else: value = None could be write: try: value = dict[key] except KeyError: value = None so depends of the context... -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
André wrote: Perhaps Bruno meant this: try: ... my_dict[key] ... except: ... when we expect that the key will most often be in my_dict so that exception will be raised rarely, otherwise use on my machine, key in dict is about twice as fast as the full try/getitem con- struct when the key is present in the dict, so that's not a very good optimization. now, if the OP had been interested in the associated value, things might have been a bit different. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
looping wrote: Michele Petrazzo wrote: Bruno Desthuilliers wrote: but what the better Depends on the context. If know only one context: see if the key are into the dict... What other context do you know? Why do you want to do that ? if key in dict: value = dict[key] else: value = None could be write: value = dict.get(key, None) (snip) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: efficiency question
For the sake of comparison: def cod(x): ... tupple1 = (abc, def, xyz) ... tupple2 = (pqr, tuv, 123) ... if x in tupple1: ... doStuff() ... elif x in tupple2: ... doOtherStuff() ... dis.dis(cod) 2 0 LOAD_CONST 7 (('abc', 'def', 'xyz')) 3 STORE_FAST 2 (tupple1) 3 6 LOAD_CONST 8 (('pqr', 'tuv', '123')) 9 STORE_FAST 1 (tupple2) 4 12 LOAD_FAST0 (x) 15 LOAD_FAST2 (tupple1) 18 COMPARE_OP 6 (in) 21 JUMP_IF_FALSE 11 (to 35) 24 POP_TOP 5 25 LOAD_GLOBAL 3 (doStuff) 28 CALL_FUNCTION0 31 POP_TOP 32 JUMP_FORWARD25 (to 60) 35 POP_TOP 6 36 LOAD_FAST0 (x) 39 LOAD_FAST1 (tupple2) 42 COMPARE_OP 6 (in) 45 JUMP_IF_FALSE 11 (to 59) 48 POP_TOP 7 49 LOAD_GLOBAL 4 (doOtherStuff) 52 CALL_FUNCTION0 55 POP_TOP 56 JUMP_FORWARD 1 (to 60) 59 POP_TOP 60 LOAD_CONST 0 (None) 63 RETURN_VALUE -- http://mail.python.org/mailman/listinfo/python-list
Re: logging error with RotatingFileHandler
Vinay Sajip schreef: flupke wrote: If this bug is fixed, where will i find a fixed version and how do i install it? Also, more important to me, what am i doing wrong to get this error message in the first place? You're not doing anything particularly wrong, though it's not exactly good practice to call fileConfig lots of times. (It's really meant for one-off configuration, not incremental configuration.) I get an error with just the following script typed in at the interactive prompt: import logging.config logging.config.fileConfig(logconf.ini) logging.config.fileConfig(logconf.ini) So, I will investigate, and when I check in a fix to the Python Subversion repository, I will post a message to this thread. Regards, Vinay Sajip Hi Vinay, thanks for the info. I tried to change the handlers.py file. First, i changed some code in doRollover. if os.path.exists(dfn): os.remove(dfn) try: #os.rename(self.baseFilename, dfn) - The rename fails for some reason. I tried with the move function of shutil shutil.move(self.baseFilename, dfn) This partially works: the file is now rotated but i still get an error: The error that i get is this: Error [Errno 13] Permission denied: 'E:\\python\\proj1\\src\\proj1.log' Traceback (most recent call last): File C:\Python24\lib\logging\handlers.py, line 72, in emit self.doRollover() File C:\Python24\lib\logging\handlers.py, line 141, in doRollover self.handleError(record) NameError: global name 'record' is not defined The last part of the error shows that the part where the exception is caugth is also not working correctly as the record isn't know. When i close my program, i get this error as well: Error in atexit._run_exitfuncs: Traceback (most recent call last): File C:\Python24\lib\atexit.py, line 24, in _run_exitfuncs func(*targs, **kargs) File C:\Python24\lib\logging\__init__.py, line 1333, in shutdown h.close() File C:\Python24\lib\logging\__init__.py, line 772, in close StreamHandler.close(self) File C:\Python24\lib\logging\__init__.py, line 674, in close del _handlers[self] KeyError: logging.handlers.RotatingFileHandler instance at 0x01E098A0 Error in sys.exitfunc: Traceback (most recent call last): File C:\Python24\lib\atexit.py, line 24, in _run_exitfuncs func(*targs, **kargs) File C:\Python24\lib\logging\__init__.py, line 1333, in shutdown h.close() File C:\Python24\lib\logging\__init__.py, line 772, in close StreamHandler.close(self) File C:\Python24\lib\logging\__init__.py, line 674, in close del _handlers[self] KeyError: logging.handlers.RotatingFileHandler instance at 0x01E098A0 Regards Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehension
tac-tics wrote: a wrote: can someone tell me how to use them thanks sigh... You do a google on them: http://docs.python.org/tut/node7.html#SECTION00714 thank you for the reminder. But after reading it, I was left with a question. Why the new syntax for what appears to be nothing more than a different way of expressing nested for loops? at first I tried rearranging the one of the examples from the previously referenced document to clarify (in my mind) what was going on: [x*y for x in vec1 for y in vec2 ] then when I tried to rewrite it as a nested for loop, that's when I realized list comprehensions is a method of returning the calculation in the interior of a for loop as an assignment without requiring aggregation of results in a temporary variable. so a double thank you to you because you've clarified something that has been a mystery to me for awhile. now if I could find someone to explain distutils and eggs so that I understand that as well... ;-) Heck, I would even settle for a wizard tool generating the first approximation for me. ---eric -- http://mail.python.org/mailman/listinfo/python-list
Re: conecting with a MsAcces DB by dao
Iain King ha escrito: luis wrote: Iain King ha escrito: luis wrote: while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() I don't know if it's the problem your asking about, but your rs.MoveNext() should be inside the while loop, no? Yes, is inside You mean, it is inside the while loop in your code, but you made a mistake copying it into your post? In the code you posted it is not inside the while loop - it would have to be indented one more level for that. Iain this is te correct identation def append_from_Access(self): try: import ... conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:/Afile.mdb; conn.Open(DSN) except Exception, inst: ... try: sql_statement='SELECT * FROM Mytable' rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(sql_statement, conn, 1, 3) while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() except Exception, inst: ... I think my problem must be with ado and dao. Now I have run makepy utility and select Microsoft ActiveX Data Objects 2.5 Library, perhaps I must also select Microsoft DAO3.5 Object Library and write win32com.client.Dispatch(DAO.DBEngine.35) for Access 97 or win32com.client.Dispatch(r'ADODB.Connection') for Acess 2000 Do you know is it possible ? luis -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2exe make wxPython window looks bad
zdp schrieb: But when I convert the program to EXE file by Py2exe, and run it, the look feel is bad. It's just like the windows 9x. All controls has a thick and emboss border. However, the scrollbars look good, same as the window XP. XP needs a manifest file in the setup.py or as a single file in the program dir. See examples in the py2exe installation dir. Andreas -- http://mail.python.org/mailman/listinfo/python-list
Can't connect to Oracle DB via DCOracle2 as sysdba
Hi, how can I connect please to DB Oracle9i via DCOracle.Connect as SYSDBA? dbc = DCOracle2.connect(user='user', password= 'password as sysdba' )u,p2: sys,'pTraceback (most recent call last): File "stdin", line 1, in ? File "C:\Program Files\Python21\lib\DCOracle2\DCOracle2\DCOracle2.py", line 186, in connect #print "Created new DCO2 connection %s" % conndco2.DatabaseError: (1017, 'ORA-01017: invalid username/password; logon denied') How can I connect via DCOracle2 in Python to Database? as usually mit sqlplus in command line: sqlplus "user/password as sysdba" Thanks for every idea! Josef -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehension
Simon Forman wrote: There's more to it, but that's the basic idea. This much I knew, but _why_ and _when_ would I choose to use list comprehension (for good Python style), rather than using a simple traditional loop ? If I want to generate something that's simply ( [1] + [2] + [3]+... ) then list comprehension is obviously the tool of choice. I suspect though that there's more to it than this. Is list comprehension also treatable as a sneaky concise formulation for nested lists, where they're as much about selection of individual elements, so much as concatenation of the sequence? What happens if a comprehension has side effects, such as from calling a function within it? Is this regarded as good or bad coding style? Is it evil (as structured programming would claim) or is it a concise formulation for an iterator or visitor pattern ? -- http://mail.python.org/mailman/listinfo/python-list
finding the last file created in a directory
Hello everyone, I have a repeatedly running process, which always creates a new logfile with an ending n+1. What I need is to find the last file, the one with highest number at the end. The problem is, that the max() method gives me a wrong answer. I tried to convert the items in my list into integers using int(), but that ends up with an error ValueError: invalid literal for int(): My code currently looks like this: def get_logfile(dir, file_name): new_file_name = file_name[:-3] + 'log' listing = glob.glob(dir + new_file_name + '*') numbers = [] for i in range(len(listing)): item = listing[i] numbers.append(item[len(dir) + len(new_file_name) + 1:]) return new_file_name + '.' + max(numbers) cheers Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Fredrik Lundh wrote: André wrote: Perhaps Bruno meant this: try: ... my_dict[key] ... except: ... when we expect that the key will most often be in my_dict so that exception will be raised rarely, otherwise use on my machine, key in dict is about twice as fast as the full try/getitem con- struct when the key is present in the dict, Doesn't it depends on the number of keys in the dict ? so that's not a very good optimization. FWIW, I personaly didn't meant to present it as an optimisation - just as one more possible way to test the existence of a given key... now, if the OP had been interested in the associated value, things might have been a bit different. /F -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: delete first line in a file
this helps me! thank you very much! greetings, juergen JH Fredrik Lundh wrote: Juergen Huber wrote: ok...i thought as much, that i have to copy this file! how will i do that?! how will i fix this file = delete the first line?! with which commands could i do that?! start here: http://docs.python.org/tut/node9.html#SECTION00920 /F JH that documentation i have already read, but it wouldn`t help me for my JH problem! JH i know, how i can read the first line an print them on the screen! JH but...how can i say python, delete the first line?! JH thats my problem! as Fredrik told you, you can not delete the first line directly!!! JH in the entry of my posting i wrote, that i am a newbie and so please JH understand me, that i ask so questions?! :-) We are trying to understand that, but it is expected some effort on your side as well :) You didn't read the documentation properly! try to experiment with the code by yourself as well! Try: 1) open your file 2) use readlines() method which returns the list of ALL rows from the file and store them to some variable. it can be done for example like: all_lines = f.readlines() (if you do not know, what the list is, start here: http://docs.python.org/tut/node5.html#SECTION00514) 4) save the list members without its first member to the file for example: for line in all_lines[1:]: f.write(line) 5) close the file Good luck Petr Jakes JH thanks for your help! -- http://mail.python.org/mailman/listinfo/python-list
Re: logging error with RotatingFileHandler
flupke schreef: snip Hi Vinay, thanks for the info. I tried to change the handlers.py file. First, i changed some code in doRollover. if os.path.exists(dfn): os.remove(dfn) try: #os.rename(self.baseFilename, dfn) - The rename fails for some reason. I tried with the move function of shutil shutil.move(self.baseFilename, dfn) This partially works: the file is now rotated but i still get an error: The error that i get is this: Error [Errno 13] Permission denied: 'E:\\python\\proj1\\src\\proj1.log' Traceback (most recent call last): File C:\Python24\lib\logging\handlers.py, line 72, in emit self.doRollover() File C:\Python24\lib\logging\handlers.py, line 141, in doRollover self.handleError(record) NameError: global name 'record' is not defined The last part of the error shows that the part where the exception is caugth is also not working correctly as the record isn't know. When i close my program, i get this error as well: Error in atexit._run_exitfuncs: Traceback (most recent call last): File C:\Python24\lib\atexit.py, line 24, in _run_exitfuncs func(*targs, **kargs) File C:\Python24\lib\logging\__init__.py, line 1333, in shutdown h.close() File C:\Python24\lib\logging\__init__.py, line 772, in close StreamHandler.close(self) File C:\Python24\lib\logging\__init__.py, line 674, in close del _handlers[self] KeyError: logging.handlers.RotatingFileHandler instance at 0x01E098A0 Error in sys.exitfunc: Traceback (most recent call last): File C:\Python24\lib\atexit.py, line 24, in _run_exitfuncs func(*targs, **kargs) File C:\Python24\lib\logging\__init__.py, line 1333, in shutdown h.close() File C:\Python24\lib\logging\__init__.py, line 772, in close StreamHandler.close(self) File C:\Python24\lib\logging\__init__.py, line 674, in close del _handlers[self] KeyError: logging.handlers.RotatingFileHandler instance at 0x01E098A0 Regards Benedict I was able to solve the errors (i think): 1. in the function doRollover of the class RotatingFileHandler if os.path.exists(dfn): os.remove(dfn) try: os.rename(self.baseFilename, dfn) I added this instead of the rename function: import shutil shutil.copy(self.baseFilename, dfn) If this code works ok, then the import shutil should be placed at the top of the file for performance reasons. The logic of the copy is that a few statements later, the self.stream var is set to a new file again so it doesn't need to be deleted. At least it seems to work here. I will need to test further. Weird thing is, the stream is closed and yet you get this error when you use rename: [Errno 13] Permission denied 2. in the same function, when an error occurred, the record var wasn't found. This can be solved by changing the code of emit in BaseRotatingHandler. Change this: if self.shouldRollover(record): self.doRollover() by: if self.shouldRollover(record): self.doRollover(record) 3. The last error (error when closing the program) can be solved by editing the __init__.py, close(self) function. Change this: _acquireLock() try:#unlikely to raise an exception, but you never know... del _handlers[self] _handlerList.remove(self) finally: _releaseLock() by: _acquireLock() try:#unlikely to raise an exception, but you never know... #del _handlers[self] if ( _handlers.has_key(self) ): del _handlers[self] #if ( self in _handlerList ): _handlerList.remove(self) _handlerList.remove(self) finally: _releaseLock() It might even be better to change the _handlerList.remove(self) statement by this statement: if ( self in _handlerList ): _handlerList.remove(self) Regards, Benedict Verheyen -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehension
Andy Dingley [EMAIL PROTECTED] wrote: Simon Forman wrote: There's more to it, but that's the basic idea. This much I knew, but _why_ and _when_ would I choose to use list comprehension (for good Python style), rather than using a simple traditional loop ? Whenever it's more readable. If I want to generate something that's simply ( [1] + [2] + [3]+... ) then list comprehension is obviously the tool of choice. I suspect though that there's more to it than this. Is list comprehension also treatable as a sneaky concise formulation for nested lists, where they're as much about selection of individual elements, so much as concatenation of the sequence? I've read this last sentence three times now and I'm still not sure to grasp it - hopefully it's friday... Care to give an example ? What happens if a comprehension has side effects, such as from calling a function within it? Is this regarded as good or bad coding style? Is it evil (as structured programming would claim) or is it a concise formulation for an iterator or visitor pattern ? I'd say it's bad style to call a function having side effects from within a list comp. List comps have a very declarative/functional style, while side effects are clearly on the imperative side. I never took time to think about this, but IIRC I've never used list comp that way - I then use a for loop. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Bruno Desthuilliers wrote: looping wrote: Michele Petrazzo wrote: Bruno Desthuilliers wrote: but what the better Depends on the context. If know only one context: see if the key are into the dict... What other context do you know? Why do you want to do that ? if key in dict: value = dict[key] else: value = None could be write: value = dict.get(key, None) value = dict.get(key) ;) Georg -- http://mail.python.org/mailman/listinfo/python-list
RE: Way for see if dict has a key
If dict.has_key('key'): print dict[''] Josef Cihal -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Georg Brandl Sent: Friday, June 30, 2006 5:07 PM To: python-list@python.org Subject: Re: Way for see if dict has a key Bruno Desthuilliers wrote: looping wrote: Michele Petrazzo wrote: Bruno Desthuilliers wrote: but what the better Depends on the context. If know only one context: see if the key are into the dict... What other context do you know? Why do you want to do that ? if key in dict: value = dict[key] else: value = None could be write: value = dict.get(key, None) value = dict.get(key) ;) Georg -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re[2]: delete first line in a file
JH this helps me! JH thank you very much! JH greetings, juergen I am happy to see my postings (which I sent by accident to you only, not to the list, see below) helped. But: Its a pity we can not see your solution (your code) here :( It helps to others as well to see, how to solve some problems Petr Jakes JH that documentation i have already read, but it wouldn`t help me for my JH problem! JH i know, how i can read the first line an print them on the screen! JH but...how can i say python, delete the first line?! JH thats my problem! PJ as Fredrik told you, you can not delete the first line directly!!! JH in the entry of my posting i wrote, that i am a newbie and so please JH understand me, that i ask so questions?! :-) PJ We are trying to understand that, but it is expected some effort on PJ your side as well :) PJ You didn't read the documentation properly! PJ try to experiment with the code by yourself as well! PJ Try: PJ 1) open your file PJ 2) use readlines() method PJ which returns the list of ALL rows from the file and store them to some PJ variable. PJ it can be done for example like: PJ all_lines = f.readlines() PJ (if you do not know, what the list is, start here: PJ http://docs.python.org/tut/node5.html#SECTION00514) PJ 4) save the list members without its first member to the file PJ for example: PJ for line in all_lines[1:]: PJ f.write(line) PJ 5) close the file JH Good luck JH Petr Jakes JH thanks for your help! -- http://mail.python.org/mailman/listinfo/python-list
Re: finding the last file created in a directory
I have a repeatedly running process, which always creates a new logfile with an ending n+1. What I need is to find the last file, the one with highest number at the end. The problem is, that the max() method gives me a wrong answer. I tried to convert the items in my list into integers using int(), but that ends up with an error ValueError: invalid literal for int(): The int() call should be passed only strings that are numeric...if you've got other bits of your filename in there (such as, in your code, the terminal period), it will likely choke on them with the above-mentioned ValueError. Presuming your filenames are of the form file.log (adjustable by altering the 'filename' and 'suffix' variables) filename = 'file' suffix = '.log' # create ourselves some sample filenames as one # might get from globbing filenames = ['%s%s%s' % (filename, i, suffix) for i in range(1,30, 7)] filenames ['file1.log', 'file8.log', 'file15.log', 'file22.log', 'file29.log'] # extract the maximum number from the list of file numbers: max_file_number = max([int(s[len(filename):-len(suffix)]) for s in filenames]) max_file_number 29 As you can see, it handles disjoint spans of file numbers, so even if you delete items in the middle, it should still find the max. There is a race condition in this in the event that you have multiple items attempting to write the file-name at hand. Thus, between the time you get the max_file_number+1, and you open the file, some other process might have created a file with that number. Use with caution accordingly. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: efficiency question
Fredrik Lundh wrote: when in doubt, ask the compiler: MTD wrote: dis.dis(cod) Thanks so much guys! Python just gets cooler every day! David -- http://mail.python.org/mailman/listinfo/python-list
Re: conecting with a MsAcces DB by dao
luis wrote: Iain King ha escrito: luis wrote: Iain King ha escrito: luis wrote: while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() I don't know if it's the problem your asking about, but your rs.MoveNext() should be inside the while loop, no? Yes, is inside You mean, it is inside the while loop in your code, but you made a mistake copying it into your post? In the code you posted it is not inside the while loop - it would have to be indented one more level for that. Iain this is te correct identation def append_from_Access(self): try: import ... conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:/Afile.mdb; conn.Open(DSN) except Exception, inst: ... try: sql_statement='SELECT * FROM Mytable' rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(sql_statement, conn, 1, 3) while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() except Exception, inst: ... I think my problem must be with ado and dao. Now I have run makepy utility and select Microsoft ActiveX Data Objects 2.5 Library, perhaps I must also select Microsoft DAO3.5 Object Library and write win32com.client.Dispatch(DAO.DBEngine.35) for Access 97 or win32com.client.Dispatch(r'ADODB.Connection') for Acess 2000 Do you know is it possible ? luis Well, without being able to test on your system I don't think I can give you any real advice. This is the module I use to interface with Access: Access.py --- import win32com.client from win32com.client import constants def isWriteable(field): Is given Field writeable? return field.Attributes 4 class Access(object): def __init__(self, filename, password=): self._filename = filename self._connection = win32com.client.Dispatch(r'ADODB.Connection') if password: self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=%s;Jet OLEDB:Database Password=%s;' % (filename, password) else: self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=%s;' % (filename) def Query(self, query): self._connection.Open(self._DSN) rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(query, self._connection, 1, 3) fields = [] for x in xrange(rs.Fields.Count): fields.append(rs.Fields(x).Name) if rs.EOF: data = [] else: data = rs.GetRows() rs.Close() self._connection.Close() return fields, data def Add(self, table, records): Adds records to table. self._connection.Open(self._DSN) rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(table, self._connection, 1, 3) unwriteables = [] for record in records: rs.AddNew() unwriteable = [] for i in xrange(len(record)): if isWriteable(rs.Fields(i)): rs.Fields(i).Value = record[i] else: unwriteable.append(rs.Fields(i).Value) unwriteables.append(unwriteable) rs.Update() rs.Close() self._connection.Close() return unwriteables def Update(self, query, function): Updates all records found in query with function(record) self._connection.Open(self._DSN) rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(query, self._connection, 1, 3) columns = rs.Fields.Count while not rs.EOF: record = [] for i in xrange(columns): record.append(rs.Fields(i).Value) newRecord = function(record[:]) for i in xrange(columns): if isWriteable(rs.Fields(i)): rs.Fields(i).Value = newRecord[i] rs.MoveNext() rs.Close() self._connection.Close() def Delete(self, query): Deletes all records found in query self._connection.Open(self._DSN) rs =
Re: Reddit broke - should have remained on Lisp?
Alok wrote: Luis M. González wrote: Alok wrote: I was merely describing my experience and inviting others' response about theirs. That's exactly what I'm doing. You misinterpret, I was talking about my experience with the site and inviting response from other people about their experience with the site. Now, I don't know much about python or lisp, but I have read about this web-site's history with the two programming languages. And hence I chose to post in comp.lang.lisp and comp.lang.python. Now if there were a reddit.technology.lisp or reddit.technology.python, and if they had the same traction as these usenet groups, then I could have posted there. But that was not an option was it. Please don't misconstrue that as a blame on any language. I think it can be interpreted in many ways. Can you please explain what your interpretation is? Now if you're not ready to read other people's oppinions, don't ask. Now, I think you are unfairly prejudiced about my not wanting to read other people's opinion. I would rather have a 1000 acrid responses to something I write and learn from it, than post into a responseless vacuum. And of course, I disagree with your comments about ridicule etc. Ok. Dear Alok, I think is you who are misinterpreting me (or I didn't make myself clear). You posted a link to a joke from reddit, which is perfectly fine, is very funny. But below, you added a comment wondering whether the change from Lisp to Python may be a reason for a huge performance loss. I'm not a python bigot, but I just said that blamming a language choice for such a deficieny was ridiculous. There are hundreds of very complex web sites developed in python that doesn't suffer these problems, and, even if they are developed in python, you must take into account which other technologies they are using for deployment (web server, framework, mod_python, cgi, fastcgi, hardware, etc, etc...). Also, the fact that someone could be more versed or knowledgeable of one language compared to another one, doesn't make it better or worse. This is s subjective fact, and has nothing to do with the language. It has to do with who's using the language. Also, as someone pointed out above, don't you think that the huge incresement of traffic since they switched to python may have had something to do with this problem? Perhaps, their lack of experise in a new language didn't prepare them for facing such a challenge. Who knows? Yeah, perhaps if they sticked to Lisp, they could have handled the problem better. They are lispers, aren't they? Anyway, you posted a comment, you asked for opinons, you got mine. Sorry if I ofended you. It wasn't my intention. I'll make sure I place more smileys in my posts to avoid hurting feelings from now on :-) Luis -- http://mail.python.org/mailman/listinfo/python-list
string replace
Hi, a lot of times I need to replace more than one char into a string, so I have to do something like value = test chars = e for c in chars: value = value.replace(c, ) A solution could be that replace accept a tuple/list of chars, like that was add into the new 2.5 for startswith. I don't know, but can be this feature included into a future python release? Thanks, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Way for see if dict has a key
Michele Petrazzo [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] when we expect that the key will most often be in my_dict so that exception will be raised rarely I didn't thought this because if I think that a key aren't in a dict, I use dict.get(key, default) Another factor to consider is if default is not something simple like 0 or None, but is an object constructed and initialized with some expensive initialization code (like access to a database). In this case: dict.get(key, ExpensiveObjectToCreate()) always creates the default value, and if the key does not exist, then promptly drops it on the floor. In such a case you'd be better off with one of the check for existence patterns, which only creates the default value if you *know* you're going to need it. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
print shell output in a file
hello, one more question i will have! now i have written a little programm, which delivers me an output on the shell! here is the print command, which delivers me the following output (see below) on the shell: print '%-30s | %-12d | %-12d |%-12d ' % (typename, size / count, count, size) --NAME-|Groesse(Byte)-|Anzahl|-Gesamtgroesse (Byte)-| -- ADD_REAL_N6| 4| 1|4 AND_BOOL_N10 | 4| 1|4 AND_BOOL_N12 | 4| 1|4 Is there a way to put this output in an file?!?! i searched about 2h for this, but i couldn`t find an answer! thnks, juergen -- http://mail.python.org/mailman/listinfo/python-list
RE: string replace
Hi Mechele, In string s u want to replace string b or c to - x import re s =a1b2c3 re.sub([bc],x,s) Sincerely josef Josef -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Michele Petrazzo Sent: Friday, June 30, 2006 4:03 PM To: python-list@python.org Subject: string replace Hi, a lot of times I need to replace more than one char into a string, so I have to do something like value = test chars = e for c in chars: value = value.replace(c, ) A solution could be that replace accept a tuple/list of chars, like that was add into the new 2.5 for startswith. I don't know, but can be this feature included into a future python release? Thanks, Michele -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: string replace
A solution could be that replace accept a tuple/list of chars, like that was add into the new 2.5 for startswith. I don't know, but can be this feature included into a future python release? I don't know, but I think it would be useful as for now I use this import re chars = re.compile(r'[abc]') text = aAbBcCdD chars.sub(,text) 'ABCdD' Thanks, Michele Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: string replace
a lot of times I need to replace more than one char into a string, so I have to do something like value = test chars = e for c in chars: value = value.replace(c, ) A solution could be that replace accept a tuple/list of chars, like that was add into the new 2.5 for startswith. I don't know, but can be this feature included into a future python release? Well, another way of doing it would be values = this is a test chars = aeiou .join([c for c in values if c not in chars]) 'ths s tst' If your either your chars is a large set or you're performing this repeatedly with the same set of chars, you might want the speed of membership-testing that one would get from a true set: charset = set(chars) # do this once for the set # do the following as many times as you like in loops, etc. .join([c for c in values if c not in charset]) 'ths s tst' HTH, -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Icono en wxpython
Thank. But I to solve my problem. On other hand I commented that I writed a litle program for to send and to recive data from the Serial Port in byte format, no chars. I wanted publish this GNU program in brief. Do you would like to translate to frances? Thank -- http://mail.python.org/mailman/listinfo/python-list
No Cookie: how to implement session?
I don't understand the reason for 'Cookies'. When you are pay to belong to AOL or another network why is it necessary to set upan additionaladdress in order to be able to have access to some information? We are not all computer talented, even at this date. Some of us only use it for convenience in our every day life, why make it more complex? -- http://mail.python.org/mailman/listinfo/python-list
Re: string replace
In article [EMAIL PROTECTED], Michele Petrazzo [EMAIL PROTECTED] wrote: Hi, a lot of times I need to replace more than one char into a string, so I have to do something like value = test chars = e for c in chars: value = value.replace(c, ) A solution could be that replace accept a tuple/list of chars, like that was add into the new 2.5 for startswith. I don't know, but can be this feature included into a future python release? Let's say you want to make every vowel uppercase: import string trans_table = string.maketrans('aeiou', 'AEIOU') I don't know, but can be this feature included into.translate(trans_table) prints: I dOn't knOw, bUt cAn bE thIs fEAtUrE InclUdEd IntO That more than addresses your requirements, as it can do multiple character substitutions multiple times in one call. -- Jim Segrave ([EMAIL PROTECTED]) -- http://mail.python.org/mailman/listinfo/python-list