wxPython Grid Question
Hey Peoples, I'm wonderg if there is a way to make a subclass of wx.grid.Grid in which the coloumn labels for the grid appear on the bottom of the grid instead of the top. 1 2 3 4 5 a| | | | | | b| | | | | | c| | | | | | d| | | | | | e| | | | | | Just in case that wasn't clear (and because I just feel like typing more): The above grid has labels in the normal placement. The grid below has the labels in the places I want them. a| | | | | | b| | | | | | c| | | | | | d| | | | | | e| | | | | | 1 2 3 4 5 Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: uploading files to file system/zipping/downloading problems
Assuming your upload_file.file.read() function works, the overwriting should be the only issue. Just want to point out that total_data += data is not advisable for this example (speed/efficiency issue, although i'm sure it could probably be even faster than what I replace it with if u decided to use arrays, but it's probably not worth it XD), and I think open() was replaced by file(), although they're probably interchangable. new code - total_data = ' ' temp_data = [] while True: data = upload_file.file.read(8192) if not data: break temp_data.append(data) total_data = ' '.join(temp_data) somefile = file(target_file_name, 'wb') somefile.write(total_data) f.close() --- OriginalBrownster wrote: > I am currently uploading a file from a users computer to the file > system on my server using python, just reading the file and writing the > binaries. > > total_data=' ' > while True: > data = upload_file.file.read(8192) > if not data: > break > total_data += data > f = open(target_file_name, 'wb') > f.write(total_data) > f.close > > However when i download the file from the server it is not intact and > it cannot be opened. It is happening with every type of file. > > It seemed to be working before and now it is..maybe I goofed up and > deleted something. > However I can't seem to find it. > > any ideas?? -- http://mail.python.org/mailman/listinfo/python-list
Re: intercepting keypresses, mouse movements, joystick movements.
Another option is to look at pywin32, which I believe has the SetWindowsHook[Ex] commands, or to use ctypes (which is built in if you're using python2.5) to load the neccessary dll's to use that function. However, pyHook should be good unless you need something for the joystick (don't think that's covered), or for detecting system or dead keys (unless pyHook has been updated recently, the last time I checked the docs said it didn't capture those keys). Good Luck, Jordan TheSeeker wrote: > bryan rasmussen wrote: > > Hi, > > > > I've been looking at autohotkey to do some different usability hacks > > for windows http://www.autohotkey.com/ > > one of the benefits of this language is it allows one to catch > > keyboard usage, joystick usage, and mouse usage inputs very easily at > > a global level or at application levels by watching applications for > > events within the applications. > > > > I was wondering if there were any python libraries that provided > > similar functionality before I went ahead with the project though. > > > > Cheers, > > Bryan Rasmussen > > You might take a look at pyHook: > http://sourceforge.net/project/showfiles.php?group_id=65529&package_id=92632 -- http://mail.python.org/mailman/listinfo/python-list
Re: external file closed
I think the win32all extension includes the findwindow() fuction, so
you could make a loop that looks for the window name (or class if it
takes that) of the pdf. You can also loop through a list of running
processes looking for whatever the process name is. Note that both of
these have serious loopholes, such as if there is more than one pdf
open.
Cheers,
Jordan
utabintarbo wrote:
> Jerry wrote:
> > On Oct 17, 12:43 pm, "kilnhead" <[EMAIL PROTECTED]> wrote:
> > > I am opening a file using os.start('myfile.pdf') from python. How can I
> > > know when the user has closed the file so I can delete it? Thanks.
> >
> > I assume you mean os.startfile. There is no way to do this directly.
> > os.startfile simply hands off the call to the OS and doesn't provide
> > anything to track anything after that. Since you won't know what
> > program handled the file association, you couldn't watch for an
> > instance of that to start up and detect when it exits. Even if you
> > could, it wouldn't be reliable as in the case of PDF's and Adobe
> > Acrobat Reader, the user could close the document, but not the
> > application, so your script would never delete the file in question.
> >
> > If anyone can think of a way to do this, it would be interesting to see
> > how it's done.
> >
> > --
> > Jerry
>
> os.system('myfile.pdf') will give return code upon closing. This can
> also be done using the subprocess module with poll().
--
http://mail.python.org/mailman/listinfo/python-list
Re: 3d programming without opengl
I don't thnk you should have any problems using Slut with wxpython - wx would be much less amazing if it couldn't do something like that. On the other hand, I thought that you were looking for something that doesn't use openGL and I think that Slut is built around it. Cheers, Jordan nelson - wrote: > Hi paul, > i look at slut and it seem very good... Can i embed it into a > wxpython application? > > thanks, > nelson -- http://mail.python.org/mailman/listinfo/python-list
Re: help using smtplib to work ..
Your post was definitely the most helpful for me. For some reason,
smtp for gmail seems to require that you call server.ehlo() a second
time, after having called server.starttls(), otherwise, the server
won't accept authorization. Thanks.
-Jordan
Gabriel Genellina wrote:
> At Wednesday 8/11/2006 19:23, NicolasG wrote:
>
> >I'm using the following code to send e-mail through python:
> >
> >import smtplib
> >
> >fromaddr = '[EMAIL PROTECTED]'
> >toaddrs = '[EMAIL PROTECTED]'
> >subject = 'someting for subject !'
> >
> >msg = 'This is body of the mail.'
> >
> >msg = 'From: ' + fromaddr + '\nTo: ' + toaddrs + '\nSubject:' + subject
> >+ '\n\n' + msg
> >print "Message length is " + repr(len(msg))
> >
> >server = smtplib.SMTP('smtp.gmail.com')
> >server.set_debuglevel(1)
> >server.sendmail(fromaddr, toaddrs, msg)
> >server.quit()
> >
> >send: 'mail FROM:<[EMAIL PROTECTED]> size=106\r\n'
> >reply: '530 5.7.0 Must issue a STARTTLS command first
> >s1sm7666914uge\r\n'
> >
> >What am I doing wrong ?
>
> gmail.com requires authentication before sending mail. Try this
> sequence: ehlo, starttls, ehlo (again!), login, sendmail, quit
> (BTW, you need a space after Subject:, and all \n should be \r\n)
>
>
> --
> Gabriel Genellina
> Softlab SRL
>
> __
> Correo Yahoo!
> Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
> ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python development time is faster.
Just a little something I realized after writing the same program in C++ and python (a simple chat client and server, with one on one and chat room capabilities). I used wxwidgets and wxpython respectively for the GUIs, and they weren't extremely elaborate, just some basic functionality, a few frames, a few buttons, added a few sound options... nothing huge ;D However, making the gui for python took me less than a fourth of the time it took to make the equivalent (the C++ one was actually a bit worse, there were some things that were implemented in wxpython that just didn't want to work in wxwidgets). I'm not saying that coding in python is going to let you develop things 4 times faster, but there are some obvious advantages that I think greatly increase development rate. Just making the framework for the C++ gui was very time consuming. Added to this is that python doesn't require linking and specifying libraries and all the other things that tend to go wrong on the first attempt at compiling something. You also don't have to specify void, int, char etc for functions, and of course, there's no pointers. :D Best thing you can do is probably just to download python and tinker with it, maybe try making some python equivalents to whatever you've made in other languages. Cheers -Jordan Hendrik van Rooyen wrote: > "Chris Brat" <[EMAIL PROTECTED]> wrote: > > > > I've seen a few posts, columns and articles which state that one of the > > advantages of Python is that code can be developed x times faster than > > languages such as <>. > > > > Does anyone have any comments on that statement from personal > > experience? > > How is this comparison measured? > > I don't think it can be, objectively - comparing two teams, one using > language > "a", and the other python, to do a task, is simply comparing the skill levels > of the two teams - and using the same team to do the same task in two > different > languages is also misleading, because of the experience gained in the first > iteration. > > Python is actually astonishing - it seems to "fit the brain" of a large number > of people - it is very easy to get started with, and is rich enough to keep > surprising you - even after considerable time hacking around with it. > It can do OO, but you can also write procedures in it, and you can even mix > the > two in the same module, and most of the time it "just works" - and when it > doesn't, it is normally very easy to teach yourself what you are doing wrong > by > playing at the interactive interpreter prompt. This makes for productivity, > as > you can write quite complex things in a day or so, from scratch, such as: > > A single pass "assembler" for a virtual machine with 33 instructions - from > nothing to running, fully debugged, in two days. > > A simple sliding window protocol - coded up from nothing in four days - mostly > spent staring into space, imagining problems, instead of coding... so the > "design" time is included... but its not working yet, as I have to write the > other side in assembler on a very small machine, which would normally have > taken > me almost a month, but that will now probably take about two weeks, as I have > the Python code to translate... > > And I am not a guru on this group, and I have just idly mucked around with > Python for about a year in real time, not doing it full time, or making any > real > effort to study the language formally beyond lurking here - there are other > people here on this group who, I am sure, could beat the hell out of these > times, both for the design and the coding. > > So to sum up my personal perspective - it is very worth while to know a little > python, even if you just use it as a prototyping language - it gets you going > rapidly... > > - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Running python from a usb drive
If making a usb version of python was that easy, movable python would be open source. Check out http://www.voidspace.org.uk/python/movpy/ if you need a portable usb version of python for work or something. Copying the Python24 directory is a good start, but doesn't include the enormous number of registry keys that are included in the install and are probably needed for the complete capabilites of python. I really hope I didn't missunderstand what you were asking about -_-; Environmental Variables? Try setting the user/system variable "pythonpath" cjl wrote: > Hey: > > I am trying to run python from a usb drive under windows xp. I > installed python "for this user" on to a machine, then copied the > entire Python24 directory to the usb drive. > > I have the following in a batch file at the root of the drive: > > @path=%PATH%;%CD%Python24;%CD%Python24\libs;%CD%Python24\Scripts;%CD%Python24\Lib\site-packages;%CD%Python24\DLLs > @set pythonpath = %CD%Python24 > @cmd > > When I double click the file and type 'python' at the prompt I am in a > working python environment, and I am able to import modules in the > site-packages directory (in this case, django). > > However, when I run a script directly from the cmd prompt (in this case > 'django-admin.py' the script runs, but fails to import modules from the > site-packages directory. > > Is there a command line option to python.exe or an environment variable > I can set to remedy this? > > Any other thoughts? > > Thanks in advance, > CJL -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing Video conference software for Windows
If you're going to need win32 system access use the win32all python extension (very, very good extension). Do you need single frame image capture, or constant video stream? PIL can be used for the first, it might also be usable for video, I'm not sure. For sound, python comes with some built in libraries, but you should also take a look at pysonic http://www.cs.unc.edu/Research/assist/developer.shtml. For the bandwidth efficiency issue, what type of connection are you using? The socket module is quite capable of transmiting whatever data you have, so unless you're thinking of implementing some mini bittorrent like network in an attempt to save bandwidth I don't know what you can do about that. There's an extension called IPqueue which might give you somewhere to start for packet/bandwidth manipulation. Check out The Vaults of Parnassus, which has a lot of stuff (including ogg/mp3 converters last time a check).Big question, is this supposed to act like a remote desktop, or just show what's happening? Start by searching Google, it's very useful. Paolo Pantaleo wrote: > Hi, > > I need to write a software that allow to see the desktop and hear the > microphone capture of a remote PC across a network. I need to do that > for a unviresity assignement. The software must run on Windows. Since > I like Python very much I am thinking to write that software in > Python. Do you thinkit is a good choice? Are there libraries for audio > compression (OGG or MP3 or maybe GSM or something like realaudio) and > video compression (btw what can be some good libraries to transmit > images of a desktop in a bandwidth-efficent way?). What about capture > of audio and screen? (Probably i will need some Win32 system call, > there are bindings in Python, aren't they?) > > If I needed to write some Python modules in C, would it be difficult? > > Can some language like C# or C++ may be better? > > Thnx > PAolo > > -- > if you have a minute to spend please visit my photogrphy site: > http://mypic.co.nr -- http://mail.python.org/mailman/listinfo/python-list
Re: XSLT speed comparisons
If your using python 2.4.3 or essentially any of the 2.3, 2.4 series, i'd test out PyScripter as an IDE, it's one of the best that I've used. Unfortunately, they have yet to fully accomedate 2.5 code (you can still write 2.5 code with almost no problems, but you won't be able to use a 2.5 interactive interpeter). Damian wrote: > Sorry about the multiple posts folks. I suspect it was the "FasterFox" > FireFox extension I installed yesterday tricking me. > > I had a brief look at libxml(?) on my Ubuntu machine but haven't run it > on the server. > > I'll look into pyrxp Larry. > > I have to say I'm struggling a little with the discoverability and > documentation side of things with Python. I realise that > discoverability is purported to be one of its strong sides but coming > from the Visual Studio IDE where Intellisense looks after everything as > you are typing and you can see exactly what methods are available to > what class and what variables are required and why what I've seen so > far is not that flash. > > I've installed Eclipse with Pydev (very impressive) on my Linux box and > am using IDLE on Windows and it could just be my lack of familiarity > that is letting me down. Any other IDE recommendations? > > I'd be keen to test pyrxp and libxslt but may need help with the code - > I spent literally hours yesterday trying to make a 20-line bit of code > work. To make things worse I started with 4suite in Ubuntu and it > refused to work with an error about not being able to find default.cat > or something. Googled for hours with no luck. > > That said, I really want to make the switch and so far Python looks to > be the best choice. > > Cheers > Damian -- http://mail.python.org/mailman/listinfo/python-list
Re: XSLT speed comparisons
If your using python 2.4.3 or essentially any of the 2.3, 2.4 series, i'd test out PyScripter as an IDE, it's one of the best that I've used. Unfortunately, they have yet to fully accomedate 2.5 code (you can still write 2.5 code with almost no problems, but you won't be able to use a 2.5 interactive interpeter). Good Luck Jordan Damian wrote: > Sorry about the multiple posts folks. I suspect it was the "FasterFox" > FireFox extension I installed yesterday tricking me. > > I had a brief look at libxml(?) on my Ubuntu machine but haven't run it > on the server. > > I'll look into pyrxp Larry. > > I have to say I'm struggling a little with the discoverability and > documentation side of things with Python. I realise that > discoverability is purported to be one of its strong sides but coming > from the Visual Studio IDE where Intellisense looks after everything as > you are typing and you can see exactly what methods are available to > what class and what variables are required and why what I've seen so > far is not that flash. > > I've installed Eclipse with Pydev (very impressive) on my Linux box and > am using IDLE on Windows and it could just be my lack of familiarity > that is letting me down. Any other IDE recommendations? > > I'd be keen to test pyrxp and libxslt but may need help with the code - > I spent literally hours yesterday trying to make a 20-line bit of code > work. To make things worse I started with 4suite in Ubuntu and it > refused to work with an error about not being able to find default.cat > or something. Googled for hours with no luck. > > That said, I really want to make the switch and so far Python looks to > be the best choice. > > Cheers > Damian -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a global hotkey?
If you're using python 2.4, you can use the pyHook library (I don't think it has been ported to 2.5 yet... I should email him about that), which can hook both the mouse and keyboard, so your program can be running in the background and still catch what keys (or mouse clicks) are pressed. The pyHook extension comes with some very good examples of how to use it, but if they aren't good enough examples (I can't imagine that would happen), you should check out pykeylogger (sourceforge) which uses the pyHook extension (it's a really good program. Although not like conventional keyloggers built in C/C++ which hide themselves from the OS - the purpose was not actually to spy on the user but to create backups of what was typed - it still does a very good job and the latest release has a lot of options and extendability). If your OS is linux, unix, or mac... good luck ;D Cheers, Jordan Gerold Penz wrote: > > I want my function to execute when the user presses the > > hotkey anywhere. > > Hi! > > - XLib unter Linux: http://python-xlib.sourceforge.net/ > - wxPython unter Windows: > http://wxpython.org/docs/api/wx.Window-class.html#RegisterHotKey > > regards, > Gerold > :-) > > -- > > Gerold Penz - bcom - Programmierung > [EMAIL PROTECTED] | http://gerold.bcom.at | http://sw3.at > Ehrliche, herzliche Begeisterung ist einer der > wirksamsten Erfolgsfaktoren. Dale Carnegie -- http://mail.python.org/mailman/listinfo/python-list
Tarfile .bz2
When using python to create a tar.bz2 archive, and then using winrar to
open the archive, it can't tell what the compressed size of each
individual file in the archive is. Is this an issue with winrar or is
there something that needs to be set when making the archive that isn't
there by default.
example archive:
#Note, the tabs on this are not really tabs, so good luck copying it
correctly
import os, tarfile
archive = tarfile.open("archive.tar.bz2","w:bz2")
for thing in os.listdir(somepath):
nthing = somepath+thing
if os.path.isfile(nthing): # somepath must end in "\\" for this to
work
info = archive.gettarinfo(nthing)
archive.addfile(info,file(nthing,'rb'))
archive.close()
---
Thanks,
Jordan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Tarfile .bz2
So that would explain why a tar.bz2 archive can't be appended to wouldn't it... And also explain why winrar was so slow to open it (not something I mentioned before, but definitely noticed). I had wondered what it was that made bz2 so much better at compression than zip and rar. Not really on topic anymore but what's the method for tar.gz? And even more off the topic, does anyone know a good lossless compression method for images (mainly .jpg and .png)? Cheers, Jordan Wolfgang Draxinger wrote: > Jordan wrote: > > > When using python to create a tar.bz2 archive, and then using > > winrar to open the archive, it can't tell what the compressed > > size of each > > individual file in the archive is. Is this an issue with > > winrar or is there something that needs to be set when making > > the archive that isn't there by default. > > When compressing a tar archive all files in the archive are > compressed as a whole, i.e. you can only specify a compression > ration for the whole archive and not just for a single file. > > Technically a tar.bz2 is actually a aggregation of multiple files > into a single tar file, which is then compressed. > > This is different to e.g. PKZip in which each file is compressed > individually and the compressed files are then merged into an > archive. > > The first method has better compression ratio, since redundancies > among files are compressed, too, whereas the latter is better if > you need random access to the individual files. > > Wolfgang Draxinger > -- > E-Mail address works, Jabber: [EMAIL PROTECTED], ICQ: 134682867 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to manage two (different) sockets without using threads?
Why are you trying to make this asynchronous? I think part of the point of ftp using two sockets was to make it multithreaded. If you're going to make it asynchronous, It's probably going to be easier to do the "select"ing yourself, instead of relying on asyncore or asynchat. Unless you have an insanely fast connection and/or really small files on the server, using asynchronous socket handling is going to stop up the server b/c select won't check the other sockets until the current one is done with whatever it's doing. billie wrote: > Hi all. > I'm (re)writing an FTP server application by using asyncore/asynchat > modules. > FTP tipically got two different channels: command and data. > I'm succesfully managing command channel through asynchat framework, > but I'm not sure about how to manage data channel without using a > thread/subprocess. > Is there an optimal to do that? > Can anyone point me in the right direction? -- http://mail.python.org/mailman/listinfo/python-list
Re: pyHook or SetWindowsHookEx
On Feb 27, 9:01 am, "abcd" <[EMAIL PROTECTED]> wrote: > I am having trouble with pyHook on python 2.4.1. Basically I have a > python app that uses pyHook to capture keyboard events and write them > straight to a file. The application is running as a service on a > windows machine. If I am at that windows machine the application > works just fine, logging my keystrokes. However, if I use Remote > Desktop to connect to the machine and open up say Notepad it doesn't > capture the keystrokes. Is this a problem with pyHook? or is it he > way Windows handles the events? > > Is there a way to setup my own hook without pyHook using just python? > i think the function I am interested in is SetWindowsHookEx. > > Thanks in advance. I'm pretty sure it's not a problem with pyHook. I'm also fairly sure that you can't log the keystrokes of someone who is logged onto your machine from another; that would be a major security flaw. The only way (I think) this would work is if you wrote your own remote desktop program that logged keystrokes, and then sent it to the remote computer when logging off. Cheers, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading a portion of a file
On Mar 8, 11:52 am, "Rune Strand" <[EMAIL PROTECTED]> wrote: > On Mar 8, 5:12 pm, [EMAIL PROTECTED] wrote: > > > I am using a script with a single file containing all data in multiple > > sections. Each section begins with "#VS:CMD:command:START" and ends > > with "#VS:CMD:command:STOP". There is a blank line in between each > > section. I'm looking for the best way to grab one section at a time. > > Will I have to read the entire file to a string and parse it further > > or is it possible to grab the section directly when doing a read? I'm > > guessing regex is the best possible way. Any help is greatly > > appreciated. > > Seems like something along these line will do: > > _file_ = "filepart.txt" > > begin_tag = '#VS:CMD:command:START' > end_tag = '#VS:CMD:command:STOP' > > sections = [] > new_section = [] > for line in open(_file_): > line = line.strip() > if begin_tag in line: > new_section = [] > elif end_tag in line: > sections.append(new_section) > else: > if line: new_section.append(line) > > for s in sections: print s > > If your want more control, perhaps flagging "inside_section", > "outside_section" is an idea. You probably don't want to use regex for something this simple; it's likely to make things even more complicated. Is there a space between the begin_tag and the first word of a section (same question with the end_tag)? -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading a portion of a file
On Mar 8, 12:46 pm, "Jordan" <[EMAIL PROTECTED]> wrote: > On Mar 8, 11:52 am, "Rune Strand" <[EMAIL PROTECTED]> wrote: > > > > > On Mar 8, 5:12 pm, [EMAIL PROTECTED] wrote: > > > > I am using a script with a single file containing all data in multiple > > > sections. Each section begins with "#VS:CMD:command:START" and ends > > > with "#VS:CMD:command:STOP". There is a blank line in between each > > > section. I'm looking for the best way to grab one section at a time. > > > Will I have to read the entire file to a string and parse it further > > > or is it possible to grab the section directly when doing a read? I'm > > > guessing regex is the best possible way. Any help is greatly > > > appreciated. > > > Seems like something along these line will do: > > > _file_ = "filepart.txt" > > > begin_tag = '#VS:CMD:command:START' > > end_tag = '#VS:CMD:command:STOP' > > > sections = [] > > new_section = [] > > for line in open(_file_): > > line = line.strip() > > if begin_tag in line: > > new_section = [] > > elif end_tag in line: > > sections.append(new_section) > > else: > > if line: new_section.append(line) > > > for s in sections: print s > > > If your want more control, perhaps flagging "inside_section", > > "outside_section" is an idea. > > You probably don't want to use regex for something this simple; it's > likely to make things even more complicated. Is there a space between > the begin_tag and the first word of a section (same question with the > end_tag)? Sent the post too soon. What is the endline character for the file type? What type of file is it?An example section would be nice too. Cheers. -- http://mail.python.org/mailman/listinfo/python-list
Re: logging and wx.Timer
On Mar 14, 1:52 am, hg <[EMAIL PROTECTED]> wrote: > Hi, > > I read that logging was thread safe ... but can I use it under a GUI timer ? > > Thanks, > > hg That was barely enough information to be worthy of a reply. Need more than that. What do you mean under a gui timer? What gui? What type of usage? More info = more (and better) help. Cheers. JT -- http://mail.python.org/mailman/listinfo/python-list
Re: python noob, multiple file i/o
On Mar 16, 7:09 am, Laurent Rahuel <[EMAIL PROTECTED]> wrote:
> Maybe the walk method in os module is what you
> needhttp://docs.python.org/lib/os-file-dir.html
>
> Regards
>
> Jon Clements wrote:
> > On 16 Mar, 09:02, "Jon Clements" <[EMAIL PROTECTED]> wrote:
> >> On 16 Mar, 03:56, "hiro" <[EMAIL PROTECTED]> wrote:
>
> >> > Hi there,
>
> >> > I'm very new to python, the problem I need to solve is whats the "best/
> >> > simplest/cleanest" way to read in multiple files (ascii), do stuff to
> >> > them, and write them out(ascii).
>
> >> > --
> >> > import os
>
> >> > filePath = ('O:/spam/eggs/')
> >> > for file in os.listdir(filePath): #straight from docs
> >> > # iterate the function through all the files in the directory
> >> > # write results to separate files <- this is where I'm mostly
> >> > stuck.
>
> >> > --
> >> > For clarity's sake, the file naming conventions for the files I'm
> >> > reading from are file.1.txt -> file.nth.txt
>
> >> > It's been a long day, i'm at my wits end, so I apologize in advance if
> >> > I'm not making much sense here.
> >> > syntax would also be great if you can share some recipes.
>
> >> I'd try the glob module.
>
> >> [code]
> >> import glob
>
> >> # Get a list of filenames matching wildcard criteria
> >> # (note that path is relative to working directory of program)
> >> matching_file_list = glob.glob('O:/spam/eggs/*.txt')
>
> >> # For each file that matches, open it and process it in some way...
> >> for filename in matching_file_list:
> >> infile = file(filename)
> >> outfile = file(filename + '.out','w')
> >> # Process the input file line by line...
> >> for line in infile:
> >> pass # Do something more useful here, change line and write to
> >> outfile?
> >> # Be explicit with file closures
> >> outfile.close()
> >> infile.close()
> >> [/code]
>
> >> Of course, you can change the wild card criteria in the glob
> >> statement, and also then filter further using regular expressions to
> >> choose only files matching more specific criteria. This should be
> >> enough to get you started though.
>
> >> hth
>
> >> Jon.- Hide quoted text -
>
> >> - Show quoted text -
>
> > Okies; postcoding before finishing your early morning coffee is not
> > the greatest of ideas!
>
> > I forgot to mention that glob will return pathnames as well. You'll
> > need to check that os.path.isfile(filename) returns True before
> > processing it...
>
> > Jon.
Also, leaving the format as .out is not necessarily convenient. You
had glob do a search for .txt, so how about doing:
Also, Python advises using open() over file() (although I admit to
using file() myself more often than not)
>>for filename in matching_file_list:
>> infile = open(filename,'r') # add 'r' for clarity if nothing else
>> outfile = open(filename[:-4] + '.out.txt','w') # assumes file ext of
>> original file is .txt
>> # Process the input file line by line...
>> for line in infile:
>> pass # do thing --> you don't have to iterate line by line, if you
>> specified what you wanted to do to each file we could probably help out here
>> if you need it.
>> # Be explicit with file closures
>> outfile.close()
>> infile.close()
Might also add some try/except statements to be safe ;).
Cheers,
Jordan
--
http://mail.python.org/mailman/listinfo/python-list
Re: running applications in python
os.system, os.spawn, the process module, os.popen[1,2,3,4], this is a pretty basic thing, not trying to be mean, but you should look in the python docs, this is definitely in there. Also, the subprocess module is meant to replace all of those but i haven't looked too closely at it yet, so the following might not be perfect. import subprocess as sp sp.call(['wmplayer.exe', 'some_args_probably_a_movie_name']) you'll probably need to use the full path for media player, and the call() function is a simplified command within the subprocess module, useful if you don't really need to redirect input/output/errors or other aspects of the opened application.Also, you'll probably want something more like: retcode = sp.call(...), so that you can check the return code to see if it was successful. Check out the subprocess module. Cheers, Jordan On Jan 25, 12:28 pm, "lee" <[EMAIL PROTECTED]> wrote: > how can i run or open a windows application from the python prompt?for > e.g.mediaplayer opening,folder acess etc -- http://mail.python.org/mailman/listinfo/python-list
Re: asyncore.dispatcher.handle_read
That was not entirely helpful, it's way more likely a mistake you made in subclassing dispatcher than a problem within asycore itself (that ended up sounding a lot more mean/angry than intended, sorry ¬_¬ ), you really need to show us what changes you made to asyncore.dispatcher if you want help. Good luck. Cheers, Jordan On Jan 25, 12:18 pm, Indy <[EMAIL PROTECTED]> wrote: > Greetings. > > I am writing an asynchronous server, and I use the standard library's > module asyncore. > I subclass asyncore.dispatcher. handle_accept works just right, that > is, when a client socket makes a request to connect to my server > socket, things that I set in handle_accept definition, happen. So, it > is OK. But, the problem is that handle_read does not work as expected. > Things I set in handle_read definition, do not happen when a client > socket sends me data. Why? Is this a known problem? Please, can you > help me? > Thanks a lot, in advance. > > Best regards, > Aristotelis Mikropoulos > > -- > Programs must be written for people to read, and only incidentally for > machines to execute. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running long script in the background
On Feb 6, 8:26 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > Hello, > > I am trying to write a python cgi that calls a script over ssh, the > problem is the script takes a very long time to execute so Apache > makes the CGI time out and I never see any output. The script is set > to print a progress report to stdout every 3 seconds but I never see > any output until the child process is killed. > > Here's what I have in my python script: > > command = "ssh -l root %s /scripts/xen/xen-create-win-vps1.sh %s" % > (host, domuname) > output = os.popen(command) > for line in output: >print line.strip() > > Here's a copy of the bash script. > > http://watters.ws/script.txt > > I also tried using os.spawnv to run ssh in the background and nothing > happens. > > Does anybody know a way to make output show in real time? Just a little note: os.popen has been replaced by the subprocess module. ;D -- http://mail.python.org/mailman/listinfo/python-list
Re: Download parts not whole file in ones
On Feb 13, 8:09 am, NOSPAM plz <[EMAIL PROTECTED]> wrote:
> Hey,
>
> My problem is, is it possible to download parts of a file while. i think
> is it is called threading
>
> My code thats download the whole webpage, and stunds the app while is is
> downloading:
>
> ---CODE---
> import urllib
> # the heavy file to download
> f = urllib.urlopen("http://da.wikipedia.org/wiki/Wiki";)
> # This was supposed to print the file while it downloads
> while 1:
> print f.read(100)
> ---/CODE---
>
> In my example it just download the whole file, and then print it.
>
> Any suggestions?
>
> Regards
> Andreas
That's because urllib.urlopen() is not a low enough level function to
allow what you want, it will simply open the . Take a look inside of
urllib.py and maybe you'll find a way to subclass the urllopen()
function to do what you want.
Cheers,
Jordan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Download parts not whole file in ones
On Feb 13, 12:51 pm, "Jordan" <[EMAIL PROTECTED]> wrote:
> On Feb 13, 8:09 am, NOSPAM plz <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hey,
>
> > My problem is, is it possible to download parts of a file while. i think
> > is it is called threading
>
> > My code thats download the whole webpage, and stunds the app while is is
> > downloading:
>
> > ---CODE---
> > import urllib
> > # the heavy file to download
> > f = urllib.urlopen("http://da.wikipedia.org/wiki/Wiki";)
> > # This was supposed to print the file while it downloads
> > while 1:
> > print f.read(100)
> > ---/CODE---
>
> > In my example it just download the whole file, and then print it.
>
> > Any suggestions?
>
> > Regards
> > Andreas
>
> That's because urllib.urlopen() is not a low enough level function to
> allow what you want, it will simply open the . Take a look inside of
> urllib.py and maybe you'll find a way to subclass the urllopen()
> function to do what you want.
>
> Cheers,
> Jordan
Sorry, my previous msg got mangled. I meant to say that
urllib.urlopen() will simply open the webpage, you can't interrupt it
to print out what's already been downloaded.
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to write a programe that include both pipe(low speed system call) and signal
On Feb 15, 2:51 am, Marco <[EMAIL PROTECTED]> wrote: > Hi, > I have know that signal will interrupt some kind low speed system > call like pipe. But how to design a program that both support signal > and pipe? > > I have a mplayer.py to play movie via os.popen2() and mplayer > slave mode. And there is a mplayer_ctl.py send signal to mplayer.py to > trigger function from mplayer.py. Sometimes os.popen2() is reading or > writing when user run mplayer_ctl.py the bad things raise... > > Is there some better way to design the programe? Thank you > > -- > LinuX Power Take a look at the subprocess module, which is meant to replace popen[1,2,3...](). Also, please try to explain the problem again, because I just can't decypher everything you're trying to do (and say). cheers, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Required for Choosing Programming Language
On Feb 18, 7:35 pm, Dave Cook <[EMAIL PROTECTED]> wrote: > On 2007-02-16, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > > i have read about Python, Ruby and Visual C++. but i want to go > > through with GUI based programming language like VB.net > > You might take a look athttp://dabodev.com > > Dave Cook Learn python, and then learn wxpython (python binding of wxWidgets). wxWidgets is one of the most extensive and well built gui tools (in my opinion) and is easier to implement in python than C++ (also my opinion). The only reason I can see for using C++ over Python for gui building is if for some obscure reason Python wasn't fast enough. On the other hand, this brings up the argument of which is faster: Python or C++ ;) so let's not get into that. Python + WxPython = Good Language with Good GUI Toolkit. Cheers, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading compressed files
On Feb 21, 5:21 am, Steve Holden <[EMAIL PROTECTED]> wrote: > Shadab Sayani wrote: > > Hi, > > I have compressed files compressed using different techniques > > (especially unix compress). So I want to have a module that reads any of > > these (.Z,.bz,.tgz files) files and manipulates the data. > > The data has a syntax.It contains > > HEADER (some information) > > BODY (some information) > > FOOTER (some information) > > If it were a normal text file I can get the values corresponding to > > HEADER BODY and FOOTER by open function. > > But here the files are in different format .Z , .bz ,.tgz,.gz .But I > > know these are the only formats.Also I cannot rely upon the extensions > > of the file (a .Z file can have no extension at all).Is there a way to > > identify which file am I reading and then read it?If so how to read it? > > Thanks and Regards, > > Shadab. > > > Send instant messages to your online friendshttp://uk. messenger.yahoo.com > > The usual way is that used by the "file" utility - take a look at the > /etc/magic file to see if you can gain any clues from that. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenwebhttp://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com > See you at PyCon?http://us.pycon.org/TX2007- Hide quoted text - > > - Show quoted text - You really need to check the docs and do a little research before asking questions like this. Check out tarfile and zlib modules (use these for opening .tgz, .gz, .bz2 etc), and then go search for the different ways each (.Z, .tgz, .gz, .bz etc) formats their header files so that you can determine what each type of archive is. > The data has a syntax.It contains > HEADER (some information) > BODY (some information) > FOOTER (some information) > If it were a normal text file I can get the values corresponding to > HEADER BODY and FOOTER by open function. > But here the files are in different format .Z , .bz ,.tgz,.gz ... What do you mean if it was a normal text file?? Use 'rb' for reading binary and you shouldn't have a problem if you know the syntax for each of these files. What you need to do is research each syntax and write a regexp or other string searching function to determine each format based on the archive header syntax. While you're at it, open a few archives with a hex editor or using open(...,'rb') and take a look at the syntax of each file to see if you can determine it yourself. Goodluck. Cheers, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I track/monitor an application and system resources.
On Feb 22, 11:48 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > Hello All, > > I'm a newbie to Python! > > I am trying to develop a program that monitors the performance of an > application. The kind of information I am interested in is the CPU/ > Process/Thread and memory performance. Specifically, I would like to > track the following > > CPU usage > Used Memory on Phone > Free Memory on Phone > Number of Processes running > Number of threads running > Number of Filehandles currently open > Memory used by a process/thread > Process/Thread CPU activity. > > All this under Windows > > Can anyone help me, or direct me to the appriopriate API's so I can > get the above information? > > Does anyone have any other sugestions on what else I could monitor for > a running application? > > Does anyone have any example code they can direct me to? > > Many thanks in advance, > > Richard You will definitely want to check out pywin32api, because it is the best (and most powerful) way to interact with windows through python. Also, if you know any c++, you might search for taskmanager extensions on codeproject.com or look at the msdn on taskmanager to see how it gets all of its information (which is essentially what you want -- a taskmanager). Either way you'll almost defitely need pywin32, so look there first. Cheers, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: implement random selection in Python
Maybe it would help to make your problem statement a litte rigorous so
we can get a clearer idea of whats required.
One possible formulation:
Given a list L of pairs of values, weightings: [ (v_0, w_0), (v_1,
w_1), ], and some N between 1 and length(L)
you would like to randomly select a set of N (distinct) values, V,
such that for any ints i and j,
Prob (v_i is in V) / Prob (v_j is in V) = w_i / w_j
This matches your expectations for N = 1. Intuitively though, without
having put much thought into it, I suspect this might not be possible
in the general case.
You might then want to (substantially) relax thec ondition to
Prob (v_i is in V) >= Prob (v_j is in V) iff w_i >= w_j
but in that case its more an ordering of likelihoods rather than a
weighting, and doesn't guarantee the right behaviour for N = 1, so i
don't think thats really what you want.
I can't think of any other obvious way of generalising the behaviour
of the N = 1 case.
- Jordan
On Nov 17, 10:50 am, Bruza <[EMAIL PROTECTED]> wrote:
> On Nov 16, 4:47 pm, Bruza <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Nov 16, 6:58 am, duncan smith <[EMAIL PROTECTED]>
> > wrote:
>
> > > Bruza wrote:
> > > > I need to implement a "random selection" algorithm which takes a list
> > > > of [(obj, prob),...] as input. Each of the (obj, prob) represents how
> > > > likely an object, "obj", should be selected based on its probability
> > > > of
> > > > "prob".To simplify the problem, assuming "prob" are integers, and the
> > > > sum of all "prob" equals 100. For example,
>
> > > >items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)]
>
> > > > The algorithm will take a number "N", and a [(obj, prob),...] list as
> > > > inputs, and randomly pick "N" objects based on the probabilities of
> > > > the
> > > > objects in the list.
>
> > > > For N=1 this is pretty simply; the following code is sufficient to do
> > > > the job.
>
> > > > def foo(items):
> > > > index = random.randint(0, 99)
> > > > currentP = 0
> > > > for (obj, p) in items:
> > > >currentP += w
> > > >if currentP > index:
> > > > return obj
>
> > > > But how about the general case, for N > 1 and N < len(items)? Is there
> > > > some clever algorithm using Python standard "random" package to do
> > > > the trick?
>
> > > I think you need to clarify what you want to do. The "probs" are
> > > clearly not probabilities. Are they counts of items? Are you then
> > > sampling without replacement? When you say N < len(items) do you mean N
> > > <= sum of the "probs"?
>
> > > Duncabn
>
> > I think I need to explain on the probability part: the "prob" is a
> > relative likelihood that the object will be included in the output
> > list. So, in my example input of
>
> > items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)]
>
> > So, for any size of N, 'Tom' (with prob of 45) will be more likely to
> > be included in the output list of N distinct member than 'Mary' (prob
> > of 30) and much more likely than that of 'John' (with prob of 10).
>
> > I know "prob" is not exactly the "probability" in the context of
> > returning a multiple member list. But what I want is a way to "favor"
> > some member in a selection process.
>
> > So far, only Boris's solution is closest (but not quite) to what I
> > need, which returns a list of N distinct object from the input
> > "items". However, I tried with input of
>
> >items = [('Mary',1), ('John', 1), ('Tom', 1), ('Jane', 97)]
>
> > and have a repeated calling of
>
> > Ben
>
> OOPS. I pressed the Send too fast.
>
> The problem w/ Boris's solution is that after repeated calling of
> randomPick(3,items), 'Jane' is not the most "frequent appearing"
> member in all the out list of 3 member lists...- Hide quoted text -
>
> - Show quoted text -
--
http://mail.python.org/mailman/listinfo/python-list
Re: implement random selection in Python
How about this variation on your intial attempt?
# Untested!
def randomPick(n, items):
def pickOne():
index = random.randint(0, 99)
currentP = 0
for (obj, p) in items:
currentP += p
if currentP > index:
return obj
selection = set()
while len(selection) < n:
selection.add(pickOne())
return selection
Of course the performance is likely to be far from stellar for, say,
randomPick(2, [("Bob", 98), ("Jane", 1), ("Harry", 1)]), but at least
its boundedly bad (so long as you retain the condition that the sum of
the weightings is 100.)
Not sure if it satisfies the conditions in my last post either do
some empirical testing, or some mathematics, or maybe a bit of
both.
On Nov 17, 12:02 pm, Jordan <[EMAIL PROTECTED]> wrote:
> Maybe it would help to make your problem statement a litte rigorous so
> we can get a clearer idea of whats required.
>
> One possible formulation:
>
> Given a list L of pairs of values, weightings: [ (v_0, w_0), (v_1,
> w_1), ], and some N between 1 and length(L)
>
> you would like to randomly select a set of N (distinct) values, V,
> such that for any ints i and j,
>
> Prob (v_i is in V) / Prob (v_j is in V) = w_i / w_j
>
> This matches your expectations for N = 1. Intuitively though, without
> having put much thought into it, I suspect this might not be possible
> in the general case.
>
> You might then want to (substantially) relax thec ondition to
>
> Prob (v_i is in V) >= Prob (v_j is in V) iff w_i >= w_j
>
> but in that case its more an ordering of likelihoods rather than a
> weighting, and doesn't guarantee the right behaviour for N = 1, so i
> don't think thats really what you want.
>
> I can't think of any other obvious way of generalising the behaviour
> of the N = 1 case.
>
> - Jordan
>
> On Nov 17, 10:50 am, Bruza <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Nov 16, 4:47 pm, Bruza <[EMAIL PROTECTED]> wrote:
>
> > > On Nov 16, 6:58 am, duncan smith <[EMAIL PROTECTED]>
> > > wrote:
>
> > > > Bruza wrote:
> > > > > I need to implement a "random selection" algorithm which takes a list
> > > > > of [(obj, prob),...] as input. Each of the (obj, prob) represents how
> > > > > likely an object, "obj", should be selected based on its probability
> > > > > of
> > > > > "prob".To simplify the problem, assuming "prob" are integers, and the
> > > > > sum of all "prob" equals 100. For example,
>
> > > > >items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)]
>
> > > > > The algorithm will take a number "N", and a [(obj, prob),...] list as
> > > > > inputs, and randomly pick "N" objects based on the probabilities of
> > > > > the
> > > > > objects in the list.
>
> > > > > For N=1 this is pretty simply; the following code is sufficient to do
> > > > > the job.
>
> > > > > def foo(items):
> > > > > index = random.randint(0, 99)
> > > > > currentP = 0
> > > > > for (obj, p) in items:
> > > > >currentP += w
> > > > >if currentP > index:
> > > > > return obj
>
> > > > > But how about the general case, for N > 1 and N < len(items)? Is there
> > > > > some clever algorithm using Python standard "random" package to do
> > > > > the trick?
>
> > > > I think you need to clarify what you want to do. The "probs" are
> > > > clearly not probabilities. Are they counts of items? Are you then
> > > > sampling without replacement? When you say N < len(items) do you mean N
> > > > <= sum of the "probs"?
>
> > > > Duncabn
>
> > > I think I need to explain on the probability part: the "prob" is a
> > > relative likelihood that the object will be included in the output
> > > list. So, in my example input of
>
> > > items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)]
>
> > > So, for any size of N, 'Tom' (with prob of 45) will be more likely to
> > > be included in the output list of N distinct member than 'Mary' (prob
> > > of 30) and much more likely than that of 'John' (with prob of 10).
>
> > > I know "prob" is not exactly the "probability" in the context of
> > > returning a multiple member list. But what I want is a way to "favor"
> > > some member in a selection process.
>
> > > So far, only Boris's solution is closest (but not quite) to what I
> > > need, which returns a list of N distinct object from the input
> > > "items". However, I tried with input of
>
> > >items = [('Mary',1), ('John', 1), ('Tom', 1), ('Jane', 97)]
>
> > > and have a repeated calling of
>
> > > Ben
>
> > OOPS. I pressed the Send too fast.
>
> > The problem w/ Boris's solution is that after repeated calling of
> > randomPick(3,items), 'Jane' is not the most "frequent appearing"
> > member in all the out list of 3 member lists...- Hide quoted text -
>
> > - Show quoted text -- Hide quoted text -
>
> - Show quoted text -
--
http://mail.python.org/mailman/listinfo/python-list
Unicode File Names
I've got a bunch of files with Japanese characters in their names and os.listdir() replaces those characters with ?'s. I'm trying to open the files several steps later, and obviously Python isn't going to find '01-.jpg' (formally '01-ひらがな.jpg') because it doesn't exist. I'm not sure where in the process I'm able to stop that from happening. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode File Names
On Oct 16, 9:20 pm, John Machin <[EMAIL PROTECTED]> wrote: > On Oct 17, 11:43 am, Jordan <[EMAIL PROTECTED]> wrote: > > > I've got a bunch of files with Japanese characters in their names and > > os.listdir() replaces those characters with ?'s. I'm trying to open > > the files several steps later, and obviously Python isn't going to > > find '01-.jpg' (formally '01-ひらがな.jpg') because it doesn't exist. > > I'm not sure where in the process I'm able to stop that from > > happening. Thanks. > > The Fine Manual says: > """ > listdir( path) > > Return a list containing the names of the entries in the directory. > The list is in arbitrary order. It does not include the special > entries '.' and '..' even if they are present in the directory. > Availability: Macintosh, Unix, Windows. > Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a > Unicode object, the result will be a list of Unicode objects. > """ > > Are you unsure whether your version of Python is 2.3 or later? *** Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32. *** says my interpreter when it says "if path is a Unicode object...", does that mean the path name must have a Unicode char? -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode File Names
On Oct 16, 10:18 pm, John Machin <[EMAIL PROTECTED]> wrote: > On Oct 17, 12:52 pm, Jordan <[EMAIL PROTECTED]> wrote: > > > > > On Oct 16, 9:20 pm, John Machin <[EMAIL PROTECTED]> wrote: > > > > On Oct 17, 11:43 am, Jordan <[EMAIL PROTECTED]> wrote: > > > > > I've got a bunch of files with Japanese characters in their names and > > > > os.listdir() replaces those characters with ?'s. I'm trying to open > > > > the files several steps later, and obviously Python isn't going to > > > > find '01-.jpg' (formally '01-ひらがな.jpg') because it doesn't exist. > > > > I'm not sure where in the process I'm able to stop that from > > > > happening. Thanks. > > > > The Fine Manual says: > > > """ > > > listdir( path) > > > > Return a list containing the names of the entries in the directory. > > > The list is in arbitrary order. It does not include the special > > > entries '.' and '..' even if they are present in the directory. > > > Availability: Macintosh, Unix, Windows. > > > Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a > > > Unicode object, the result will be a list of Unicode objects. > > > """ > > > > Are you unsure whether your version of Python is 2.3 or later? > > > *** Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 > > bit (Intel)] on win32. *** says my interpreter > > > when it says "if path is a Unicode object...", does that mean the path > > name must have a Unicode char? > > If path is a Unicode [should read unicode] object of length > 0, then > *all* characters in path are by definition unicode characters. > > Where are you getting your path from? If you are doing os.listdir(r'c: > \test') then do os.listdir(ur'c:\test'). If you are getting it from > the command line or somehow else as a variable, instead of > os.listdir(path), try os.listdir(unicode(path)). If that fails with a > message like "UnicodeDecodeError: 'ascii' codec can't decode .", > then you'll need something like os.listdir(unicode(path, > encoding='cp1252')) # cp1252 being the most likely suspect :) > > I strongly suggest that you read this: >http://www.amk.ca/python/howto/unicode > which contains lots of useful information, including an answer to your > original question. The problem's been solved (thanks Chris and John). I was getting the path from command line, and didn't realize using unicode(path) would make the list Unicode as well. Thanks for the help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode File Names
On Oct 16, 10:18 pm, John Machin <[EMAIL PROTECTED]> wrote: > On Oct 17, 12:52 pm, Jordan <[EMAIL PROTECTED]> wrote: > > > > > On Oct 16, 9:20 pm, John Machin <[EMAIL PROTECTED]> wrote: > > > > On Oct 17, 11:43 am, Jordan <[EMAIL PROTECTED]> wrote: > > > > > I've got a bunch of files with Japanese characters in their names and > > > > os.listdir() replaces those characters with ?'s. I'm trying to open > > > > the files several steps later, and obviously Python isn't going to > > > > find '01-.jpg' (formally '01-ひらがな.jpg') because it doesn't exist. > > > > I'm not sure where in the process I'm able to stop that from > > > > happening. Thanks. > > > > The Fine Manual says: > > > """ > > > listdir( path) > > > > Return a list containing the names of the entries in the directory. > > > The list is in arbitrary order. It does not include the special > > > entries '.' and '..' even if they are present in the directory. > > > Availability: Macintosh, Unix, Windows. > > > Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a > > > Unicode object, the result will be a list of Unicode objects. > > > """ > > > > Are you unsure whether your version of Python is 2.3 or later? > > > *** Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 > > bit (Intel)] on win32. *** says my interpreter > > > when it says "if path is a Unicode object...", does that mean the path > > name must have a Unicode char? > > If path is a Unicode [should read unicode] object of length > 0, then > *all* characters in path are by definition unicode characters. > > Where are you getting your path from? If you are doing os.listdir(r'c: > \test') then do os.listdir(ur'c:\test'). If you are getting it from > the command line or somehow else as a variable, instead of > os.listdir(path), try os.listdir(unicode(path)). If that fails with a > message like "UnicodeDecodeError: 'ascii' codec can't decode .", > then you'll need something like os.listdir(unicode(path, > encoding='cp1252')) # cp1252 being the most likely suspect :) > > I strongly suggest that you read this: >http://www.amk.ca/python/howto/unicode > which contains lots of useful information, including an answer to your > original question. Thanks go to Chris and John for starting me off in the right direction. I'm not quite sure now if the problem is me, windows, or zipfile (which I kinda failed to mention before). Using os.listdir(unicode(os.listdir())) seems to have been a step in the right direction (thanks Chris and John). When testing things in the python interpreter, I don't seem to hit issues after using the above mentioned line. [code] >>> l = os.listdir(unicode(os.getcwd())) >>> l u'01-\u3072\u3089\u304c\u306a.jpg' u'02-\u3072\u3089\u304c\u306a.jpg' u'03-\u3072\u3089\u304c\u306a.jpg' >>>for thing in l: ...print thing 01-ひらがな.jpg 02-ひらがな.jpg 03-ひらがな.jpg [/code] Yay. Having a file that tries "for thing in l: print thing" fails with: File "C:\Python25\Lib\encodings\cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode characters in position 13-16: character maps to I'm perfectly willing to let command prompt refuse to print that (it's debugging only) if the next issue was resolved >_>: """ Note: There is no official file name encoding for ZIP files. If you have unicode file names, please convert them to byte strings in your desired encoding before passing them to write(). WinZip interprets all file names as encoded in CP437, also known as DOS Latin. """ I'm simply not sure what this means and how to deal with it. -- http://mail.python.org/mailman/listinfo/python-list
error when porting C code to Python (bitwise manipulation)
I am trying to rewrite some C source code for a poker hand evaluator
in Python. Putting aside all of the comments such as just using the C
code, or using SWIG, etc. I have been having problems with my Python
code not responding the same way as the C version.
C verison:
unsigned find_fast(unsigned u)
{
unsigned a, b, r;
u += 0xe91aaa35;
u ^= u >> 16;
u += u << 8;
u ^= u >> 4;
b = (u >> 8) & 0x1ff;
a = (u + (u << 2)) >> 19;
r = a ^ hash_adjust[b];
return r;
}
my version (Python, hopefully ;)):
def find_fast(u):
u += 0xe91aaa35
u ^= u >> 16
u += u << 8
u ^= u >> 4
b = (u >> 8) & 0x1ff
a = (u + (u << 2)) >> 19
r = a ^ hash_adjust[b]
return r
As far as I understand the unsigned instructions in C just increase
amount of bytes the int can hold, and Python automatically converts to
longs which have infinite size when necessary, so I am not sure why I
am getting different results.
I assume that I am missing something fairly simple here, so help a
n00b out if you can :)
Thanks in advance,
jnb
--
http://mail.python.org/mailman/listinfo/python-list
Re: error when porting C code to Python (bitwise manipulation)
I was actually just going through an example to show what was happening each step of the way and noticed the overflow!!! bah, stupid tricks tricks tricks!!! The problem is def the overflow, I notice that I start to get negative numbers in the C version, which makes me think that the & 0x trick won't work (because it will never evaluate to negative in python, right?) Seeing that the problem is the overflow and the bitwise operations returning a negative, does anyone have any suggestions...I will look more into C bitwise tricks in the meantime haha. And in terms of what this is doing in a poker hand evaluator: http://www.suffecool.net/poker/evaluator.html (an evaluator using some nice tricks to evaluate for flushes, straights, and highcard with LU tables then binary search for the rest) then http://senzee.blogspot.com/2006/06/some-perfect-hash.html (does the same thing, but uses perfect hashing instead of a binary search) the function I am having issues with comes up in the hashing algorithm :) -- http://mail.python.org/mailman/listinfo/python-list
Re: error when porting C code to Python (bitwise manipulation)
I realize I did a pretty bad job of explaining the problem. The problem is the python version is returning an r that is WY to big. Here is an example run through that function in each language: C: u starts at 1050 u += 0xe91aaa35; u is now -384127409 u ^= u >> 16; u is now -384153771 u += u << 8; u is now 56728661 u ^= u >> 4; u is now 56067472 b = (u >> 8) & 0x1ff; b is now 389 a = (u + (u << 2)) >> 19; a is now 534 r = a ^ hash_adjust[b]; r is now 6366 Python: u starts at 1050 u += 0xe91aaa35 u is now 3910839887L rut roh... -- http://mail.python.org/mailman/listinfo/python-list
Re: error when porting C code to Python (bitwise manipulation)
if after the first step (u += 0xe91aaa35) you apply this function: invert = lambda x: ~int(hex(0x - x)[0:-1],16) it returns the correct value (corrected the overflow) but there is still something wrong, still looking into it, if someone knows how to do this, feel free to comment :) -- http://mail.python.org/mailman/listinfo/python-list
Re: error when porting C code to Python (bitwise manipulation)
Well, I have figured out something that works: def findit(u): u += 0xe91aaa35 u1 = ~(0x - u) ^ u >> 16 u1 += ((u1 << 8) & 0x) u1 ^= (u1 & 0x) >> 4 b = (u1 >> 8) & 0x1ff a = (u1 + (u1 << 2) & 0x) >> 19 r = int(a) ^ hash_adjust[int(b)] return r I feel like this cannot possibly be the best way of doing this, but it does work haha If anyone would care to share a more elegant solution, that would be great :) -- http://mail.python.org/mailman/listinfo/python-list
Re: error when porting C code to Python (bitwise manipulation)
On Jul 10, 1:35 pm, MRAB <[EMAIL PROTECTED]> wrote:
> On Jul 10, 4:56 am, Jordan <[EMAIL PROTECTED]> wrote:
>
>
>
> > I am trying to rewrite some C source code for a poker hand evaluator
> > in Python. Putting aside all of the comments such as just using the C
> > code, or using SWIG, etc. I have been having problems with my Python
> > code not responding the same way as the C version.
>
> > C verison:
>
> > unsigned find_fast(unsigned u)
> > {
> > unsigned a, b, r;
> > u += 0xe91aaa35;
> > u ^= u >> 16;
> > u += u << 8;
> > u ^= u >> 4;
> > b = (u >> 8) & 0x1ff;
> > a = (u + (u << 2)) >> 19;
> > r = a ^ hash_adjust[b];
> > return r;
>
> > }
>
> > my version (Python, hopefully ;)):
>
> > def find_fast(u):
> > u += 0xe91aaa35
> > u ^= u >> 16
> > u += u << 8
> > u ^= u >> 4
> > b = (u >> 8) & 0x1ff
> > a = (u + (u << 2)) >> 19
> > r = a ^ hash_adjust[b]
> > return r
>
> > As far as I understand the unsigned instructions in C just increase
> > amount of bytes the int can hold, and Python automatically converts to
> > longs which have infinite size when necessary, so I am not sure why I
> > am getting different results.
>
> > I assume that I am missing something fairly simple here, so help a
> > n00b out if you can :)
>
> > Thanks in advance,
>
> > jnb
>
> You want to restrict the values to 32 bits. The result of + or << may
> exceed 32 bits, so you need to mask off the excess bits afterwards.
>
> def find_fast(u):
> mask = 0x
> u = (u + 0xe91aaa35) & mask
> u ^= u >> 16
> u = (u + (u << 8)) & mask # can get away with only 1 mask here
> u ^= u >> 4
> b = (u >> 8) & 0x1ff
> a = ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask
> here
> r = a ^ hash_adjust[b]
> return r
>
> HTH
Well, I guess there are two problemsthe masking and the fact the
in C it seems to for some reason overflow and become a negative
valuestill not sure why it does itSo the code with just
masking doesn't work, you still need some sort of weird inversion like
the ~(0x - u).weird
anyone?
haha
--
http://mail.python.org/mailman/listinfo/python-list
Re: error when porting C code to Python (bitwise manipulation)
On Jul 10, 4:04 pm, Harald Luessen <[EMAIL PROTECTED]> wrote:
> On Thu, 10 Jul 2008 Jordan wrote:
>
>
>
> >On Jul 10, 1:35 pm, MRAB <[EMAIL PROTECTED]> wrote:
> >> On Jul 10, 4:56 am, Jordan <[EMAIL PROTECTED]> wrote:
>
> >> > I am trying to rewrite some C source code for a poker hand evaluator
> >> > in Python. Putting aside all of the comments such as just using the C
> >> > code, or using SWIG, etc. I have been having problems with my Python
> >> > code not responding the same way as the C version.
>
> >> > C verison:
>
> >> > unsigned find_fast(unsigned u)
> >> > {
> >> > unsigned a, b, r;
> >> > u += 0xe91aaa35;
> >> > u ^= u >> 16;
> >> > u += u << 8;
> >> > u ^= u >> 4;
> >> > b = (u >> 8) & 0x1ff;
> >> > a = (u + (u << 2)) >> 19;
> >> > r = a ^ hash_adjust[b];
> >> > return r;
>
> >> > }
>
> >> > my version (Python, hopefully ;)):
>
> >> > def find_fast(u):
> >> > u += 0xe91aaa35
> >> > u ^= u >> 16
> >> > u += u << 8
> >> > u ^= u >> 4
> >> > b = (u >> 8) & 0x1ff
> >> > a = (u + (u << 2)) >> 19
> >> > r = a ^ hash_adjust[b]
> >> > return r
>
> >> > As far as I understand the unsigned instructions in C just increase
> >> > amount of bytes the int can hold, and Python automatically converts to
> >> > longs which have infinite size when necessary, so I am not sure why I
> >> > am getting different results.
>
> >> > I assume that I am missing something fairly simple here, so help a
> >> > n00b out if you can :)
>
> >> > Thanks in advance,
>
> >> > jnb
>
> >> You want to restrict the values to 32 bits. The result of + or << may
> >> exceed 32 bits, so you need to mask off the excess bits afterwards.
>
> >> def find_fast(u):
> >> mask = 0x
> >> u = (u + 0xe91aaa35) & mask
> >> u ^= u >> 16
> >> u = (u + (u << 8)) & mask # can get away with only 1 mask here
> >> u ^= u >> 4
> >> b = (u >> 8) & 0x1ff
> >> a = ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask
> >> here
> >> r = a ^ hash_adjust[b]
> >> return r
>
> >> HTH
>
> >Well, I guess there are two problemsthe masking and the fact the
> >in C it seems to for some reason overflow and become a negative
> >valuestill not sure why it does itSo the code with just
> >masking doesn't work, you still need some sort of weird inversion like
> >the ~(0x - u).weird
>
> >anyone?
>
> In C unsigned can not be negative. Why do you believe
> the numbers are negative? If your debugger is telling
> you this thow away the debugger and use printf.
> If printf is telling you this then use the right format.
> printf("%u", u); // for unsigned int u
> printf("%lu", u); // for unsigned long u
> printf("%x", u);
> or
> printf("0x%08x", u); // to see u in hex
>
> Harald
hahaI was using printf, but for some reason I decided not to use
%u...hmm...looking back over things now...
--
http://mail.python.org/mailman/listinfo/python-list
Re: error when porting C code to Python (bitwise manipulation)
Well, that about wraps this up...MRAB was 100% correct, that solution worked...not sure how I managed to mess it up when I tried it early. Based on the incoming values of u here is the code with the minimal number of maskings: def findit(u): mask = 0x u += 0xe91aaa35 u ^= u >> 16 u = (u + (u << 8)) & mask u ^= u >> 4 b = (u >> 8) & 0x1ff a = (u + (u << 2) & mask) >> 19 r = a ^ hash_adjust[b] return r Thanks for your help all! -- http://mail.python.org/mailman/listinfo/python-list
Python ver of System.arraycopy() in Java
I could seem to find a built in function that would serve the purpose of System.arraycopy() in java. I was able to accomplish it with something like this: def arraycopy(source, sourcepos, dest, destpos, numelem): dest[destpos:destpos+numelem] = source[sourcepos:sourcepos +numelem] is there a built in version, or better way of doing this... -- http://mail.python.org/mailman/listinfo/python-list
Re: graphing lifelines
There are several different modules for graphing in Python which you can find easily by searching, but to my knowledge none of them will simply take in a set of tuples and turn them into what you want, although I am sure that it is certainly possible to program a app that could do that for you... If you can't/don't want to program such an app and you don't have many data points, you could probably just cook one up using Photoshop/GIMP/ MSPaint, or whatnot (although clearly I could understand not wanting to do that for 100's of points)... sounds like an interesting project an auto lifeline maker that takes in data points...hmm -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I save command prompt screen
Let me take a stab:
I figure you either want to save something that is showing up in the
standard output in which case you can:
instead of using the print command to print to standard output, open a
file and append to that instead of printing, and then you can open
that up when you are done and see your results...
ex:
f1 = open("bla.txt","a")
f1.write('Wow, I love Python')
or you are using an interactive prompt and want to be able to rerun an
app:
you can write a file using python commands and then save it as a .py
file and run it using python in the command prompt
read this for better answers: http://www.diveintopython.org/
:)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Testing for connection to a website
On Jul 15, 3:43 pm, Alexnb <[EMAIL PROTECTED]> wrote: > Okay, I already made this post, but it kinda got lost. So anyway I need to > figure out how to test if the user is able to connect to a specific website. > Last time I got pointed to the urllib2 page, but if I do urlopen() and and > am not connected, the program stops. So I don't know if that was what you > guys wanted me to do, but I don't think so, you guys are smarter than that. > So, how can I test for connection to a website. > -- > View this message in > context:http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p... > Sent from the Python - python-list mailing list archive at Nabble.com. Ping it? ~_^ -- http://mail.python.org/mailman/listinfo/python-list
Re: % sign in python?
On Jul 17, 3:42 pm, Terry Reedy <[EMAIL PROTECTED]> wrote: > korean_dave wrote: > > What does this operator do? Specifically in this context > > > test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > > > (Tried googling and searching, but the "%" gets interpreted as an > > operation and distorts the search results) > > Having seen a number of comments like this over the years (about the > difficulty of searching for symbol meanings), I just started, last > night, a symbol index listing nearly all Python syntax uses of > non-alpha-or-digit ascii symbols. When I finish and upload it > somewhere, I will post an announcement with the link. > > tjr That sounds great Terry! I look forward to seeing this. ~Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about inheritence
On Jul 22, 12:26 pm, Catherine Heathcote <[EMAIL PROTECTED]> wrote: > If I create a new class inherited from another with a constructor, what > happens with the new class's constructer? > Thanks for your time. Well, the __init__ method of the subclass is called, and from within it you can call the superclass constructor. Here is a sample code: class A(): def __init__(self, bla): #do some stuff here class B(A): def __init__(self, bla2): #do some stuff here A.__init__(self,bla) -- http://mail.python.org/mailman/listinfo/python-list
Attack a sacred Python Cow
Hi everyone, I'm a big Python fan who used to be involved semi regularly in comp.lang.python (lots of lurking, occasional posting) but kind of trailed off a bit. I just wrote a frustration inspired rant on my blog, and I thought it was relevant enough as a wider issue to the Python community to post here for your discussion and consideration. This is not flamebait. I love Python, and I'm not out to antagonise the community. I also realise that one of the issues I raise is way too ingrained to be changed now. I'd just like to share my thinking on a misstep in Python's guiding principles that has done more harm than good IMO. So anyway, here's the post. I've become utterly convinced that at least one criticism leveled at my favourite overall programming language, Python, is utterly true and fair. After quite a while away from writing Python code, I started last night on a whim to knock up some code for a prototype of an idea I once had. It's going swimmingly; the Python Image Library, which I'd never used before, seems quick, intuitive, and with the all the features I need for this project. As for Python itself, well, my heart still belongs to whitespace delimitation. All the basics of Python coding are there in my mind like I never stopped using them, or like I've been programming in this language for 10 years. Except when it comes to Classes. I added some classes to code that had previously just been functions, and you know what I did - or rather, forgot to do? Put in the 'self'. In front of some of the variable accesses, but more noticably, at the start of *every single method argument list.* This cannot be any longer blamed as a hangover from Java - I've written a ton more code, more recently in Python than in Java or any other OO language. What's more, every time I go back to Python after a break of more than about a week or so, I start making this 'mistake' again. The perennial justification for this 'feature' of the language? That old Python favourite, "Explicit is better than implicit." I'm sorry, but EXPLICIT IS NOT NECESSARILY BETTER THAN IMPLICIT. Assembler is explicit FFS. Intuitive, clever, dependable, expected, well-designed *implicit* behaviour is one of the chief reasons why I use a high level language. Implicitly garbage collect old objects for me? Yes, please! I was once bitten by a Python wart I felt was bad enough to raise and spend some effort advocating change for on comp.lang.python (never got around to doing a PEP; partly laziness, partly young and inexperienced enough to be intimidated at the thought. Still am, perhaps.) The following doesn't work as any sane, reasonable person would expect: # Blog code, not tested class A(): def __eq__(self, obj): return True a = A() b = [] assert a == b assert not (a != b) The second assertion fails. Why? Because coding __eq__, the most obvious way to make a class have equality based comparisons, buys you nothing from the != operator. != isn't (by default) a synonym for the negation of == (unlike in, say, every other language ever); not only will Python let you make them mean different things, without documenting this fact - it actively encourages you to do so. There were a disturbingly high number of people defending this (including one quite renowned Pythonista, think it might have been Effbot). Some had the temerity to fall back on "Explicit is better than implict: if you want != to work, you should damn well code __ne__!" Why, for heaven's sake, should I have to, when in 99.99% of use cases (and of those 0.01% instances quoted in the argument at the time only one struck me as remotely compelling) every programmer is going to want __ne__ to be the logical negation of __eq__? Why, dear Python, are you making me write evil Java-style language power reducing boilerplate to do the thing you should be doing yourself anyway? What's more, every programmer is going to unconciously expect it to work this way, and be as utterly as mystified as me when it fails to do so. Don't tell me to RTFM and don't tell me to be explicit. I'll repeat myself - if I wanted to be explicit, I'd be using C and managing my own memory thank you very much. Better yet, I'd explicitly and graphically swear - swear in frustration at this entrenched design philosophy madness that afflicts my favourite language. I think the real problem with the explicit is better than implicit, though, is that while you can see the underlying truth its trying to get at (which is perhaps better expressed by Ruby's more equivocal, less dependable, but more useful Principle of Least Surprise), in its stated form its actually kind of meanginless and is used mainly in defence of warts - no, we'll call them for what they are, a language design *bugs*. You see, the problem is, there's no such thing of explict in programming. Its not a question of not doing things implicitly; its a question of doing the most sensible thing implicitly. For example this python code: some_obj.some_meth(so
Re: Attack a sacred Python Cow
On Jul 24, 3:41 pm, Jordan <[EMAIL PROTECTED]> wrote: > Hi everyone, > > I'm a big Python fan who used to be involved semi regularly in > comp.lang.python (lots of lurking, occasional posting) but kind of > trailed off a bit. I just wrote a frustration inspired rant on my > blog, and I thought it was relevant enough as a wider issue to the > Python community to post here for your discussion and consideration. > > This is not flamebait. I love Python, and I'm not out to antagonise > the community. I also realise that one of the issues I raise is way > too ingrained to be changed now. I'd just like to share my thinking on > a misstep in Python's guiding principles that has done more harm than > good IMO. So anyway, here's the post. > > I've become utterly convinced that at least one criticism leveled at > my favourite overall programming language, Python, is utterly true and > fair. After quite a while away from writing Python code, I started > last night on a whim to knock up some code for a prototype of an idea > I once had. It's going swimmingly; the Python Image Library, which I'd > never used before, seems quick, intuitive, and with the all the > features I need for this project. As for Python itself, well, my heart > still belongs to whitespace delimitation. All the basics of Python > coding are there in my mind like I never stopped using them, or like > I've been programming in this language for 10 years. > > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* This cannot be any longer blamed as a hangover from > Java - I've written a ton more code, more recently in Python than in > Java or any other OO language. What's more, every time I go back to > Python after a break of more than about a week or so, I start making > this 'mistake' again. The perennial justification for this 'feature' > of the language? That old Python favourite, "Explicit is better than > implicit." > > I'm sorry, but EXPLICIT IS NOT NECESSARILY BETTER THAN IMPLICIT. > Assembler is explicit FFS. Intuitive, clever, dependable, expected, > well-designed *implicit* behaviour is one of the chief reasons why I > use a high level language. Implicitly garbage collect old objects for > me? Yes, please! > > I was once bitten by a Python wart I felt was bad enough to raise and > spend some effort advocating change for on comp.lang.python (never got > around to doing a PEP; partly laziness, partly young and inexperienced > enough to be intimidated at the thought. Still am, perhaps.) > > The following doesn't work as any sane, reasonable person would > expect: > > # Blog code, not tested > class A(): > def __eq__(self, obj): > return True > a = A() > b = [] > assert a == b > assert not (a != b) > > The second assertion fails. Why? Because coding __eq__, the most > obvious way to make a class have equality based comparisons, buys you > nothing from the != operator. != isn't (by default) a synonym for the > negation of == (unlike in, say, every other language ever); not only > will Python let you make them mean different things, without > documenting this fact - it actively encourages you to do so. > > There were a disturbingly high number of people defending this > (including one quite renowned Pythonista, think it might have been > Effbot). Some had the temerity to fall back on "Explicit is better > than implict: if you want != to work, you should damn well code > __ne__!" > > Why, for heaven's sake, should I have to, when in 99.99% of use cases > (and of those 0.01% instances quoted in the argument at the time only > one struck me as remotely compelling) every programmer is going to > want __ne__ to be the logical negation of __eq__? Why, dear Python, > are you making me write evil Java-style language power reducing > boilerplate to do the thing you should be doing yourself anyway? > What's more, every programmer is going to unconciously expect it to > work this way, and be as utterly as mystified as me when it fails to > do so. Don't tell me to RTFM and don't tell me to be explicit. I'll > repeat myself - if I wanted to be explicit, I'd be using C and > managing my own memory thank you very much. Better yet, I'd explicitly > and graphically swear - swear in frustration at this entrenched design > philosophy madness that afflicts my favourite language. > > I think the real pro
Re: Attack a sacred Python Cow
Of course not. I just think Explicit is better than Implicit is taken seriously by a large segment the Python community as a guiding principle, and overall its influence does more harm than good. Clearly self being in every argument list was a decision arrived at long before the Zen was ever coined. Its merely an example of what I feel is a shortcoming in the conventional 'pythonic' approach to thinking about problems. The reluctance to admit that the __eq__ behaviour is a poor design choice is further evidence; its something (unlike self) that quite conceivably could be changed, and should be changed, but its somehow seen (by certain people) as the way that Python should do things. -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
On Jul 24, 7:40 pm, Torsten Bronger <[EMAIL PROTECTED]> wrote: > Hallöchen! > > Bruno Desthuilliers writes: > > [...] > > > How would you handle this case with an implicit 'self' : > > > class Foo(object): > > pass > > > def bar(self): > > print self > > > Foo.bar = bar > > Just like this. However, the compiler could add "self" to > non-decorated methods which are defined within "class". > > Tschö, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > Jabber ID: [EMAIL PROTECTED] Yeah, forgot what I said, Torsten's reply is much better :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
OK, it seems my original reply to Bruno got lost in the Aether (apologies therefore if a paraphrased "quantum duplicate" of this message is eventually forthcoming.) Torsten has adequately responded to his second point, so I need only replicated what I said for the first. > Please get your facts, the behaviour *is* actually fully documented: I have the facts. I know full well the behaviour is documented - it was pointed out at the time of the original discussion. Documenting a confusing, unintuitive design decision (whether its in a programming language, an end user GUI app or anything in between) doesn't justify it. To attack a strawman: "foolanguage uses the bar IO library; printing to stdout takes about 10 mins on the average machine. But thats ok, because look, its documented right here." > FWIW, the __lt__ / __le__ / __eq__ / __ne__ / __gt__ / __ge__ methods > set, known as "rich comparisons", was added in Python 2.1 to give more > fine-grained control on comparisons. If you don't need such a > granularity, just implement the __cmp__ method and you'll have all > comparison operators working as expected. First, the most serious justification for rich comparisons I remember seeing was that scipy "needed" them. I never saw a good reason scipy couldnt use methods like the rest of us mortals, nor why it was justifiable introducing a wart into the entire language for the sake of mildly conveniencing an (admittedly important and widely used) library. Second, fine, have silly C++-operator-overloading-style rich comparisons that confuse people reading your code if you must. Why does it have to be the default behaviour? Its people wanting __ne__ do do something other than not __eq__ who should have to be explicit about it. Third, __cmp__ is no good as a fix. Most classes that wan't equality comparison (== and !=) don't want ordered based comparison (>= etc.) thrown in as well. I shouldn't implement __cmp__ unless I want my class to implement every order comparison operator. Fourth, I'm trying to examine the wider implications of the Explicit > Implict mantra here, not resurrect an old campaign to change != behaviour that I think is probably a lost cause (if it happens as a side effect though, that'd be kinda cool.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
> This is just plain wrong for at least C# and C++. C# wants you to > explicitly overload "!=", if you have overloaded "==", While this is as inconvenient as Python at least it doesn't catch you unawares. C# 1 (or maybe 0.5), Python 0. > C++ complains > about "!=" not being defined for class A. See above. C++ 1, Python 0. So in showing my clearly hyperbolic comment was technically incorrect (something I could have told you myself), you have merely shown that two languages I find vastly inferior to Python overall are actually better than it in this case. > Fortunately, Python isn't designed according to your ideas, and won't > change, so consider your posting a waste of time. If feeling like bringing > such old "issues" up again next time, spend your time learning another > programming language, as you would obviously not get happy with Python > anyway ... OK, if that's your response, that's sad. Of course, I try to learn new languages all the time. Python is still IMO the best. If the attitude in the community in response to feedback/criticism has gone from "maybe you've got a point" to "your a lunatic, we'll never change", well, only Python will suffer in the long term. -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
On Jul 24, 8:01 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED] central.gen.new_zealand> wrote: > In message > <[EMAIL PROTECTED]>, Jordan > wrote: > > > Except when it comes to Classes. I added some classes to code that had > > previously just been functions, and you know what I did - or rather, > > forgot to do? Put in the 'self'. In front of some of the variable > > accesses, but more noticably, at the start of *every single method > > argument list.* > > The reason is quite simple. Python is not truly an "object-oriented" > language. It's sufficiently close to fool those accustomed to OO ways of > doing things, but it doesn't force you to do things that way. You still > have the choice. An implicit "self" would take away that choice. You could still explicitly request non-implicit self on a method by method basis. -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
> Personally, I think it has more to do with statements like "there are > plenty of smart Python programmers who will > justify all kinds of idiocy in the name of their holy crusade" than > with your position. You don't begin a discussion by discrediting > anyone who might disagree with you as some kind of religious bigot > while simultaneously holding that you are the only sane voice > speaking. I didn't set out to discredit anyone who might disagree with me; in fact I didn't in anyway try to pre-empt any person who might disagree with my thesis. I merely stated an observation - I have in the past seen seemingly intelligent people take silly stands in the name of Explicit is greater than Implicit (not just on comp.lang.python, and not just concerning != or self). I wish in retrospect I'd had the time, patience and focus to edit the initial post to make it more measured and less inflammatory, because its clear the tone detracts from the argument I'm making, which I feel still stands. So if you wish, ignore the specifics of the frustration that inspired me and consider only the thrust of what I'm saying: "Explicit is better than Implict" considered harmful. Discuss. -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
> I don't really mind, what you think about my response. Python will suffer > from it as little as it will suffer from your complaints: These things > will not change, whatever any of us says about them. So this discussion > unlikely to produce any new insight, especially because this as been > discussed over and over again in the past, without any effect on Python. You're right, of course. Because Python is in so many ways what I'm looking for in a language, I transform it in my mind to my own, personal ideal, close to the real existing language but with what I consider to be the imperfections removed. I'm not suggesting getting rid of explicit self, even in "Python 4000." Not because of the advantages it gives, which are some but don't outweigh the net loss in my ledger. It just wouldn't be Pythonic. I know its not a Pythonic thing to want. Thats my problem - because I have a largely Pythonic approach in some areas, it upsets me when there's a mismatch. So lets say I'm -1 for introducing it into a language and +0 for keeping it in Python now that its entrenched. If a lot of users keep bringing up something like this, well my attitude used to be the same as yours - "learn to love Python for what it is." Maybe > Let's just drop this, and if you want to complain next time, just complain > about something, that is really worth being complained about, like for > instance old and outdated modules in the standard library, or real > showstoppers in Python (e.g. the GIL). Its worth complaining about because I'm not just someone who has stumbled across Python after years of Java and PHP, and hasn't really grokked it, and has jumped on the net at once to start a flamewar. I'm someone who loves Python, uses it in preference to other languages, and have now returned to it after a bit of a break and its finally hit me over the head like a tonne of bricks "Hey, I can see exactly what all those internet trolls were talking about. This *is* a really annoying and silly state of affairs." I was trying not to change explicit self, or even != (which has a much better case.) I was trying to ask the community to reconsider a premise that the language is built around. Explicit is actually kinda annoying a lot of the time, viz., java. This is about social and philosophical adjustments, not technical ones. In reality? I'll just keep writing Python (hopefully enough so that explicit self become burned into muscle memory), and use other languages when necessary (no more C than I have to, looking forward to dabbling in Erlang soon, and one day overcoming the parentheses phobia enough to really tackle Lisp properly). When I'm old enough and wise enough, and have the time, energy and inclination, maybe I'll sit down and put a proper effort into designing and implementing a new language that bests suits my own particular style and needs. Just maybe it'll be good enough that smart people will rally to defend its design principles from people attacking them on the internet :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
> Then why do you write, let me quote: > > """ > (snip) coding __eq__ (snip) buys you > nothing from the != operator. != isn't (by default) a synonym for the > negation of == (unlike in, say, every other language ever); not only > will Python let you make them mean different things, without > documenting this fact - it actively encourages you to do so. > """ My words aren't as clear as they should be. I mean that Python lets *you* do something without documenting, or rather stating to use a better term, that your intention is the non-obvious one. I'm not saying that Python itself lacks documentation for its own behaviour; I'm saying it should force you to make your intentions clear and visible to someone reading your code when you want to do something non- obvious. > I was not commenting on the actual design choice, just stating that it > is actually documented. Yes, it is. I apologise for the poor construction of my statement which led to this confusion. > And you're talking about strawman ??? Come on, you obviously can tell > the difference between a one-line statement and your above strawman > argument, don't you ? I'm talking about strawmen because I was deliberately choosing to invoke one with rhetorical flourish for the purposes of making my point forcefully. I wanted people to be clear that I knew perfectly well what I was doing and that they needn't call me out on it. > Please understand that I'm not arguing about this particular design > choice (and FWIW, I'd mostly agree on the point that having a != b > different from not (a == b) is actually a wart). I'm just correcting > your statement about the behaviour of __eq__ / __ne__ not being > documented, which is obviously false. Good, at least we've come to a point in this discussion where I can firmly agree with somebody. -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
> > You're not a lunatic. > > We, and Python itself, change quite readily. > > Neither of those mean your ideas in this instance have merit. You're right, these premises don't lead to this conclusion. Neither do they lead to its negation, of course. As it happens, you're wrong on both counts. I do in fact suffer from a mental illness and have spent a week in a psych ward, so am a lunatic by some reasonable definitions. Python readily changes in some regards, but not in others. Of course, a great many things of worth have this as one of their essential qualities. Pithy replies are fun. > Thanks for your opinion. I disagree strongly: I think its influence is > nicely balanced by the other important principles that are also > followed. This isn't just being clever, there's substance here. A clearly stated opposing position, with a decent if somewhat short justification. I think you're right insofar as you go - that if someone really sits down, and thinks clearly about all the Pythonic principles, as a whole, and in detail, then the net result in the shaping their thinking will be positive more often than not. Perhaps we're just looking at an instance of a wider problem - smart people boil good ideas down into short slogans, which are nice and memorable and somewhat helpful, but can lead to bad consequences when lots of others start overusing or misunderstanding them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
Well this discussion is chugging along merrily now under its own steam, but as the OP I should probably clarify a few things about my own views since people continue to respond to them (and are in some cases misunderstanding me.) I *like* explicit self for instance variable access. There are arguments for and against, and my personal opinion is that the arguments for are stronger. Local variables and instance variables should be explicitly differentiated somehow, for the sake of readability. Python's approach works. I slightly prefer Ruby's @, because I think the brevity is a net win for something so commonplace (is it less readable? Maybe. is "def" less readable than "define"? I don't know - I think about 10 seconds of coding in Python or Ruby is enough for you to be able to instantly grok def. Likewise, @. The argument is more aesthetic IMO - how many perl-style/1337speak pu|\| ([EMAIL PROTECTED] [EMAIL PROTECTED]|<$ can you stand?) I have come to dislike explicit self in method argument lists. Sure, there are reasons. I don't think they're at all strong enough. I'm definitely against the != behaviour, and maybe will get around to actually PEPing it. The point I was trying to make originally was that applying any mantra dogmatically, including Explicit is better than implicit, can lead to bad results. Perhaps having Practicality beats purity is enough of a reminder of that fact for the Python community :-) -- http://mail.python.org/mailman/listinfo/python-list
Python Script for Colorizing Traceroute Output
I'm looking into writing a python script that colorizes particular hops when using traceroute. Anyone run across something like this? I don't think it would be extremely difficult to write but some example code would help. Basically particular hops in traceroute output would match a table as either a router, firewall or layer 3 switch and be colorized accordingly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Script for Colorizing Traceroute Output (apologies for top-post)
For this case the firewalls DO respond to TTL(in most cases) and will show in a traceroute. The objective here is to colorize particular devices to easily see what type of devices traffic would traverse across the network. I would be using a database of device hostnames that when they match in traceroute they would be printed a particular color. Something like router=green, layer 3 switch yellow, and firewall red. I'm just looking for a basic script to accomplish this. Nothing too fancy. -- http://mail.python.org/mailman/listinfo/python-list
A case for "real" multiline comments
I came across this case while debugging some Python code that contained an error stemming from the use of multiline strings as comments. The code contained a very long list of objects, and I had commented out some of the objects using the multiline string. This caused a string to be appended to the list instead of ignoring the section. Consider the following code: list = [ Object1(arg), """ Object2(arg), Object3(arg), """ Object4(arg) ] Real multiline comments would produce [Object1, Object4]. The list, in fact, contains [Object1, "Object2, Object3", Object4]. I can't really see a good way to get around this without true multiline comments. - Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Instant File I/O
That did the trick! Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Directly Executable Files in Python
Is it possible to make a directly executable (such as .exe on Windows) file from scripts written in Python? So as to prevent the end-user from having to download an interpreter to run the program. -- http://mail.python.org/mailman/listinfo/python-list
Stupid question, just need a quick and dirty fix
I'm trying to modify some code to suit my purposes and I'm just trying to filter results as necessary. Basically, the code is returning one of a number from a subset of 150 numbers. I want to only do anything with it if the number is a 'good' one. I'm by no means a Python programmer (C# for me by trade) and I'm not looking for anything that will be distributed..I just want something that works. Basically, here's what I'm trying to insert: global blnDesiredInd blnDesiredInd == False if IDNum < 10: blnDesiredInd = True if IDNum == 12: blnDesiredInd = True if IDNum == 15: blnDesiredInd = True if IDNum == 24: blnDesiredInd = True if IDNum == 25: blnDesiredInd = True if IDNum == 26: blnDesiredInd = True if IDNum == 27: blnDesiredInd = True if IDNum == 28: blnDesiredInd = True if IDNum == 31: blnDesiredInd = True if IDNum == 34: blnDesiredInd = True if IDNum == 35: blnDesiredInd = True if IDNum == 36: blnDesiredInd = True if IDNum == 37: blnDesiredInd = True if IDNum == 38: blnDesiredInd = True if IDNum == 39: blnDesiredInd = True if IDNum == 40: blnDesiredInd = True if IDNum == 45: blnDesiredInd = True if IDNum == 50: blnDesiredInd = True if IDNum == 51: blnDesiredInd = True if IDNum == 53: blnDesiredInd = True if IDNum == 55: blnDesiredInd = True if IDNum == 56: blnDesiredInd = True if IDNum == 57: blnDesiredInd = True if IDNum == 59: blnDesiredInd = True if IDNum == 62: blnDesiredInd = True if IDNum == 65: blnDesiredInd = True if IDNum == 68: blnDesiredInd = True if IDNum == 71: blnDesiredInd = True if IDNum == 76: blnDesiredInd = True if IDNum == 78: blnDesiredInd = True if IDNum == 80: blnDesiredInd = True if IDNum == 82: blnDesiredInd = True if IDNum == 83: blnDesiredInd = True if IDNum == 87: blnDesiredInd = True if IDNum == 88: blnDesiredInd = True if IDNum == 89: blnDesiredInd = True if IDNum == 91: blnDesiredInd = True if IDNum == 93: blnDesiredInd = True if IDNum == 94: blnDesiredInd = True if IDNum == 96: blnDesiredInd = True if IDNum == 97: blnDesiredInd = True if IDNum == 101: blnDesiredInd = True if IDNum == 103: blnDesiredInd = True if IDNum == 105: blnDesiredInd = True if IDNum == 106: blnDesiredInd = True if IDNum == 107: blnDesiredInd = True if IDNum == 109: blnDesiredInd = True if IDNum == 110: blnDesiredInd = True if IDNum == 112: blnDesiredInd = True if IDNum == 113: blnDesiredInd = True if IDNum == 115: blnDesiredInd = True if IDNum == 122: blnDesiredInd = True if IDNum == 124: blnDesiredInd = True if IDNum == 125: blnDesiredInd = True if IDNum == 126: blnDesiredInd = True if IDNum == 130: blnDesiredInd = True if IDNum == 131: blnDesiredInd = True if IDNum == 132: blnDesiredInd = True if IDNum > 133: blnDesiredInd = True if blnDesiredInd == True: I get various errors no matter what I do to this to try and make it work. Variable not defined. Referenced before assignment. etc etc. I'm lost. How do I make it work? -- https://mail.python.org/mailman/listinfo/python-list
Re: Stupid question, just need a quick and dirty fix
On Thursday, July 21, 2016 at 11:28:55 PM UTC-5, Chris Angelico wrote:
> On Fri, Jul 22, 2016 at 2:19 PM, Jordan Bayless wrote:
> > I get various errors no matter what I do to this to try and make it work.
> > Variable not defined. Referenced before assignment. etc etc. I'm lost. How
> > do I make it work?
>
> It might be easier if you post all your code. To be honest, what I'd
> be looking at is something like this:
>
> good_ids = {
> 12, 15, 24,
> ... # fill in all of these
> }
> desired = id < 10 or id > 133 or id in good_ids
>
> But it's possible your problem has nothing to do with your massive
> 'if' tree and everything to do with indentation or other problems we
> can't see.
>
> ChrisA
Posting the entire code snippet is tough because it's thousands of lines of
code. Basically, I'm inside of a For loop already. The code worked when I got
it, but I'm trying to tap into it and extend it outward to notify me via email
in certain circumstances. I got it to send the email, but it seems there's a)
no case statement (WTF?) and b) I'm limited to how many elif statements I can
use. Again, I don't particularly care how elegant this is because it's
ultimately getting disposed of sooner rather than later..I just want it to work.
Let me review my code and see if I can pare it down to the essentials so I can
give a better idea of what I'm doing.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Stupid question, just need a quick and dirty fix
No, I tried using a bunch of elif statements earlier and when I added more than
around 3 of them it threw errors. I just assumed that was some kind of limit.
We both agree that's piss-poor, lazy coding. I'm just trying to find something
that works though. To this point, everything I try fails.
I added your code and now it's telling me my variable isn't defined.
good_ids = {
2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 24, 25, 26, 27, 28, 31, 34, 35, 36, 37,
38, 39, 40, 45, 50, 51, 53, 55, 56, 57, 59, 62, 65, 68, 71, 76, 78, 80,
82, 83, 87, 88, 89, 91, 93, 94, 96, 97, 101, 103, 105, 106, 107, 109,
110, 112, 113, 115, 122, 124, 125, 126, 130, 131, 132, 134, 135, 136,
137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151
}
desired = Id < 10 or Id > 133 or Id in good_ids
When I try to validate whether I passed that check, I'm told there's a Name
error and it's not defined (using the last line of the snippet above).
Also, I guess I'm at a loss for what I'm supposed to do with "desired" to check
it prior to running my email code.
if desired == True: doesn't work
I'm headed to bed. Too tired to focus on making this work and I apparently
really don't 'get' what I'm doing. Maybe I'll be better off with fresh eyes on
it tomorrow.
--
https://mail.python.org/mailman/listinfo/python-list
Re: reading a list from a file
Be careful, though - make sure you can absolutely trust your source of data before calling eval on it. If an unauthorised person could forseeably modify your file, then they could insert a string containing arbitrary Python code into it in place of your list, and then running your program would cause that code to be executed. So, to put it bluntly, eval is dangerous. Sure is convenient, though :) -- http://mail.python.org/mailman/listinfo/python-list
Re: reading a list from a file
If you decide to steer clear of eval, the following comes close to what
you want, and is somewhat Pythonic (I feel):
def back_to_list(str):
return str.strip("[]").split(", ")
>>> s = "[1, 2, 3, 4, 5, 6]"
>>> back_to_list(s)
['1', '2', '3', '4', '5', '6']
So parsing the list structure is pretty easy. The problem is the list
elements are still in string form.
If they're only integers like in this example, you're fine. If they're
arbitrary objects, on the other hand, well then you may need eval after
all.
Question is, how did they get printed to a file in this form in the
first place?
--
http://mail.python.org/mailman/listinfo/python-list
Re: references/addrresses in imperative languages
You can add Australia to the list :) Any volunteers for a fourth continent? Antarctica, perhaps? ;) - Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Boss wants me to program
The problem with all posts that say "Use Visual Basic, its easy for small programs" is that small programs, seemingly inevitably, become bigger programs (unless they become dead, unmaintained programs). If your users - you, your boss, coworkers, whoever - find your software useful, and you start to get even remotely enthusiastic for the project, then you'll find yourself extending and developing new features, as well as having to fix problems in your existing code. And while I'm personally no expert at language design, I've noticed it seems to be a pretty solid consensus among the actual experts that VB is one of the most atrociously designed mass market programming languages in existence. Fine for small programs, sure. But if you ever want to even think about doing bigger programs, or extending those useful smaller programs to do more, or even maintain and fix bugs in your existing code, then VB is not going to be your friend. The major traditional advantage of VB is that it integrates very smoothly and easily with Windows, and it has powerful and simple GUI building tools. However, Microsoft have essentially displaced VB from lone occupancy of this niche with .NET. And part of the point of .NET is that its not forcing you into one particular choice of language. So there's no advantage to be had from using Visual Basic; youre better off using a language that might give you some sort of insight into good programming practice, not to mention one that'll allow you to develop a serious application if you ever need to. Ultimately, if you want a current, supported version of VB, you have to use VB .NET anyway, and if you're going to use .NET, why use VB at all? If you have some C++ experience, C# is probably a good bet, as has been pointed out. You get all the advantages that VB used to provide, with far fewer of the drawbacks, and it'll stand you in good stead to learn Java. Theres even a version of Python for .NET, called IronPython. The major advantage of this is that you get to program in Python, which I can tell you from experience is a lot more enjoyable and pain-free than C, C++, Fortran, or Java (and, I would highly suspect, VB and C#). But apparently the available GUI builders aren't as good for Python - having not done a whole lot of GUI building in general, I'll leave this for more experienced people to judge. [EMAIL PROTECTED] wrote: > I'm a manager where I work(one of the cogs in a food service company). > The boss needed one of us to become the "tech guy", and part of that is > writing small windows programs for the office. He wants the development > work done in house, and he knows I am in school for a CS minor. I know > basic C++(Part 2 of that is in the fall), and I will be taking Java 1 > in the fall also. What is the easiest way for me to make windows > programs that will do basic things like(Inventory, Menu Management, > etc...)? I have heard visual basic is where it's at. I want to keep an > open mind though, so I am wondering if python could be an option. The > programs have > no speed requirement. But they must be pretty, and not confuse my > boss. Plus he wants well documented help for each function. I asked the > windows programming group, but I thought I would ask here also. Thanks. > > Xeys -- http://mail.python.org/mailman/listinfo/python-list
Re: Will Guido's "Python Regrets" ever get implemented/fixed?
Python 3000 is the proveribal and so far hypothetical version of the language in which backward incompatible changes will be allowed (and encouraged). See http://www.python.org/peps/pep-3000.html for details. [EMAIL PROTECTED] wrote: > Guido gave a nice "Python Regrets" Power Point talk at OSCON few years > ago. > > I was wondering if the plan is to ever implement these ideas. > > e.g. Guido said he'd prefer 'print' to be a *function* with perhaps a > 'println' version IIRC. > >He also had a ton of stuff he'd rather see become iterators. > > Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: how to retrive highlighted text in a browser?
I don't know how hard this would be to do in Python - appending text to a file is straightforward, but it sounds like you'd need to extend the browser itself to get the functionality you want. The most obvious choice if you want an extensible browser is Mozilla Firefox (http://www.mozilla.org/products/firefox/), but AFAIK its extensions are written in C++, and I'm not sure how easy it would be to get Python into the mix. If you do get this working, I'd love to hear about it! I've wanted this feature in browers for a long time. -- http://mail.python.org/mailman/listinfo/python-list
String Manipulation
i'll be straight with you and say that this is a homework assignment. ive tried to figure it out on my own but am now out of time. i need to go through a .txt file and get rid of all punctuation. also, every time i see the work "Fruitloops=1" or "Hamburgers=x" where x is ANY number i need to get rid of that also. thanks a bunch. hurry please! jen :) -- http://mail.python.org/mailman/listinfo/python-list
String Manipulation
hey, i have this huge text file and i need to go through and remove all punctuation and every instance of the phrase "fruitloops=$" where $ is any number 0-100" um, and yeah this is homework but i've tried to no avail. thanks guys. cheerio :). jen -- http://mail.python.org/mailman/listinfo/python-list
Re: Path inherits from basestring again
Personally, I *like* the current distinction between + as a regular
string join, which gives the already much discussed benefit of allowing
paths to be dropped in seamlessly and painlessly anywhere strings are
currently used, and then having in addition the / operator for
"concatenate with a path separator." I think its intuitive, and the
option least likely to surprise someone encountering code that uses the
Path class for the first time - + works exactly like it always does,
and if they see a slash, which is an entirely new operator for
string-like objects, they'll be alerted to the fact they're getting
behaviour that differs from familiar string operators and methods.
Having + work differently when acting between a string and a path
versus a path and a path is in my mind a potential source of annoying
and subtle bugs, although hopefully they'd be rare in sensibly written
path-oriented code.
Sure, / means something completely different in the context of numbers.
So what? + and * are very different operators for numbers vs. strings,
but it doesn't generally trouble people too much; + has become pretty
widespread in programming conciousness as a string concatinator.
I don't think the argument that / and * are natural inverses holds much
water, either. In the context of sets in Python, - means set
difference, and +, its 'natural inverse', means nothing (in
mathematics, it typically means symmetric difference, which is
certainly not in any sense the inverse of -). This is all based on
arbitrary mathematical convention. The important point is that it
results in readable code for people who've dealt with sets before,
while trying to minimise the potential for surprises; not that it tries
to mirror the relationships between arithmetic operators, which I don't
think is an especially reasonable or normal thing to expect.
And I'm born and bred (unfortunately) on Windows machines, I do ALL my
Python programming in a Windows environment, so the "forward slash is
only an intuitive path seperator for POSIX hackers" argument doesn't
apply.
After all, anyone who's had any exposure to the internet can't be
entirely unfamiliar with the fact that forward slash can be used as a
path(-like) separator (please don't construe this as an attempt to
resurrect the "path should be used for URLs too" debate, though).
Ultimately, its just not different enough from backslash to be very
confusing (hear I'll put in a disclaimer, that I don't have enough
computing experience to know of any OS where neither type of slash is
used in paths.)
And thats my 14.5 cents :)
- Jordan Rastrick
Ron Adam wrote:
> Michael Hoffman wrote:
> > Ron Adam wrote:
> >
> >> In all current cases, (that I know of), of differing types, '+' raises
> >> an error.
> >
> >
> > Not quite:
> >
> > >>> "hello " + u"world"
> > u'hello world'
> > >>> 4.5 + 5
> > 9.5
> >
> >> Question: Is a path object mutable?
> >
> >
> > No.
> >
> > This should answer the rest of your questions.
>
> Yes it does, thanks.
>
> In the case of numeric types, it's an addition and not a join. I should
> have specified in 'all cases, (I know of), where '+' is used to join
> objects, but I thought that was clear from the context of the
> discussion. I haven't needed to use unicode yet, so it didn't come to mind.
>
>
> Although it raises other questions... ;-)
>
> Could a string prefix be used with paths as well?
>
> path = p"C://somedir//somefile"
>
>
> Would that clash with the 'u' prefix? Or would we need a 'p' and a 'up'
> prefix to differentiate the two?
>
> (Just a thought. I'm +0 on this, but this seems to be a new string type,
> and file operations are frequent and common.)
>
>
>
> You could have both behaviors with the '+'.
>
> path_a + path_b -> join path_b to path_a using separator.
>
> path + string -> append string to path (no separator)
>
> string + path -> prepends string to path (no separator)
>
>
> This would be similar, (but not exactly like), how u'text'+'text' and
> 'text'+u'text' work. They both return unicode strings given a standard
> string. It would allow the following to work.
>
>
> path = path('C:')+path('somedir')+path('somefile.txt')+'.zip'
>
> ->> 'C://somedir//somefile.txt.zip'
>
>
>
> So I guess the question here is which of these is preferable with '+'?
>
> 1. Strings act like paths when one is a path. They will be joined with
> a separator.
>
> 2. Paths are joined with separators *and* a string is prepended or
> postpended "as is" with no separator.
>
> 3. All path objects (and strings) act like strings. No separator is
> used when joining path objects with '+'.
>
>
> (Seems like #3 defeats the purpose of path a bit to me.)
>
>
> I'm +1 on #2 after thinking about it.
>
> Cheers,
> Ron
--
http://mail.python.org/mailman/listinfo/python-list
Re: Euclid's Algorithm in Python?
Raising an assertion error for a < b is a bit of overkill, since its not really a case of bad input. So normally you see Euclid done like this: def gcd(a,b): # All lowercase for a function is a bit more conventional. if a < b: a, b = b, a # Ensures a >= b by swapping a and b if nessecary while b != 0: # Note parentheses are unnessecary here in python a, b = b, a % b return a A bit more concise and no less readable (IMO). If you really want to check for actual bad input, youre better off testing, for example, than a and b are both greater than 0 [EMAIL PROTECTED] wrote: > Well, this article > http://pythonjournal.cognizor.com/pyj1/AMKuchling_algorithms-V1.html > was the first hit on google for '"euclid's algorithm" python'. > > It contains this function: > def GCD(a,b): > assert a >= b # a must be the larger number > while (b != 0): > remainder = a % b > a, b = b, remainder > return a > > Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaclasses and new-style classes
Correct me if I'm wrong, but I think the OP was asking if metaclasses
work with old-style classes, not new-style.
[EMAIL PROTECTED] wrote:
> This may be a limitation Zope imposes.
>
> I wrote this program:
> #---
> class M(type):
> def __new__(*args):
> print "new M", args
>
> class T(object):
> __metaclass__ = M
> #---
>
> Running it prints
> new M (, 'T', (,),
> {'__module__': '__main__', '__metaclass__': })
> ... so you can see that the __metaclass__ mechanism works just fine with
> new-style objects in plain Python.
>
> Jeff
--
http://mail.python.org/mailman/listinfo/python-list
Re: Euclid's Algorithm in Python?
Good point. I suppose I'd only ever seen it implemented with the if test, but you're right, the plain while loop should work fine. Silly me. def gcd(a,b): while b != 0: a, b = b, a%b return a Even nicer. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary inheritance
Talin asked: > Also, on a completely different subject: Has there been much discussion > about extending the use of the 'is' keyword to do type comparisons a la > C# (e.g. "if x is list:") ? > > -- Talin No, is already has a specific, well defined meaning - object identity. IDLE 1.1 >>> a = [1,2,3] >>> a is list False >>> b = type(a) >>> b >>> b is list True "Extending it" to mean something entirely different to what it currently means is a bad idea, and is also unnessecary - the builtin function isinstance already provides the functionaliy you're looking for: >>> isinstance(b, list) False >>> isinstance(a, list) True >>> However, use sparingly - calling isinstance unnessecarily rather than relying on polymorphism is considered pretty unpythonic, and usually reflects pretty poor OO design. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I exclude a word by using re?
could ildg said:
> I want to use re because I want to extract something from a html. It
> will be very complicated without using re. But while using re, I
> found that I must exlude a hole word "", certainly, there are
> many many "" in this html.
Actually, for properly processing html, you shouldn't really be using
regular expressions, precisely because the problem is complicated -
regular expressions are too simple and can't properly model a language
like HTML, which is generated by a context free grammar.
If thats only meaningless technical mumbo-jumbo to you, never mind -
the important point is you shouldn't really use an re. Trust me :)
What you want for a job like is an HTML parser. Theres one in the
standard library; if it doesnt suit, there are plenty of third party
ones. I like Beautiful Soup:
http://www.crummy.com/software/BeautifulSoup/
If you insist on using an re, well I'm sure someone on this group will
figure out a solution to your issue thats as good as you're going to
get...
>
> My re is as below:
> _
> r=re.compile(ur'valign=top>(?P\d{1,2})]*>\s{0,2}'
> ur''
> ur'(?P.+)',re.UNICODE|re.IGNORECASE)
> _
> There should be over 30 matches in the html. But I find nothing by
> re.finditer(html) because my last line of re is wrong. I can't use
> "(?P.+)" because there are many many "" in the html
> and I just want the ".*" to match what are before the firest "".
> So I think if there is some idea I can exclude a word, this will be
> done. Assume there is "NOT(WORD)" can do it, I just need to write the
> last line of the re as "(?P(NOT())+)".
> But I still have no idea after thinking and trying for a very long time.
>
> In other words, I want the "" of "(?P.+)" to be
> exactly the first "" in this match. And there is more than one
> match in this html, so this must be done by using re.
>
> And I can't use any of your idea because what I want I deal with is a
> very complicated html, not just a single line of word.
>
> I can copy part of the html up to here but it's kinda too lengthy.
> On 8/15/05, John Machin <[EMAIL PROTECTED]> wrote:
> > could ildg wrote:
> > > In re, the punctuation "^" can exclude a single character, but I want
> > > to exclude a whole word now. for example I have a string "hi, how are
> > > you. hello", I want to extract all the part before the world "hello",
> > > I can't use ".*[^hello]" because "^" only exclude single char "h" or
> > > "e" or "l" or "o". Will somebody tell me how to do it? Thanks.
> >
> > (1) Why must you use re? It's often a good idea to use string methods
> > where they can do the job you want.
> > (2) What do you want to have happen if "hello" is not in the string?
> >
> > Example:
> >
> > C:\junk>type upto.py
> > def upto(strg, what):
> > k = strg.find(what)
> > if k > -1:
> > return strg[:k]
> > return None # or raise an exception
> >
> > helo = "hi, how are you? HELLO I'm fine, thank you hello hello hello.
> > that's it"
> >
> > print repr(upto(helo, "HELLO"))
> > print repr(upto(helo, "hello"))
> > print repr(upto(helo, "hi"))
> > print repr(upto(helo, "goodbye"))
> > print repr(upto("", "goodbye"))
> > print repr(upto("", ""))
> >
> > C:\junk>upto.py
> > 'hi, how are you? '
> > "hi, how are you? HELLO I'm fine, thank you "
> > ''
> > None
> > None
> > ''
> >
> > HTH,
> > John
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
--
http://mail.python.org/mailman/listinfo/python-list
Re: question about binary and serial info
Sounds like you want the bitwise and operator, & >>> 2 & 3 2 >>> 32 & 16 0 >>> 31 & 12 12 etc. [EMAIL PROTECTED] inquired: > i have an interesting project at work going on. here is the challenge. > i am using the serial module to read data from a serial input. > it comes in as a hex. i need to make it a binary and compare it bit by > bit to another byte. They have some weird way they set this up that i > have to compare these things with AND. in other words, if bit 1 is 1 > AND bit 1 is 1 then the real value is 1... > > long story short. is there a good way to compare bytes, bit by bit with > one of the modules of python. i want to know so i dont get halfway into > developing this and find that there is a much better way to do this > than by hand. > > thanks for any suggestions. > sk <>< -- http://mail.python.org/mailman/listinfo/python-list
Re: list insertion
What you've posted looks right, more or less. To get any sort of meaningful feedback, you really need to post a full version of your code, including the print statements, what's being printed, and why you think this shows the code is not working. What you've shown is far too little for anybody else to work with. Regards, Jordan Randy Bush: > i am trying to insert into a singly linked list > > hold = self.next > self.next = DaClass(value) > self.next.next = hold > > but i suspect (from print statement insertions) that the result > is not as i expect. as the concept and code should be very > common, as i am too old for pride, i thought i would ask. > > mahalo, > randy -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write this iterator?
I've written this kind of iterator before, using collections.deque,
which personally I find a little more elegant than the list based
approach:
from collections import deque
def interleave(*iterables):
iters = deque(iter(iterable) for iterable in iterables)
while iters:
it = iters.popleft()
try:
yield it.next()
except StopIteration:
continue
iters.append(it)
>>> for item in interleave(xrange(6), "abc", ["gamma", "delta"]): print item
0
a
gamma
1
b
delta
2
c
3
4
5
I too came across the need for it while dealing with infinite
generators, where itertools.chain obviously won't suffice.
If you extended this approach to the class based solution it would have
the advantage of making append() an 0(1) operation, which is nice.
[EMAIL PROTECTED] wrote:
> >> Sorry, my description was not very good, I meant something behaving as:
> >>
> >> >>>example=Liter("abc","12345","XY")
> >> >>>for x in example: print x,
> >>
> >> a 1 X b 2 Y c 3 4 5
> >>
> >> or for that append() method,
> >>
> >> >>>example=Liter("abc", "12345")
> >> >>>for i in range(3): print example.next(),
> >>
> >> a 1 b
> >>
> >> >>>example.append("XY")
> >> >>>for x in example: print x,
> >>
> >> 2 c X 3 Y 4 5
>
> >Check the module I posted on
> >http://rafb.net/paste/results/CRT7bS68.html. append() makes things more
> >complicated -- mainly because generators don't accept attributes, so it
> >has to be wrapped in a class -- but the simple generator (without
> >append) is more manageable
>
> Thank you very much for your solution. Actually I needed that append()
> method quite a lot, so maybe my solution (posted at the beginning of this
> thread) was not that stupid :) (to inflate my ego a bit)
>
> Anyway, this is roughly what I used it for; is it a sane use of iterators?
>
> I was looking for the Holy Grail. I had an iterator 'quest' that produced
> either junk that was to be thrown away, or the Holy Grail itself, or
> another iterator of the same kind (that had to be searched for the Holy
> Grail as well). The iterators were potentially infinite. The code was
> rougly:
>
> quest=Liter(quest)
> for x in quest:
> if is_Holy_Grail(x):
> share_and_enjoy(x)
> break
> elif is_another_iterator(x):
> quest.append(x)
>
>
> Best regards
> P.
--
http://mail.python.org/mailman/listinfo/python-list
Suggesting a new feature - "Inverse Generators"
First, a disclaimer. I am a second year Maths and Computer Science undergraduate, and this is my first time ever on Usenet (I guess I'm part of the http generation). On top of that, I have been using Python for a grand total of about a fortnight now. Hence, I apologise if what follows is a stupid suggestion, or if its already been made somewhere else, or if this is not the appropriate place to make it, etc. But I did honestly do some background checking through the Python documentation, www.python.org, FAQs, and so forth before making this post. Basically what I'm trying to say here is, please don't flame this post :) Anyway, I have a suggestion to make for a rather radical new feature in Python. Rather than just struggling to explain and justify it straight out, I'll give the background of how I thought up the feature - and how I worked through the ideas I came up with. The example may seem a bit trivial to start, but bear with me, because I think theres at least some possibility the suggestion has merit. I am writing a project in Python atm, and one thing it needs to do is parse a very simple text file to get a list of records. Its a straightforward kind of thing that I (and I'm sure you) have done many times before in many languages. Each bit of interesting data in the file occurs over 3 or 4 lines of text. On top of this there are lines of random uninteresting junk as well. I decided to write a generator to filter out the junk lines, strip excess whitespace and the like (generators are one of my favourite features in Python). So the main body of code looks like this: def filterJunk(lines): for line in lines: # Do filtering & cleaning up stuff on line. # ... yield line def getData(filename): recordList = [] input = file(filename) lines = line.readlines() input.close() for line in filterJunk(lines): # ... create records and add to recordList So far, so good. Next comes the business of actually creating the records from the lines of interesting text. You can probably see the problem I ran into - I need to look at 3 or 4 lines at a time to create the record. Theres no easy way out of this requirement, because whether the record is contained in 3 or 4 lines is conditional on the value of the second line. But the for loop isn't going to allow me to do that. So I rewrote the for loop above as: while True: try: # do stuff repeatedly with lines.next() to add to recordList[] except StopIteration: pass This works. (And yes, there are also a multitude of other reasonably simple ways to approach this problem, some of which I've used in this past. And probably some fancy ways involving map and reduce as well.) But it seems ugly to me somehow. And I'm suspicious of anything that hints of ugliness (in Computer Science, anyway.) I suppose that Python's getting me into the habit of assuming theres always an elegant looking solution. I tried, and failed, to think of some sort of Generator-based concept (I really do love generators! So simple, but so useful!) that would allow me to retain a for loop. I guess that, essentially, I feel this task is really just iterating over the lines, and that iterating over something in Python is a job for a for loop. Generators allow you to use for loops all regular iteration. So I wanted to have something "vaugely Generator like", that would allow me to get back to using a for loop. It occured to me - what if I had some sort of "inverse generator" - a function with a resumable call mechanism that retained state, but that would resume when accepting input rather than returning output. For want of a better term, call it an Acceptor. If you think of a Generator as a method acting as (an abstraction of) a source of sequential data, then the Acceptor correspondingly is a sink. I started playing round with the Acceptor idea, thinking about how it might work. I imagined a simple mirroring of Generator syntax - using a new keyword, accept, to take in a value, just as Generator's use yield to return a value. Here's my first attempt at 'coding' my precious for loop using an imaginary Acceptor: def combineIntoRecord(): # This is an acceptor function optionalline = None # We may not get given a value for this line accept firstline accept secondline if condition(secondline): accept optionalline accept lastline r = createRecord(firstline, secondline, lastline, optionalline) return r recordlist = [] for line in lines: recordlist.append(combineIntoRecord(line)) I've since thought about it somewhat, and its clear I got this first try just plain wrong. Its got a number of hideous defects. First, combineIntoRecord() is 'accepting' its values by taking a magical argument, line, that does not appear in the argument list. Second, in this particular syntax, do combineIntoRecord(x)at line 50 and combineIntoRecord(y)at line 200 want x and y to be c
Re: Suggesting a new feature - "Inverse Generators"
Sorry about the mangled formatting... like i said, first time on Usenet Suggestions, comments, replies, etc most welcome. This definitely includes replies of the form: "This is stupid, because..." provided it isnt followed with "youre a jerk who knows nothing. Period." Heres a follow up rant in the form of a Q&A, trying to answer what I think are likely or interesting questions: Q: Is this idea even remotely feasible to actually implement? A: No Idea Q: Are you volunteering to implement it? A: Not really. I'd have no clue where to start. I probably don't even have enough C experience to begin to understand the Python source. But if some real Python dev (or devs)actually wants to implement this, and is willing to humour an undergraduate by somehow utilising assistance in form a very limited set of programming skills, well, then I'd be highly flattered and more than happy to help :) Q: The whole document is full of half-formed ideas, hundredth-formed ideas, mistakes(conceptual/typograhpcial/stylistic/grammatical/terminological/programming/...), inconsistencies, random nonsense.. A: Firstly, thats not a question, its a statment. Secondly, see the very first paragraph. Thirdly, the whole document, from initial attempts to code the original for loop (yes, it is a real program I'm trying to write here), to thinking of Acceptors, refining the model to something vaguely coherent, coming up with examples, and typing it all out, was produced on the fly, in the space of 5 hours or so. I attempted to give it a semblance of coherent structure at first, but soon gave up. Its basically stream of conciousness production. The bit where the first, nonsensical example is given, is literally where I first tried to forumlate the idea in code, saw the massive holes, stopped, thought about it for a few minutes, and came backed and typed out the much improved second version. The whole thing is totally unedited.Oh, and I had virtually no sleep last night. A real answer, with respect to the issue of terminology: If I use technical terms loosely, e.g., if I improperly use 'method' for 'function' or vice versa (a hang up from dealing with languages that only have one e.g. Java, or the other, e.g. C) , please forgive me. I hope what I'm trying to say is still clear enough. And as for coding style, Python itself is inconsistent (or to be more diplomatic, not obsessively concerned with the relatively minor issue of) using underscore_seperated_words or mixedCaseInstead, etc. And again, I cry the nefarious influence of Java Q: Did you steal this from somewhere else? A: No, its entirely something I thought of, by myself, in the last 5 hours. Thats not to say something like it (or more likely, better than it) hasnt been thought of somewhere else by someone else. But if it has, I havent seen it. To give credit where due though: I was motivated by the various examples, from sources like www.python.org, of how Generators can be used to do things really elegantly. Also, I'm still tossing around ideas in the back of my mind from a great talk given at my university by Rob Pike, of Google, about a language he helped devise and implement called sawzall (or something close). Its used to do processing with Google's massive data sets and highly parallel computing architecture, yet its incredibly simple to understand and very efficient. I guess it was only tenuously related to the idea presented here. But it was certainly very inspiring in a general computer-science-enthusiasm kind of way. Q: Why did you go to all this trouble thinking up this feature when you could have solved the original problem in so many other, simpler ways? A: I honestly can't give a decent justification :-) Whenever I've needed to do things like: line = readline from file if (line is some sort of 'extra' data) do something with line line = readline from file # get the 'regular' data ... in the past, in Pascal, Java and the like, it always irked me. Don't ask why, it just did. I thought I could get around it with generator in Python, but I couldnt. In trying to think of a generator solution, I more or less randomly thought of extending the generator concept somehow, and I decided to see where it took me. I thought it took me to somewhere interesting, and possibly worthy of further investigation. Q: What about using some sort of 'sequential data sink' that doesn't use 'pretending to be a function' syntax, e.g. a simple Class of some sort? A: Maybe. You can have Iterators without Generators. Maybe you can have "inverse Iterators" without "inverse Generators", I havent thought about it. I love the 'pretending to be a function' syntax, its part of what makes Generators so elegant. So I tried to emulate it. Q: What could be some of the benefits of introducing this feature? What could it be used for? A: Again, I don't really know. Past the examples I've given, I havent really thought about pos
Re: Suggesting a new feature - "Inverse Generators"
Thanks for the very fast feedback :) I specifically set optionalline = None to deal with that bug you mentioned, with the implicit assumption createRecord knows how to deal with a None argument. If that guard got destroyed in the copy paste process, my bad. As for you solution, yes, you could do it that way. But I'm not so much interested in alternate solutions to the problem itself, which is to be honest trivial. I'm intereseted in the implications of the imaginary solution of the Acceptor function. Just as you can have Iterators (an abstract class based solution to iteration) without Generators, yet Generators are still of interest, so you could solve this problem without Acceptors, yet Acceptors are (potentially) of interest. Basically, an Acceptor is linked to a Generator (or some other sequence) in the way you have linked the class implementation to a Generator. So this is a kind of implementation of an Acceptor using a class. I like the Acceptor syntax, though. And I'm wondering if maybe there are more complex examples that are harder or impossible to do your way... I think I already put something (briefer) in the Q&A bit along these lines -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggesting a new feature - "Inverse Generators"
Yes, granted. This is basically the same as Andrew's reply, except with Iterators in place of generators, so I'll let my answer to that stand. In fact, its my solution, but with iter.next() in place of accept :) This is probably something like how I wanted to solve the problem when I first was looking at it and wanting a generator based solution. I ended up thinking of this whole Acceptor business as part of getting me to this point. I'll try to reduce my pages of ranting to a single question. In posting, i was wondering if the "syntactic sugar" (Acceptors) that i invented to implement the solution is of any general interest. So are there maybe examples less straightforward than this one, where Acceptors work better? Or can you always just "turn the generator inside out" in the way you have done here? If you can always do it your way, well, thats a powerful design pattern, and it just goes to show my faith in Generators was justified :) And that I wasnt thinking hard /clearly enough about how to use them. There are other issues, like "Does the Acceptor syntax, although perhaps functionally equivalent to other methods, ever make the code more readable, easier to parse, etc?" But they're a lot less important i'd say. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggesting a new feature - "Inverse Generators"
Wow, if I'm going to get replies (with implemented solutions!) this quickly, I'll post here more often :-) This is the most different to my solution, and also the shortest, and therefore the most interesting, reply so far. Its also the last one I'll reply to before I go to bed. Its taken me a while to get a rough understanding of this code, but I think I have some idea. Correct me if I'm wrong. groupby groups based on value of line(record) Record returns 1 for the first line, 1 of the second, 1 for the 3rd, then 2 for the 4th because seq[0] gets incremented since len(line) > 20 OK thats fair enough. But how does record retain state between calls? How is that related to the fact your storing your value as a singleton list, instead just an int? It seems a little confusing to be honest, probably mainly due to my unfamiliarity with groupby. Retaining state between method calls is part of what interests me so much about the Generator/ Acceptor case. Here youre retaining state between calls with none of the special syntax used for example in Generators. How? Is it a side effect of the way groupby uses record? If so, then thats a littleoblique and unreadable for my liking. Is the state the record returns passed back to it somehow? I take it gets passed a value for seq at some point, seeing as how you've bothered to define it as a default argument rather than just seq = [0] on the first line. That works, but at the cost of having to return and pass all of state every call. I imagine other solutions (Generator/Acceptor based etc) would be substanitally more efficient. And again more readable, to a Python beginner such as myself at least. Still, this is fascinating going to have to spend some time experimenting with groupby as soon as I get a chance -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggesting a new feature - "Inverse Generators"
> No, it's nothing special about groupby. record simply stores its state in a > mutable default parameter. This isn't general good practice: at least you have > to be careful with it. You can see the behavior in the following example: > >>> def accumulate(value, accum = []): > ... accum.append(value) > ... return accum > ... > >>> accumulate(1) > [1] > >>> accumulate(2) > [1, 2] > >>> accumulate(6) > [1, 2, 6] > >>> Wow I'd never seen this kind of thing in examples of Python code. Although its really neat, it doesn't really make sense, intuituvely to me. Why does accum remember its state - I suppose its to do with the scope of arguments (as opposed to method variables) or something like that? Still, thats powerful. But I see why its not standard use - it could be easily abused! -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggesting a new feature - "Inverse Generators"
Hmmm, I like the terminology consumers better than acceptors. The ability to have 'full coroutines', or at least more 'coroutiney behaviour' than is provided by generators alone, was I think what I was trying to get at with my original idea, although things got a bit sidetracked by the way I focused on the particular (and not espeically interesting) example I provided. Another factor I think was that I restricted Acceptors far too much in the second version by demanding they receive all their input at once - that meant they weren't much more interesting than a function taking a generator or the like and using its output. The ability for them to accept input and resume execution at any point is an essential part of what would make such a feature interesting. Maybe if they gave you a callable object, and just avoided the whole issue of return value all-together, something like # I wish I could think of a more interesting example :) def combineIntoRecords(listToAppend): accept firstline # etc listToAppend.append(record) # No return value, avoid issues of non-evaluation recordList = [] combine = combineIntoRecords(recordList) for line in filterJunk(lines): combine(line) This acheives the same result as before, but of course now youre free to use combine anywhere else in the code if you wanted. I still think this kind would allow you to do things that can't be done using the other techniques brought up in this discussion... maybe Terry or somebody else familiar with Consumers might know a good example? Anyway this has all been very interesting, and I've learned a lot. I never really had a clue what Stackless Python was before, and now I think I have a vague idea of some of the implications. Not to mention the little tidbit about default argument evaluation. And groupby looks very interesting. Thanks everyone for the host of replies, which have all been of an excellent standard IMO. I only wish being a newbie in other languages was as much fun as it is in Python :) Now to actually finish implementing my text file parser. The only problem is deciding between the dozens of potential different methods... -- http://mail.python.org/mailman/listinfo/python-list
Re: the bugs that try men's souls
I think I found your bug, although it took a bit of time, a fair bit of
thought, and a fair bit of extra test-framework code - your program is
very concise, reasonably complex, and very unreadable. Its perfect for
testing maths theorems of your own interest, but you probably should
have polished it up a little, and explained a little more precisely
what the actual lines of code were supposed to be doing (as distinct
what mathematical ideas they were testing) before posting it to a forum
with a request for others to debug it.
I sympathise though - I'm a Maths undergraduate student myself, and I
often write dodgy, buggy code like this in high level languages like
Python, Haskell etc to test ideas :)
Anyway, from what I can tell the problem is with the line
print '%s %5s %3s' %(str([a,b]),int([p[a],p[b]] in
s),int([p[t[a]],p[t[b]]] in s))
I've assumed/deduced you mean for the expression:
([p[a],p[b]] in s)
to test whether (a,b) is an inversion of pt, i.e. is [pt(a),pt(b)] in
the collection s of stepup pairs (thats according to my understanding
of the terms you've used). But s is not complete list of stepup pairs
if you apply the 'xor filter' in the line you've labeled #MYSTERIOUSLY
BROKEN, its the list of stepup pairs sharing a co-ordinate with [a,b].
So you correctly identified the source of the bug as being at that
line.
I think (guess) what youre really trying to do is filter at the
printing stage, so you're just printing at those cases where {a,b} and
{x,y} share one and only one element, and ignoring the other trivial
cases - i'm inferring this from the fact you don't think the 'answers'
should change, just, presumably, the amount of output. This works:
def feedback(p,t):
## GIVEN A PERMUTATION f AND A STEPUP PAIR s WITH COORDINATES IN
THE RANGE OF f,
## SHOW THE INTEGER CASE OF THE PROPOSITION << f(s) IS A STEPUP
PAIR >>
k = 18
moved = [i for i in range(len(t)) if t[i]<>i]
g,h = min(moved), max(moved)
n = len(p) - 1
s = stepups(n)
print '-'*k
print 'p: ' + str(range(n+1)) + '\n ' + str(p)
print '-'*k
print 't = ' + str((g,h))
print '-'*k
print '%s %7s %3s' %('pair','p','pt') + '\n' + '-'*k
for [a,b] in s:
if xor(g in [a,b], h in [a,b]):
print ([p[a],p[b]]), ([p[t[a]],p[t[b]]])
print '%s %5s %3s' %(str([a,b]),int([p[a],p[b]] in
s),int([p[t[a]],p[t[b]]] in s))
print '-'*k
You can replace g and h if you want, they were pretty arbitrary
letters, but whatever you do dont use 'a' and 'b' twice like your
original code did, its awful programming practice. Even in Maths you
wouldnt let one pronumeral stand for two different quantities in the
same proof, its a recipe for disaster.
If this was wrong, and you really did want to test for inversion only
against the reduced set of pairs, a more complete explanation of what
kind of 'wrong answers' you are getting and what kind of 'right
answers' you were expecting might help. As far as I can tell though,
its quite natural the answers will be different when testing against a
subset of the stepup pairs when compared to testing against the whole
set.
Cheers,
Jordan
P.S. Oh, and if you come up with a proof of the proposition, let me
know, I'd like to see it :)
Sean McIlroy wrote:
> This needs some background so bear with me.
>
> The problem: Suppose p is a permutation on {0...n} and t is the
> transposition that switches x and y [x,y in {0...n}]. A "stepup pair"
> (just a term I invented) for p is a pair (a,b) of integers in {0...n}
> with a of p iff (p(a),p(b)) is NOT a stepup pair. Now, if {a,b}={x,y}, then
> clearly (a,b) is an inversion of p iff it is NOT an inversion of pt
> (functional composition). Also, if {a,b} and {x,y} are disjoint, then
> (a,b) is an inversion of p iff it is an inversion of pt. The
remaining
> cases are the ones where {a,b} and {x,y} have a single element in
> common, and of these, there are exactly as many inversions of p as
> there are of pt, though in general it is not the same set of stepup
> pairs for each function.
>
> The code below represents my attempt to apply python toward getting
> insight into why the number of inversions, with exactly one
coordinate
> in {x,y}, is the same for p and pt. The problem with the code is that
> if, at the relevant line ("MYSTERIOUSLY BROKEN"), I use the
> commented-out expression instead of the expression that's actually
> there, then in some cases the script gives a DIFFERENT ANSWER to the
> question whether a given pair is or is not an inversion of p
> respectively pt.
>
> I'd sure like to know what's going wrong with
Re: the bugs that try men's souls
Sean McIlroy wrote: > > Wow again. I had a real "V8 moment" when I looked at your solution > (smacking my forhead, groaning ruefully, etc). You were right: my > intention was simply to hide the trivial cases from view; I completely > missed the fact that I was now testing for membership in a different > set. I should have remembered that python "plays fair", and looked a > little harder to find my mistake. > > Thanks again, > Sean You're most welcome, I'm glad the solution was the right one. Its the kind of bug you can stare at mindlessly for hours without spotting it, but which will often be reasonably transparent to someone with a fresh perspective on the code. I had a doozy myself the other night, writing a mergesort for python's deque class (I can't believe it doesnt come with one!) the method would yield a queue with the right elements in it, but in a seemingly arbitrary order. Turns out, there was a > sign that needed to be a >= sign. GRRR. I bet if I'd posted to this group it would have been spotted in about 3 seconds flat :) - Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting a list and counting interchanges
Unless I'm mistaken, this doesnt quite work, because it switches the parity of phase every time a comparison is made, rather than every time a swap is made. So: # phase = 1 def mycmp(x,y): global phase c = cmp(x,y) if c > 0: # i.e. a swap will be performed in the sort phase = -phase return c -- http://mail.python.org/mailman/listinfo/python-list
Dynamically Cause A Function To Return
I want dynamically place the 'return' statement in a function via user input or achieve the same through some other means. If some other means, the user must be able initiate this at runtime during a raw_input(). This is what I have so far, this would be an awesome command line debugging tool if I can get it to work. def b(label="", *args): """Used to create breaks for debugging. Will break the function or continue the function it is place within based on user input. Has as a input loop for querying variables and executing code before a break or a continue.""" print label+":", for arg in args: print str(arg), if len(args): print x = "" while x != ".": command = raw_input() try: exec command except: pass -- http://mail.python.org/mailman/listinfo/python-list
Re: using names before they're defined
Steve Holden wrote: > [EMAIL PROTECTED] wrote: > > I have a problem. I'm writing a simulation program with a number of > > mechanical components represented as objects. When I create instances > > of objects, I need to reference (link) each object to the objects > > upstream and downstream of it, i.e. > > > > supply = supply() > > compressor = compressor(downstream=combustor, upstream=supply) > > combuster = combuster(downstream=turbine, upstream=compressor) > > etc. > > > > the problem with this is that I reference 'combustor' before is it > > created. If I swap the 2nd and 3rd lines I get the same problem > > (compressor is referenced before creation). > > > > > > aargh!!! any ideas on getting around this? > > > Yes. You are building a generic data structure, so you shouldn't really > be trying to store individual objects in variables like that. You need a > data structure that's appropriate to your problem. > > For example, you could consider storing them in a list, so you have > > components = [supply(), compressor(), combuster()] > > Then components[n] is upstream of components[n-1] and downstream of > components[n+1]. Unfortunately, if he wanted to make the topology more complicated, for instance having two components downstream, it would be much more cumbersome to inherit the list object and implement this. > In short, your thinking about data representation might need to become a > little more sophisticated. That sounds a little arrogant. sorry! > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about using python as a scripting language
Terry Reedy wrote:
> "heavydada" <[EMAIL PROTECTED]> wrote in message
>> I just need some way of
>> being able to read from the file what function the program needs to
>> call next. Any help is appreciated.
>
> Suppose you have a file actions.py with some action functions:
> def hop(self): ...
> def skip(self): ...
> def jump(self)
> Terry Jan Reedy
Another convenient way if, for some reason, you're not creating objects
for your creatures would be using a dictionary to look up functions, like:
def hop(x):
return x+1
def skip(x):
return x+2
def jump(x):
return x+3
actionlookup={"hop": hop, "skip": skip, "jump": jump}
action=actionlookup["hop"]
action() #this will call hop()
Please note that I'm only including this for completeness, for any
larger project (or medium sized, or anything more then a few lines,
really) this gets really unwieldy really quickly (imagine if you had
thousands of functions! Madness!) Terry's suggestion is a much better
solution then this. If this looks easier, consider changing the rest of
your program before kludging something hideous like this together.
Good luck,
-Jordan Greenberg
--
Posted via a free Usenet account from http://www.teranews.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: proper format for this database table
John Salerno wrote:
> Hi guys. I was wondering if someone could suggest some possible
> structures for an "Education" table in a database. It will contain at
> minimum university names, years of attendance, and degrees earned. My
> problem is that I don't know quite how to set this up for people who
> have attended multiple universities. I could do:
>
> university text DEFAULT NULL,
> yearStart integer DEFAULT NULL,
> yearEnd integer DEFAULT NULL,
> degreesEarned text DEFAULT NULL
>
> But this only allows for one university. (Also not sure if I should
> split up the years like that.) But mainly I'm looking for a way to
> construct this table so it can hold multiple universities, if necessary.
>
> Thanks.
Use associative tables.
Something like:
Table Students:
PK id (some unique id, maybe a student id#, or just an auto-inc)
name, etc...
Table Students2Education:
studentID (id from Students)
EducationID (id from Education)
Table Education:
id (probably just some auto-inc)
university
yearStart
yearEnd
degreesEarned
This way, if you have some students:
Students:
001 Jordan
and Jordan started university in 2003 @ Wentworth Institute of Technology:
Students2Education:
001 Wentworth_Institute_Of_Technology
Education:
1 Wentworth_Institute_Of_Technology 2003 NULL NULL
And then, in the future, say I go to MIT. By then I'll (hopefully) have
my CS degree...
Students:
001 Jordan
Students2Education:
001 Wentworth_Institute_Of_Technology
Education:
1 Wentworth_Institute_Of_Technology 2003 2007 BCOS
2 Massachusetts_Institute_Of_Technology 2008 NULL NULL
And I could go back to Wentworth and major in Computer Engineering this
time:
Education:
1 Wentworth_Institute_Of_Technology 2003 2007 BCOS
2 Wentworth_Institute_Of_Technology 2007 200
(You should probably use an integer ID for universities, and have a
separate table to link those to names. Something like:
Education:
UniversityID
yearStart
yearEnd
degreeEarned
Universities:
UniversityID
Name
City
Etc,etc)
In general, when you're having trouble representing something in a
database, it helps to break it down and model the smaller relationships
first, and use those as building blocks to model the whole relationship.
HTH.
Jordan Greenberg
--
Posted via a free Usenet account from http://www.teranews.com
--
http://mail.python.org/mailman/listinfo/python-list
