Re: segfault with small pyqt script
Lee, On 08/13/2010 12:53 AM, Lee Harr wrote: > >> I'm desperate. I'm having a real application, which fails rather often >> when finishing it. I'm not sure, whether any serious problem could be >> hidden behind it >> >> The script is a pyqt script, which segfaults most of the time on my >> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. > > > Looks to be a known issue: > http://www.google.com/search?q=pyqt+segfault+on+exit > https://launchpad.net/bugs/561303 > > The last activity on that bug is almost 2 months ago... > Hopefully the fix will be distributed soon. This seems to be the problem. In my case I can workaround the issue by adding one line. if __name__ == "__main__": app = QApplication([]) myform = MyForm() myform.show() retcode = app.exec_() myform = None # THIS IS THE WORK AROUND print "last" Thaks a lot -- http://mail.python.org/mailman/listinfo/python-list
How do I get number of files in a particular directory.
Hi, all, Is there a way to get a number of files in a particular directory? I tried using os.walk, os.listdir but they are return me with a list, tuple of the files, etc. But I want it to return a number. Is it possible? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get number of files in a particular directory.
blur959 a écrit : Hi, all, Is there a way to get a number of files in a particular directory? I tried using os.walk, os.listdir but they are return me with a list, tuple of the files, etc. But I want it to return a number. Is it possible? len(any_sequence) -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get number of files in a particular directory.
On 13Aug2010 00:54, blur959 wrote: | Hi, all, Is there a way to get a number of files in a particular | directory? I tried using os.walk, os.listdir but they are return me | with a list, tuple of the files, etc. But I want it to return a | number. Is it possible? Measure the length of the list returned to you? The len() built in function suggests itself... -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6,9 and 20
SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION On 08/12/10 21:41, News123 wrote: On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: On 08/11/10 21:14, Baba wrote: How about rephrasing that question in your mind first, i.e.: For every number that is one higher then the previous one*: If this number is dividable by: 6 or 9 or 20 or any combination of 6, 9, 20 than this number _can_ be bought in an exact number else print this number you are allowed to mix. 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 I was aware of that, thats whhy I wrote: "or any combination of 6, 9, 20" I guess, trying to find the result with divisions and remainders is overly complicated. Python 2.6.4 (r264:75706, Jul 1 2010, 12:52:41) [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 Type "help", "copyright", "credits" or "license" for more information. >>> MODULO_COMBINATIONS = [[20], [9], [6], ...[20, 9], [20, 6], [9, 20], ...[9, 6], [6, 20], [6, 9], ...[20, 9, 6], [20, 6, 9], [9, 20, 6], ...[9, 6, 20], [6, 20, 9], [6, 9, 20]] >>> >>> def apply_combinations_on(number): ... tmp = list() ... for combination in MODULO_COMBINATIONS: ... remainder = number ... for modulo_value in combination: ... if remainder == 0: ... remainder = None ... break ... ... result = remainder % modulo_value ... ... if result == remainder : ... remainder = None ... break ... ... remainder = result ... ... if remainder == 0: ... tmp.append(str(combination)) ... return(tmp) ... >>> print(apply_combinations_on(15)) ['[9, 6]'] >>> What is so over complicated about it? -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get number of files in a particular directory.
Hi, I tried that, but it doesn't seem to work. My file directory has many different files extensions, and I want it to return me a number based on the number of files with similar files extensions. But when I tried running it, I get many weird numbers. Below is my code i had so far and the result. import os directory = raw_input("Please input file directory. \n\n") s = raw_input("Please input a name to replace. \n\n") ext = raw_input("input file ext") for files in os.listdir(directory): if ext in files: file_number = len(files) print file_number The result is: 13 13 13 6 15 8 10 10 8 7 5 where the result should be just 11. Can anyone help me? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing libs on Windows?
Brian Salter wrote: It appears that every example is calling a dll, and I'm looking to bring in a lib. Does ctypes work with libs too? "Gary Herron" wrote in message news:mailman.2044.1281656800.1673.python-l...@python.org... On 08/12/2010 04:09 PM, Brian Salter wrote: I've seen a number of tutorials that describe how to bring in a dll in python, but does anybody know of a tutorial for how to bring in a lib? Is it even possible? Thanks, in advance! Look at the Python module named ctypes: http://docs.python.org/library/ctypes.html Gary Herron A lib file is not executable. It's a *description* of routines and data that has to be converted by a linker into actual executable code. The reason it's called a static lib is that once it is converted by the linker, the actual executable code resides inside the EXE file. So an application written in C doesn't ship with the lib file either (unless of course it's a compiler/linker). What's your actual goal? DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get number of files in a particular directory.
On 2010-08-13 11:18, blur959 wrote: > import os > > directory = raw_input("Please input file directory. \n\n") > s = raw_input("Please input a name to replace. \n\n") > ext = raw_input("input file ext") > > for files in os.listdir(directory): > if ext in files: > file_number = len(files) > print file_number > > > The result is: > 13 > 13 > 13 > 6 > 15 > 8 > 10 > 10 > 8 > 7 > 5 > > where the result should be just 11. Can anyone help me? Thanks. `os.listdir` returns a list of names. What you named `files` should actually be `filename`. What you got printed in the loop are the lengths of each filename. Stefan -- http://mail.python.org/mailman/listinfo/python-list
writing \feff at the begining of a file
Hello python world, I'm trying to update the content of a $Microsoft$ VC2005 project files using a python application. Since those files are XML data, I assumed I could easily do that. My problem is that VC somehow thinks that the file is corrupted and update the file like the following: - +? Actually, is displayed in a different color by vim, telling me that this is some kind of special caracter code (I'm no familiar with such thing). After googling that, I have a clue : could be some unicode caracter use to indicate something ... well I don't know in fact ("UTF-8 files sometimes start with a byte-order marker (BOM) to indicate that they are encoded in UTF-8."). My problem is however simplier : how do I add such character at the begining of the file ? I tried f = open('paf', w) f.write(u'\ufeff') UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 0: ordinal not in range(128) The error may be explicit but I have no idea how to proceed further. Any clue ? JM -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Martin P. Hellwig wrote: > SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION > > On 08/12/10 21:41, News123 wrote: > >> On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: >>> On 08/11/10 21:14, Baba wrote: >>> >>> >>> How about rephrasing that question in your mind first, i.e.: >>> >>> For every number that is one higher then the previous one*: >>> If this number is dividable by: >>> 6 or 9 or 20 or any combination of 6, 9, 20 >>> than this number _can_ be bought in an exact number >>> else >>> print this number >>> >> >> you are allowed to mix. >> 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 > > I was aware of that, thats whhy I wrote: > "or any combination of 6, 9, 20" > >> >> I guess, trying to find the result with divisions and remainders is >> overly complicated. > > Python 2.6.4 (r264:75706, Jul 1 2010, 12:52:41) > [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 > Type "help", "copyright", "credits" or "license" for more information. > >>> MODULO_COMBINATIONS = [[20], [9], [6], > ...[20, 9], [20, 6], [9, 20], > ...[9, 6], [6, 20], [6, 9], > ...[20, 9, 6], [20, 6, 9], [9, 20, 6], > ...[9, 6, 20], [6, 20, 9], [6, 9, 20]] > >>> > >>> def apply_combinations_on(number): > ... tmp = list() > ... for combination in MODULO_COMBINATIONS: > ... remainder = number > ... for modulo_value in combination: > ... if remainder == 0: > ... remainder = None > ... break > ... > ... result = remainder % modulo_value > ... > ... if result == remainder : > ... remainder = None > ... break > ... > ... remainder = result > ... > ... if remainder == 0: > ... tmp.append(str(combination)) > ... return(tmp) > ... > >>> print(apply_combinations_on(15)) > ['[9, 6]'] > >>> > > What is so over complicated about it? > Well, it was hard enough for me to run the code rather than just read it. I get >>> apply_combinations_on(21) [] which should be 1*9 + 2*6 What am I missing? Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: writing \feff at the begining of a file
On 13/08/2010 10:45, Jean-Michel Pichavant wrote: My problem is however simplier : how do I add such character at the begining of the file ? I tried f = open('paf', w) f = open ("pag", "wb") f.write ("\xfe\xff") TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Floating numbers
On Aug 12, 9:43 pm, Bradley Hintze wrote: > Hi all. > > Is there a way I can keep my floating point number as I typed it? For > example, I want 34.52 to be 34.52 and NOT 34.520002. Nitpick: unless you're on very unusual hardware, you're missing some zeros here. On my machine, under Python 2.6, the float 34.52 displays as 34.523, and the value stored internally is actually 34.5231263880373081783294677734375; so that's within 1 part in 10**16 of the value you entered. Why do you care? That's a serious question, and its answer goes a long way to determining what you should do. - If you're doing calculations with this number, then the difference between the number Python stores and 34.52 is so miniscule that in normal situations it's not going to matter. In particular, if it represents some physical quantity then any error in the representation will be swamped by the inherent measurement error. IOW, it's not worth worrying about. - If you're printing this number, and you just want the output to look nice (why? perhaps because you're showing this to other people?), then use float formatting operations to limit the number of decimal places you're printing. For example, '%.6f' % my_float, or format(my_float, '.6f'), will give my_float to 6 places after the decimal point. Or, as others have mentioned, it just so happens that Python 2.7 and 3.x will output a nice representation for this float automatically. That wouldn't necessarily be true if the result were coming from a calculation, though, so you shouldn't rely on repr producing nice results in those versions of Python. - If you *really* need a number that represents the *exact* value 34.52, then use the decimal module, or perhaps consider using a simple home-brewed fixed-point representation. One situation where you might care is when doing financial calculations, and in particular when rounding a quantity to a smaller number of decimal digits. Here binary floats can give unpredictable results in halfway cases. (E.g., round(2.675, 2) might give 2.68 or 2.67, depending on what version of Python you're using, and also possibly depending on your platforms.) -- Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 12, 2010, at 10:51 PM, John Posner wrote: On 8/12/2010 9:22 AM, Dave Angel wrote: Now you have to find the largest number below 120, which you can easily do with brute force tgt = 120 # thanks, Dave Angel Anytime, but I'm not Dave Angel. My previous algorithm was more efficient, but for those who like one- liners: [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) for b in range(x/9) for c in range(x/6))][-1] Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Deditor -- pythonic text-editor
Hey, I've finished my second version of deditor, a python text-editor for python under linux. It offers some python-only features like an interpreter, a code- analyzer, syntax-highlighting,... Are there some people in here who would like to test the app? (and maybe even help spread it) more info can be found on launchpad: https://launchpad.net/deditor or you can mail me darragh@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 13, 2010, at 12:25 PM, Roald de Vries wrote: My previous algorithm was more efficient, but for those who like one- liners: [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) for b in range(x/9) for c in range(x/6))][-1] OK, I did some real testing now, and there's some small error in the above. All solutions for all x's are given by: [(x, a, b, c) for x in range(120) for a in range(x/20+1) for b in range(x/9+1) for c in range(x/6+1) if x == a*20+b*9+c*6] ... and all non-solutions by: [x for x in range(120) if not any(x == a*20+b*9+c*6 for a in range(x/20+1) for b in range(x/9+1) for c in range(x/6+1))] Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Python CGI windows
Dear All, I Have certain clarification in python CGI. I use Python IDLE *1. How do we execute CGI Scripts in Windows? 2. How do i configure the Server?(If i use WAMP,XAMPP) 3. Is mod_python required for python cgi? * Someone Please revert back to me with the solution for the same.I would be at-most thankful -- Thanks & Regards, Srikanth.N -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6,9 and 20
On 08/13/10 10:46, Peter Otten wrote: Martin P. Hellwig wrote: SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION No it wasn't :-) which should be 1*9 + 2*6 What am I missing? Aah interesting, 21 % 9 returns 3 instead of 12, which makes sense of course. I guess the algorithm has to be adapted in a way that if the value is bigger or equal twice the size of the modulo value you need to iterate over it, something like: for minus_multiplier in range(1, int(number, modulo_value)+2): number = number - (modulo_value * minus_multiplier) do the rest of the loop Probably another ten lines or so to make it working as it should -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: writing \feff at the begining of a file
Jean-Michel Pichavant wrote: > My problem is however simplier : how do I add such character [a BOM] > at the begining of the file ? > I tried > > f = open('paf', w) > f.write(u'\ufeff') > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in > position 0: ordinal not in range(128) Try the codecs module to open the file, which will then do all the transcoding between internal texts and external UTF-8 for you. Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get number of files in a particular directory.
On Aug 13, 6:09 pm, Peter Otten <__pete...@web.de> wrote: > blur959 wrote: > > Hi, I tried that, but it doesn't seem to work. My file directory has > > many different files extensions, and I want it to return me a number > > based on the number of files with similar files extensions. But when I > > tried running it, I get many weird numbers. Below is my code i had so > > far and the result. > > Use glob.glob() instead of os.listdir() if you are only interested in files > with a specific extension: > > >>> import glob > >>> len(glob.glob("*.py")) > > 42 > > Peter Hi, I want to make it such that the user inputs a file extension and it prints the number of similar file extensions out. I tried doing this: directory = raw_input("input file directory") ext = raw_input("input file ext") file_list = len(glob.glob(ext)) print file_list And my result was this: 0 which it is suppose to be 11 May I know why? And how do I specify which directory it is searching the files extension from? I want the user to specify a directory and it searches the particular directory for the particular file extensions and prints the number out. Hope you guys could help. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Inserting/Deleting newline(s) in very large text files
I would greatly appreciate a python solution as this problem is only the head of a larger problem for which I am on a mission to write a FULL one-stop-shop python script. I am trying two things- iter() and fileinput module... Thanks! From: Matty Sarro To: Dlanor Slegov Sent: Thu, August 12, 2010 5:22:58 PM Subject: Re: Inserting/Deleting newline(s) in very large text files On Thu, Aug 12, 2010 at 11:12 AM, Dlanor Slegov wrote: Hi, > >I am dealing with very large text files (a few million lines) and would like >to >check and modify them according to a well defined format. The format >requires ONLY ONE NEWLINE (followed by some sort of text) on top of the file >and >NO NEWLINE in the very end. The input files can be very diverse, such as one >file may have 2 newlines on top and none in the end or other may not have a >newline on top and 5 in the end. > > >The aim is to check these files & introduce JUST ONE NEWLINE in the TOP and NO >NEWLINE in the BOTTOM. > >Any pointers will be appreciated. > >Thanks, >DS. > > >-- >http://mail.python.org/mailman/listinfo/python-list > > If you're using a unix box you may want to look into sed. sed -i. '1i text to be inserted in first line' For example: sed -i.bak '1i alias bond0 bonding' /etc/modprobe.conf Would back up the original file to the initial filename plus the extension .bak. Then it would insert: alias bond0 bonding into /etc/modprobe.conf Into the 1st line of the file, moving everything else down one line. You can find some info on dealing with newlines here: http://www.grymoire.com/Unix/Sed.html#toc-uh-nl I know you're looking for a python solution, but this may be easier. Just a heads up. -- http://mail.python.org/mailman/listinfo/python-list
Embedding, subinterpreters and dynamic types
Hi, this is my first contact with the python community so I hope this is the right place for my two questions. They are both related to embedding and extending python. I'm writing a program that dynamically loads c++ modules that extend the functionality of my program. These modules are controlled by scripts. Currently I have embedded the v8 javascript engine but I would also like to support scripts written in python. I have a special interface between the c++ modules and the scripts to be able to support different scripting languages. Scripts are separated into different 'applications' that are executed in one process triggered by external events (no threading, since I'm working in an event driven system). The scripts should execute independently of each other. I solved this with v8 by switching between the applications' contexts. However, it seems like python has some issues with this. 1. To do some basic context switching I assume I should use a sub interpreter ie create a new thread state (without any actual threads). I cannot find any information on how to do this except creating the new thread state. Is this the preferred way of doing this, if so, how do I switch between different thread states and execute scripts in them? I assume scripts running in one thread state are isolated from scripts running in other thread states, like global variables and such (except for the GIL thing?) ? I do not care much about security problems like file descriptor issues and extension issues right now. 2. When a new C++ module is loaded into my program I want to create a representation of it in Python. Not as a type, but rather just return a single object instance reference of a new type representing the exported attributes and methods of the module's C++ class. In other words, I want to be able to do something like this obj = application.getObject("objectId"); where objectId is the name of an instance of that c++ module type. I do not want the script to be able to create new instances of this type, since this is done via xml in my program. Hence I would also like to be able to associate my C++ object with my returned python object to be able to manipulate it when methods are called on 'obj'. So how do I define a new type on the fly and create an instance of it, associated with a c++ pointer and return it in the c function representing the python method 'getObject' in my application module? Hope this makes any sense, let me know if something is unclear. Regards Mikael Liljeroth -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get number of files in a particular directory.
blur959 wrote: > On Aug 13, 6:09 pm, Peter Otten <__pete...@web.de> wrote: >> blur959 wrote: >> > Hi, I tried that, but it doesn't seem to work. My file directory has >> > many different files extensions, and I want it to return me a number >> > based on the number of files with similar files extensions. But when I >> > tried running it, I get many weird numbers. Below is my code i had so >> > far and the result. >> >> Use glob.glob() instead of os.listdir() if you are only interested in >> files with a specific extension: >> >> >>> import glob >> >>> len(glob.glob("*.py")) >> >> 42 >> >> Peter > > > Hi, I want to make it such that the user inputs a file extension and > it prints the number of similar file extensions out. > I tried doing this: > > directory = raw_input("input file directory") > ext = raw_input("input file ext") > > file_list = len(glob.glob(ext)) > print file_list > > > And my result was this: > 0 > which it is suppose to be 11 > > May I know why? And how do I specify which directory it is searching > the files extension from? I want the user to specify a directory and > it searches the particular directory for the particular file > extensions and prints the number out. > Hope you guys could help. The part of the filename you don't care about has to be replaced with a "*": import os import glob directory = raw_input("directory? ") ext = raw_input("file extension? ") pattern = os.path.join(directory, "*" + ext) matching_files = glob.glob(pattern) print len(matching_files), "matching files" Note that you'll learn a lot more when you look up in the documentation how the functions mentioned actually work instead of coming back here for every tiny detail. I you don't feel ready yet to understand enough of the Python documentation, go one step back and work your way through a tutorial or introductory book. A starting point is here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get number of files in a particular directory.
blur959 wrote: On Aug 13, 6:09 pm, Peter Otten <__pete...@web.de> wrote: blur959 wrote: Hi, I tried that, but it doesn't seem to work. My file directory has many different files extensions, and I want it to return me a number based on the number of files with similar files extensions. But when I tried running it, I get many weird numbers. Below is my code i had so far and the result. Use glob.glob() instead of os.listdir() if you are only interested in files with a specific extension: import glob len(glob.glob("*.py")) 42 Peter Hi, I want to make it such that the user inputs a file extension and it prints the number of similar file extensions out. I tried doing this: directory =aw_input("input file directory") ext =aw_input("input file ext") file_list =en(glob.glob(ext)) print file_list And my result was this: 0 which it is suppose to be 11 May I know why? And how do I specify which directory it is searching the files extension from? I want the user to specify a directory and it searches the particular directory for the particular file extensions and prints the number out. Hope you guys could help. Thanks Glob doesn't do much useful unless there's a wildcard. And as you point out, it also needs the directory. You want to pass it something like mydirect/*.txt In your case, you might construct that with something like os.path.join(directory, "*." + ext) DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Floating numbers
A quick question. I understand how to get these numbers 34.5231263880373081783294677734375 and 47 (from 2**47) and the sign. with the decimal module, but I fail to find this one 4858258098025923 Possible? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get number of files in a particular directory.
Hi all, I got a problem with my script. Everything looks good so far but for some reason my os.rename isn't working. Can anyone tell me why? Hope you guys could help. Thanks. import os import glob directory = raw_input("directory? ") ext = raw_input("file extension? ") r = raw_input("replace name") pattern = os.path.join(directory, "*" + ext) matching_files = glob.glob(pattern) file_number = len(matching_files) for filename in os.listdir(directory): if ext in filename: path = os.path.join(directory, filename) seperated_names = os.path.splitext(filename)[0] replace_name = filename.replace(seperated_names, r) split_new_names = os.path.splitext(replace_name)[0] for pad_number in range(0, file_number): padded_numbers = "%04d" % pad_number padded_names = "%s_%s" % (split_new_names, padded_numbers) newpath = os.path.join(directory, padded_names) newpathext = "%s%s" % (newpath, ext) new_name = os.rename(path, newpathext) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
> ... However, the killer reason is: "it's what everybody > else does. If this were really true, lists would be 1-based. I go back to WATFOR; and Fortran (and I believe Cobol and PL/I, though I'm not positive about them) were 1-based. (Now that I think about it, PL/I, knowing IBM, could probably be set to use either) Back then, everyone else was doing 1-based lists. In my opinion, the reason lists are 0-based started with a lazy programmer who decided that his own comfort (using 0-based addressing at the machine level and not having to translate the high-level 1- based language index into a low-level 0-based index) was paramount over teaching the language and having it make sense in the real world. After all, not even Brian Kernighan thinks books start on page 0. I'm not singling out C in this case because it is a relatively low- level language for low-level programmers and 0-based lists make perfect sense in that context. But then every compiler/interpreter programmer after that stopped caring about it. I smile every time I see the non-nonsensical sentence "The first thing, therefore, is in thing[0]" in a programming language learning book or tutorial. I laugh every time I hear someone defend that as common sense. Every three year old watching Sesame Street knows counting things starts with '1', not '0'. When you were three and you counted your blocks, you started with '1', not '0'. The whole rest of the world understands that implicitly, even if their counting starts '1', '2', 'many'. 0-based lists are NOT common sense. They only make sense to the programmers of computer languages, and their fanbois. There may be loads of reasons for it, but don't throw common sense around as one of them. Den -- http://mail.python.org/mailman/listinfo/python-list
Re: Floating numbers
On Aug 13, 3:03 pm, jmfauth wrote: > A quick question. > > I understand how to get these numbers > > 34.5231263880373081783294677734375 > > and > > 47 (from 2**47) > > and the sign. > > with the decimal module, but I fail to find this one > > 4858258098025923 > > Possible? See the float.as_integer_ratio method. -- Mark -- http://mail.python.org/mailman/listinfo/python-list
text to DB
I have a text file in this format PRA 1:13 2:20 3:5 SRA 1:45 2:75 3:9 TRA 1:2 2:65 3:45 pattern is- Book Chapter:Verses now i have my DB schema like this book_id chapter_id versed_id 1 1 13 1 2 20 1 3 5 2 1 45 2 2 75 2 3 9 3 1 2 3 2 65 3 3 45 I want to write a pyhton script which read the text file and dump to DB could any one give me suggestion -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding, subinterpreters and dynamic types
On 2010-08-13 13:22, Mikael Liljeroth wrote: > Hi, this is my first contact with the python community so I hope this > is the right place for my two questions. > They are both related to embedding and extending python. > > I'm writing a program that dynamically loads c++ modules that extend > the functionality of my program. > These modules are controlled by scripts. Currently I have embedded the > v8 javascript engine but I would also like to support scripts written > in python. I have a special interface between the c++ modules and the > scripts to be able to support different scripting languages. Scripts > are separated into different 'applications' that are executed in one > process triggered by external events (no threading, since I'm working > in an event driven system). The scripts should execute independently > of each other. I solved this with v8 by switching between the > applications' contexts. However, it seems like python has some issues > with this. > > 1. To do some basic context switching I assume I should use a sub > interpreter ie create a new thread state (without any actual threads). > I cannot find any information on how to do this except creating the > new thread state. Is this the preferred way of doing this, if so, how > do I switch between different thread states and execute scripts in > them? I assume scripts running in one thread state are isolated from > scripts running in other thread states, like global variables and such > (except for the GIL thing?) ? I do not care much about security > problems like file descriptor issues and extension issues right now. > Py_NewInterpreter does indeed sound like what you want. I have a feeling you're going to run into problems here sooner or later, say, when extension modules that aren't yours use static variables. As for switching interpreters, after skimming the docs, I'm guessing you're looking for PyEval_AcquireThread http://docs.python.org/py3k/c-api/init.html#PyEval_AcquireThread > 2. When a new C++ module is loaded into my program I want to create a > representation of it in Python. Not as a type, but rather just return > a single object instance reference of a new type representing the > exported attributes and methods of the module's C++ class. In other > words, I want to be able to do something like this obj = > application.getObject("objectId"); where objectId is the name of an > instance of that c++ module type. I do not want the script to be able > to create new instances of this type, since this is done via xml in my > program. Hence I would also like to be able to associate my C++ object > with my returned python object to be able to manipulate it when > methods are called on 'obj'. So how do I define a new type on the fly > and create an instance of it, associated with a c++ pointer and return > it in the c function representing the python method 'getObject' in my > application module? > How difficult this is obviously depends somewhat on how varied the types you create are, but in principle, there's no difference between creating a type statically and creating one on-the-fly: all you need to do to create a type is create a PyTypeObject structure with suitable function pointers. If you want to make it impossible to create a second instance of your type, you can simply create a tp_new or tp_init that raises an exception. If you have a good look at http://docs.python.org/py3k/extending/newtypes.html , you'll notice that most of the "creating a type" involves writing a static PyTypeObject structure -- you'll just have to allocate that yourself, and you should be good. -- http://mail.python.org/mailman/listinfo/python-list
Re: python interview quuestions
On 11 August 2010 13:34:09 UTC+1, Steven D'Aprano wrote: > Getting interviewees to do a take-home problem just means you hire the > guy who is friends with a good programmer, rather than the good > programmer. We give a take-home problem. If we like the code we see, we invite the candidate to come in and pair with one of our devs in adding a simple feature or two to their own code. It's time consuming, but not so time consuming as hiring a weak dev. -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
how to make portable distribution of python 2.6?
All greetings! How to make portable distribution of python 2.6? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On 2010-08-13 17:27, Den wrote: > There may be loads of reasons for it, but don't throw common sense > around as one of them. > It's a good thing then that I didn't: >> ... However, the killer reason is: "it's what everybody >> else does. >> > "Where it all started" is that 0-based indexing gives languages like C a very nice property: a[i] and *(a+i) are equivalent in C. From a language design viewpoint, I think that's quite a strong argument. Languages based directly on C (C++, Objective C, ...) can't break with this for obvious reasons, and other language designers/implementers imitated this behaviour without any good reason to do so, or not to do so. In higher-level languages, it doesn't really matter. 1-based indexing might seam more intuitive, but in the end, it's just another thing you have to learn when learning a language, like "commas make tuples", and somebody studying a programming language learns it, and gets used to it if they aren't used to it already. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make portable distribution of python 2.6?
On 2010-08-13 19:00, zaur wrote: > All greetings! > > How to make portable distribution of python 2.6? > I don't know, but what you're looking for probably already exists. Do you mean "portable" as in portable, i.e. "take this and build it for your system, it should work if your OS is supported"? Then you can get source tarballs from python.org http://python.org/download/ Or do you understand "portable" the way that is fashionable in the Windows world nowadays for some reason, i.e. "look, Ma, already installed if you happen to use Microsoft Windows of roughly the right version!" Then http://www.portablepython.com/ is exactly where Google would have lead you had you searched. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python CGI windows
On 2010-08-13 12:40, Srikanth N wrote: > *1. How do we execute CGI Scripts in Windows? > * You'll need a web server. > *2. How do i configure the Server?(If i use WAMP,XAMPP) > * For CGI, you just need your server configured for CGI, nothing Python-specific. It would surprise me if XAMPP didn't set up a working cgi-bin for your programming pleasure anyway. > *3. Is mod_python required for python cgi? > * No. mod_python is a completely different approach to running Python from the web. Don't use it, it's dead. If you want something similar, use mod_wsgi. ** Come to think of it, you should probably look into WSGI anyway -- you can run WSGI scripts via CGI for the time being, that's simple enough, and switch to something else for production, or for serious development, later on. > Someone Please revert back to me with the solution for the same.I > would be at-most thankful This line is fascinating, -- http://mail.python.org/mailman/listinfo/python-list
Re: Python CGI windows
On 2010-08-13 12:40, Srikanth N wrote: > *2. How do i configure the Server?(If i use WAMP,XAMPP) > * Sorry, I forgot to link you to http://www.editrocket.com/articles/python_apache_windows.html Hope this helps. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On 2010-08-13, Thomas Jollans wrote: > 1-based indexing might seam more intuitive, but in the end, > it's just another thing you have to learn when learning a > language, like "commas make tuples", and somebody studying a > programming language learns it, and gets used to it if they > aren't used to it already. I think the main reason zero-based indexing is chosen in higher level languages is the following useful property: x[n:m] + x[m:len(x)] == x -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: writing \feff at the begining of a file
Jean-Michel Pichavant wrote: Hello python world, I'm trying to update the content of a $Microsoft$ VC2005 project files using a python application. Since those files are XML data, I assumed I could easily do that. My problem is that VC somehow thinks that the file is corrupted and update the file like the following: - +? Actually, is displayed in a different color by vim, telling me that this is some kind of special caracter code (I'm no familiar with such thing). After googling that, I have a clue : could be some unicode caracter use to indicate something ... well I don't know in fact ("UTF-8 files sometimes start with a byte-order marker (BOM) to indicate that they are encoded in UTF-8."). My problem is however simplier : how do I add such character at the begining of the file ? I tried f = open('paf', w) f.write(u'\ufeff') UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 0: ordinal not in range(128) The error may be explicit but I have no idea how to proceed further. Any clue ? In Python 2 the default encoding is 'ascii'. What you want is 'utf-8'. Use codecs.open() instead, with the 'utf-8-sig' encoding, which will include the BOM. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Fri, 13 Aug 2010 19:14:44 +0200, Thomas Jollans wrote: > "Where it all started" is that 0-based indexing gives languages like C a > very nice property: a[i] and *(a+i) are equivalent in C. From a language > design viewpoint, I think that's quite a strong argument. Languages > based directly on C (C++, Objective C, ...) can't break with this for > obvious reasons, and other language designers/implementers imitated this > behaviour without any good reason to do so, or not to do so. In > higher-level languages, it doesn't really matter. 1-based indexing might > seam more intuitive. > In a higher level language 1-based indexing is just as limiting as 0- based indexing. What you really want is the ability to declare the index range to suit the problem: in Algol 60 it is very useful to be able to declare something like: real sample[-500:750]; and Algol 68 went even further: flex [1:0] int count where the array bounds change dynamically with each assignment to 'count'. Iteration is supported by the lwb and upb operators which return the bounds of an array, so you can write: for i from lwb count to upb count do -- martin@ | Martin Gregorie gregorie. | Essex, UK org | -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6,9 and 20
Martin P. Hellwig wrote: On 08/13/10 10:46, Peter Otten wrote: Martin P. Hellwig wrote: SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION No it wasn't :-) which should be 1*9 + 2*6 What am I missing? Aah interesting, 21 % 9 returns 3 instead of 12, which makes sense of course. I guess the algorithm has to be adapted in a way that if the value is bigger or equal twice the size of the modulo value you need to iterate over it, something like: for minus_multiplier in range(1, int(number, modulo_value)+2): number = number - (modulo_value * minus_multiplier) do the rest of the loop Probably another ten lines or so to make it working as it should I don't understand what you're trying to do. My solution would be: def can_buy(nuggets): for packs_20 in range(nuggets // 20, -1, -1): remaining_20 = nuggets - 20 * packs_20 for packs_9 in range(remaining_20 // 9, -1, -1): remaining_9 = remaining_20 - 9 * packs_9 if remaining_9 % 6 == 0: packs_6 = remaining_9 // 6 return [packs_6, packs_9, packs_20] return [] -- http://mail.python.org/mailman/listinfo/python-list
Re: writing \feff at the begining of a file
On Fri, 13 Aug 2010 11:45:28 +0200, Jean-Michel Pichavant wrote: > I'm trying to update the content of a $Microsoft$ VC2005 project files > using a python application. > Since those files are XML data, I assumed I could easily do that. > > My problem is that VC somehow thinks that the file is corrupted and > update the file like the following: > > - > +? > > > Actually, is displayed in a different color by vim, telling me > that this is some kind of special caracter code (I'm no familiar with > such thing). U+FEFF is a "byte order mark" or BOM. Each Unicode-based encoding (UTF-8, UTF-16, UTF-16-LE, etc) will encode it differently, so it enables a program reading the file to determine the encoding before reading any actual data. > My problem is however simplier : how do I add such character at the > begining of the file ? > I tried Either: 1. Open the file as binary and write '\xef\xbb\xbf' to the file: f = open('foo.txt', 'wb') f.write('\xef\xbb\xbf') [You can also use the constant BOM_UTF8 from the codecs module.] 2. Open the file as utf-8 and write u'\ufeff' to the file: import codecs f = codecs.open('foo.txt', 'w', 'utf-8') f.write(u'\ufeff') 3. Open the file as utf-8-sig and don't write anything (or write an empty string): import codecs f = codecs.open('foo.txt', 'w', 'utf-8-sig') f.write('') The utf-8-sig codec automatically writes a BOM at the beginning of the file. It is present in Python 2.5 and later. -- http://mail.python.org/mailman/listinfo/python-list
Re: text to DB
Praveen wrote: I have a text file in this format PRA 1:13 2:20 3:5 SRA 1:45 2:75 3:9 TRA 1:2 2:65 3:45 pattern is- Book Chapter:Verses now i have my DB schema like this book_id chapter_id versed_id 1 1 13 1 2 20 1 3 5 2 1 45 2 2 75 2 3 9 3 1 2 3 2 65 3 3 45 I want to write a pyhton script which read the text file and dump to DB could any one give me suggestion Read through the file a line at a time. For the first line the book_id is 1, for the second it's 2, etc. Split each line on whitespace, and then for all but the first entry (which is a name?) split on the colon to get the chapter_id and versed_id. Insert each tuple of (book_id, chapter_id, versed_id) into the DB. You haven't said what type of DB it is, so I can't help you there. Just read the documentation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On 08/10/10 06:36, Bartc wrote: > And if the context is Python, I doubt whether the choice of 0-based over a > 1-based makes that much difference in execution speed. And I doubt anyone cares about execution speed when deciding whether to use 1-based or 0-based array. The reason why you want to choose the alternative that use less conversion to the other system is to simplify the source code. Many common mathematical/physics/economics formulas are expressed much simply if we use 0-based counting: * arithmetic series: - 1-based: s(n) = a + (n - 1) * d - 0-based: s(n) = a + n * d * geometric series: - 1-based: g(n) = a * r**(n - 1) - 0-based: g(n) = a * r**n * equation of motion: - 1-based: x(t) = a + 1/2 * a * (t - 1)**2 - 0-based: x(t) = a + 1/2 * a * t**2 * exponential growth/decay: - 1-based: d(t) = a * e**(k * (t - 1)) - 0-based: d(t) = a * e**(k*t) In fact, most textbooks would already uses 0-based formula for some of these formulas already. Most physics and economic textbooks would show the base 0 variation of the formula, and refers to t=0 as the point in time where the "event" started. I often used this model of thinking for 0-based array indices (and negative indices): -7 -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+---+ | c | h | a | r | l | i | e | +---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 (7) instead of: In short, the choice of 0-based array is of practical purpose, rather than historical purpose. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
Sorry the message gets cuts off by an accidental press of send button. On 08/14/10 04:31, Lie Ryan wrote: > On 08/10/10 06:36, Bartc wrote: >> And if the context is Python, I doubt whether the choice of 0-based over a >> 1-based makes that much difference in execution speed. > > And I doubt anyone cares about execution speed when deciding whether to > use 1-based or 0-based array. The reason why you want to choose the > alternative that use less conversion to the other system is to simplify > the source code. > > Many common mathematical/physics/economics formulas are expressed much > simply if we use 0-based counting: > > * arithmetic series: > - 1-based: s(n) = a + (n - 1) * d > - 0-based: s(n) = a + n * d > * geometric series: > - 1-based: g(n) = a * r**(n - 1) > - 0-based: g(n) = a * r**n > * equation of motion: > - 1-based: x(t) = a + 1/2 * a * (t - 1)**2 > - 0-based: x(t) = a + 1/2 * a * t**2 > * exponential growth/decay: > - 1-based: d(t) = a * e**(k * (t - 1)) > - 0-based: d(t) = a * e**(k*t) > > > In fact, most textbooks would already uses 0-based formula for some of > these formulas already. Most physics and economic textbooks would show > the base 0 variation of the formula, and refers to t=0 as the point in > time where the "event" started. > > I often used this model of thinking for 0-based array indices (and > negative indices): > > -7 -6 -5 -4 -3 -2 -1 > +---+---+---+---+---+---+---+ > | c | h | a | r | l | i | e | > +---+---+---+---+---+---+---+ > 0 1 2 3 4 5 6 (7) > > instead of: > so to repeat, I often use this model of thinking: -7 -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+---+ | c | h | a | r | l | i | e | +---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 (7) instead of: -7 -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+---+ | c | h | a | r | l | i | e | +---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 that is, the indices refers to the "gap" between the array entries. The "gap index" model highlights the naturalness of using 0-based array, negative indices, array slicing, and half-open. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make portable distribution of python 2.6?
On 13 авг, 21:28, Thomas Jollans wrote: > On 2010-08-13 19:00, zaur wrote:> All greetings! > > > How to make portable distribution of python 2.6? > > I don't know, but what you're looking for probably already exists. > > Do you mean "portable" as in portable, i.e. "take this and build it for > your system, it should work if your OS is supported"? Then you can get > source tarballs from python.org > > http://python.org/download/ > > Or do you understand "portable" the way that is fashionable in the > Windows world nowadays for some reason, i.e. "look, Ma, already > installed if you happen to use Microsoft Windows of roughly the right > version!" > > Thenhttp://www.portablepython.com/is exactly where Google would have > lead you had you searched. I want to realize howto build my own portable python in order to use them without installation. I want also to be able install modules (numpy, matplotlib, pyqt, etc...) when it is necessary. This very usefull for teaching python in computer classes. -- http://mail.python.org/mailman/listinfo/python-list
Python Tutorial
Hello, I plan to make a new python tutorial and I'd like to collaborate with someone on it. I'm thinking of a slightly different approach than existing tutorials: the idea is that readers will learn from examples, going from small but complete and useful scripts to larger programs, similar to Django by Example: http://lightbird.net/dbe/ If you are interested and have a few years of experience with Python, drop me an email and we'll discuss this further... -ak -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi News 123, Ok i'm getting closer. I am able to write code that will output values that can be bought in exact quantity (truelist) and values that cannot be bought in exact quantities. For a range up to 29 i get this: true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28] the sixth value that passes the test of having an exact solution is 20 so that would mean that the last number i got that cannot be bought in exact quantity is 19 that doesn't seem quite right, does it? def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True return False truelist=[] falselist=[] for n_nuggets in range(30): result = can_buy(n_nuggets) if result==True: truelist=truelist+[n_nuggets,] else: falselist=falselist+[n_nuggets,] print 'true',truelist print 'false',falselist tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi News 123, Ok i'm getting closer. I am able to write code that will output values that can be bought in exact quantity (truelist) and values that cannot be bought in exact quantities. For a range up to 29 i get this: true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28] the sixth value that passes the test of having an exact solution is 20 so that would mean that the last number i got that cannot be bought in exact quantity is 19 that doesn't seem quite right, does it? def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True return False truelist=[] falselist=[] for n_nuggets in range(30): result = can_buy(n_nuggets) if result==True: truelist=truelist+[n_nuggets,] else: falselist=falselist+[n_nuggets,] print 'true',truelist print 'false',falselist tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: Floating numbers
On 13 août, 17:43, Mark Dickinson wrote: > On Aug 13, 3:03 pm, jmfauth wrote: > > > > > A quick question. > > > I understand how to get these numbers > > > 34.5231263880373081783294677734375 > > > and > > > 47 (from 2**47) > > > and the sign. > > > with the decimal module, but I fail to find this one > > > 4858258098025923 > > > Possible? > > See the float.as_integer_ratio method. > > -- > Mark Thanks. I *stupidely* forget this. jmf -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT)
tormod wrote: On Aug 12, 12:30 pm, Alexander Gattin wrote: Does Windows have anything like LD_LIBRARY_PATH/SHLIB_PATH? Yes and no. Windows uses PATH both for finding execuables and for finding DLLs. So if there's a DLL Windows cannot find, you need to add the folder containing that DLL to your PATH variable. No, isn't that only if I have an actual Oracle client installed (not the instant client)? Whether you use the instant client or an actual Oracle client is not the issue. You may or may not need LD_LIBRARY_PATH either way. When you import cx_Oracle on Linux, it loads a file named cx_Oracle.so which in turn loads two files named libclntsh.so and libnnz10.so. These two files are part of the Oracle client installation. The dynamic loader has a list of directories where it tries to find these files; if they aren't there, then the import of cx_Oracle will fail. In that case, you need to set LD_LIBRARY_PATH to the directory containing them (or talk your sysadmin into adding this directory to the default path. He'd do that by adding the directory to /etc/ld.so.conf and running ldconfig). Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Fri, Aug 13, 2010 at 12:25 PM, Baba wrote: > Hi News 123, > > Ok i'm getting closer. I am able to write code that will output values > that can be bought in exact quantity (truelist) and values that cannot > be bought in exact quantities. > > For a range up to 29 i get this: > true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] > false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, > 28] > > the sixth value that passes the test of having an exact solution is 20 > so that would mean that the last number i got that cannot be bought in > exact quantity is 19 > > that doesn't seem quite right, does it? It's not. You're not just trying to find the sixth value that can be bought in exact quantity, but a sequence of six values that can all be bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not sequential. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get number of files in a particular directory.
On Fri, 13 Aug 2010 07:40:42 -0700, blur959 wrote: > Hi all, I got a problem with my script. Everything looks good so far but > for some reason my os.rename isn't working. Can anyone tell me why? Hope > you guys could help. Thanks. > You have a number of logic flaws in your code. 1st you do not actually need to know how many matching files you have. 2nd you need to rename the file inside the same loop that is splitting your file name (this is why you are failing, your rename loop has the same filename each time around), I knocked up a quick hack loosely based on your original code that will generate the file names for you. it has some stratigic print statements so you can see what is happening (always a good idea when debugging code) I have left the actual re-naming of the files for you to complete, I would also agree with the earlier suggestion that you work through some on line tutorials import os import glob def rename(filelist): #function to add a count to each filenale in a list count=0 for fullname in filelist: count+=1 print "full file path %s" % fullname path,filename=os.path.split(fullname) name,ext=os.path.splitext(filename) print "path: '%s' Name: '%s' Extn: '%s'" % (path,name,ext) newname="%s_%04d.%s" %(name,count,ext) print "New filename: '%s'" % newname # rename filename to newname goes here # dont forget you also need path directory = raw_input("directory? ") ext = raw_input("file extension? ") r = raw_input("replace name") pattern = os.path.join(directory, "*." + ext) matching_files = glob.glob(pattern) rename(matching_files) -- Nothing makes one so vain as being told that one is a sinner. Conscience makes egotists of us all. -- Oscar Wilde -- http://mail.python.org/mailman/listinfo/python-list
struct pointing to another struct?
say i have this definition: 1 typedef struct SDL_Surface { 2 Uint32 flags; /* Read-only */ 3 SDL_PixelFormat *format;/* Read-only */ 4 int w, h; /* Read-only */ 5 Uint16 pitch; /* Read-only */ 6 void *pixels; /* Read-write */ 7 SDL_Rect clip_rect; /* Read-only */ 8 int refcount; /* Read-mostly */ 9 10 /* This structure also contains private fields not shown here */ 11 } SDL_Surface; notice two pointers, format and pixels. say format has this definition. 1 typedef struct { 2 SDL_Palette *palette; 3 Uint8 BitsPerPixel; 4 Uint8 BytesPerPixel; 5 Uint8 Rloss, Gloss, Bloss, Aloss; 6 Uint8 Rshift, Gshift, Bshift, Ashift; 7 Uint32 Rmask, Gmask, Bmask, Amask; 8 Uint32 colorkey; 9 Uint8 alpha; 10 } SDL_PixelFormat; so say i want to create a mock sdl handle and pass it to some library function that requires an sdl handle. (would it even work? would i need to use an SDL_SWSURFACE?) so i make the pixelformat data using struct.pack, and make the surface data using struct.pack, but how do i link the surface data to the pixelformat data? if i just use id() it'll give me the memory address of the "box" for the string and not the string data itself. thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: struct pointing to another struct?
inhahe wrote: > say i have this definition: > >1 typedef struct SDL_Surface { >2 Uint32 flags; /* Read-only */ >3 SDL_PixelFormat *format;/* Read-only */ >4 int w, h; /* Read-only */ >5 Uint16 pitch; /* Read-only */ >6 void *pixels; /* Read-write */ >7 SDL_Rect clip_rect; /* Read-only */ >8 int refcount; /* Read-mostly */ >9 > 10 /* This structure also contains private fields not shown here > */ > 11 } SDL_Surface; > > notice two pointers, format and pixels. > say format has this definition. > > >1 typedef struct { >2 SDL_Palette *palette; >3 Uint8 BitsPerPixel; >4 Uint8 BytesPerPixel; >5 Uint8 Rloss, Gloss, Bloss, Aloss; >6 Uint8 Rshift, Gshift, Bshift, Ashift; >7 Uint32 Rmask, Gmask, Bmask, Amask; >8 Uint32 colorkey; >9 Uint8 alpha; > 10 } SDL_PixelFormat; > > so say i want to create a mock sdl handle and pass it to some library > function that requires an sdl handle. (would it even work? would i > need to use an SDL_SWSURFACE?) > > so i make the pixelformat data using struct.pack, and make the surface > data using struct.pack, but how do i link the surface data to the > pixelformat data? if i just use id() it'll give me the memory address > of the "box" for the string and not the string data itself. thanks. I think you are looking at the wrong module; you need ctypes, not struct. http://docs.python.org/library/ctypes.html Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Roald, What would your solution be if you weren't allowed to 'know' that 120 is an upper limit. Assume you were only allowed to 'know', that you won't find any other amount, which can't be bought A AOON A you found six solutions in a row? I have a rather straightforward solution trying from 0 nuggets on until I found six 'hits' in a row, but would be interested about other idioms. On 08/13/2010 12:38 PM, Roald de Vries wrote: > On Aug 13, 2010, at 12:25 PM, Roald de Vries wrote: >> My previous algorithm was more efficient, but for those who like >> one-liners: >> >> [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) >> for b in range(x/9) for c in range(x/6))][-1] > > OK, I did some real testing now, and there's some small error in the > above. All solutions for all x's are given by: > > [(x, a, b, c) for x in range(120) for a in range(x/20+1) for b in > range(x/9+1) for c in range(x/6+1) if x == a*20+b*9+c*6] > > ... and all non-solutions by: > > [x for x in range(120) if not any(x == a*20+b*9+c*6 for a in > range(x/20+1) for b in range(x/9+1) for c in range(x/6+1))] > > Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: struct pointing to another struct?
On Aug 13, 4:07 pm, Peter Otten <__pete...@web.de> wrote: > inhahe wrote: > > say i have this definition: > > > 1 typedef struct SDL_Surface { > > 2 Uint32 flags; /* Read-only */ > > 3 SDL_PixelFormat *format; /* Read-only */ > > 4 int w, h; /* Read-only */ > > 5 Uint16 pitch; /* Read-only */ > > 6 void *pixels; /* Read-write */ > > 7 SDL_Rect clip_rect; /* Read-only */ > > 8 int refcount; /* Read-mostly */ > > 9 > > 10 /* This structure also contains private fields not shown here > > */ > > 11 } SDL_Surface; > > > notice two pointers, format and pixels. > > say format has this definition. > > > 1 typedef struct { > > 2 SDL_Palette *palette; > > 3 Uint8 BitsPerPixel; > > 4 Uint8 BytesPerPixel; > > 5 Uint8 Rloss, Gloss, Bloss, Aloss; > > 6 Uint8 Rshift, Gshift, Bshift, Ashift; > > 7 Uint32 Rmask, Gmask, Bmask, Amask; > > 8 Uint32 colorkey; > > 9 Uint8 alpha; > > 10 } SDL_PixelFormat; > > > so say i want to create a mock sdl handle and pass it to some library > > function that requires an sdl handle. (would it even work? would i > > need to use an SDL_SWSURFACE?) > > > so i make the pixelformat data using struct.pack, and make the surface > > data using struct.pack, but how do i link the surface data to the > > pixelformat data? if i just use id() it'll give me the memory address > > of the "box" for the string and not the string data itself. thanks. > > I think you are looking at the wrong module; you need ctypes, not struct. > > http://docs.python.org/library/ctypes.html > > Peter can you (or anybody) tell me how to link one c struct to another using ctypes? Thx -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On 8/13/2010 6:25 AM, Roald de Vries wrote: On Aug 12, 2010, at 10:51 PM, John Posner wrote: On 8/12/2010 9:22 AM, Dave Angel wrote: Now you have to find the largest number below 120, which you can easily do with brute force tgt = 120 # thanks, Dave Angel Anytime, but I'm not Dave Angel. Oops -- sorry for the erroneous attribution, Roald. -John -- http://mail.python.org/mailman/listinfo/python-list
Dump logging configuration
Hi all! Sorry for dumb question if it is - I'd tried to google it before but have found nothing. Is there any way to dump current logging configuration for future loading it via fileConfig/dictConfig? -- http://mail.python.org/mailman/listinfo/python-list
Help to convert Number to String
I am trying to count the number of lines in a file and insert into the file but getting the error message "TypeError: must be string or read-only character buffer, not int", Could you please help me how to correct this? here is the code lines1 = sum(1 for line in open('C:/test1.txt')) wfile = open('C:/test1.txt'', 'a') wfile.write(str(lines1).zfill(9)) wfile.close() Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6,9 and 20
On 08/13/2010 10:57 AM, Martin P. Hellwig wrote: > SPOILER ALTER: THIS POST CONTAINS A POSSIBLE SOLUTION > > On 08/12/10 21:41, News123 wrote: > >> On 08/12/2010 09:56 PM, Martin P. Hellwig wrote: >>> On 08/11/10 21:14, Baba wrote: >>> >>> >>> How about rephrasing that question in your mind first, i.e.: >>> >>> For every number that is one higher then the previous one*: >>> If this number is dividable by: >>> 6 or 9 or 20 or any combination of 6, 9, 20 >>> than this number _can_ be bought in an exact number >>> else >>> print this number >>> >> >> you are allowed to mix. >> 15 is neither divisable by 6 nor by nine, but 9 + 6 = 15 > > I was aware of that, thats whhy I wrote: > "or any combination of 6, 9, 20" > >> >> I guess, trying to find the result with divisions and remainders is >> overly complicated. > > Python 2.6.4 (r264:75706, Jul 1 2010, 12:52:41) > [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 > Type "help", "copyright", "credits" or "license" for more information. MODULO_COMBINATIONS = [[20], [9], [6], > ...[20, 9], [20, 6], [9, 20], > ...[9, 6], [6, 20], [6, 9], > ...[20, 9, 6], [20, 6, 9], [9, 20, 6], > ...[9, 6, 20], [6, 20, 9], [6, 9, 20]] def apply_combinations_on(number): > ... tmp = list() > ... for combination in MODULO_COMBINATIONS: > ... remainder = number > ... for modulo_value in combination: > ... if remainder == 0: > ... remainder = None > ... break > ... > ... result = remainder % modulo_value > ... > ... if result == remainder : > ... remainder = None > ... break > ... > ... remainder = result > ... > ... if remainder == 0: > ... tmp.append(str(combination)) > ... return(tmp) > ... print(apply_combinations_on(15)) > ['[9, 6]'] > > What is so over complicated about it? What I meant with complicated is your mathematical assumption about modulos, which are probably not obvious to everybody on the first glance. Saying, that you can find out, whether for integers a,b.c,n the equation n = a*6 + b*9 + c*20 is true by verifying whether n mod 6 == 0 or n mod 9 == 0 or (n mod 6) mod 9 == 0 or (n mod 9) mod 6 == 0 Trial error is not so smart, but much easier to explain to beginners. One can even return a,b,c for verification. Being a little (and incrementally) smart, the search space can then be reduced by some degrees with rather easy to explain and incremental assumptions, For given example the run times are so short, that it's not really an issue. Another advantage of brute force is, that you can return a,b,c and not only say, whether a,b,c exist. This allows simple verification or assertions during debugging and learning. # plain brute force. # def can_buy(n_nuggets): for a in range (n_nuggets): for b in range (n_nuggets): for c in range (n_nuggets): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a + 9*b + 20*c == n_nuggets: return (a,b,c) return () # brute force but reduce the upper limit for each loop by saying, # that one can stop if one a*6 > n or b*9 > n or c*20 >n #-- def can_buy(n_nuggets): for a in range (n_nuggets / 6 + 1): for b in range (n_nuggets / 9 + 1): for c in range (n_nuggets / 20 + 1): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a + 9*b + 20*c == n_nuggets: return (a,b,c) return () # as above code, but try even less in inner loops by # removing what has been taken in outer loop # def can_buy(n_nuggets): for a in range (1, n_nuggets / 6 + 1): left_6 = n)nuggets - a * 6 for b in range (1, left_6 / 9 + 1): left_9 = left_6 - b * 9 for c in range (1, left_9/ 20 + 1): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 6*a+9*b+20*c==n_nuggets: return (a,b,c) return () # as above code, but do less multiplications # in inner loop #--- def can_buy(n_nuggets): for a in range (1, n_nuggets / 6 + 1): left_6 = n)nuggets - a * 6 for b in range (1, left_6 / 9 + 1): left_9 = left_6 - b * 9 for c in range (1, left_9/ 20 + 1): print "trying for %2d: %2d %2d %2d" % (n,a,b,c) if 20*c == left_9: return (a,b,c) return () # as above code, but use modulo in inner loop # -- def can_buy(n_nuggets): for a in range (1, n_nuggets / 6 + 1): left_6 = n)nuggets - a * 6 for b in range (1,
Re: struct pointing to another struct?
inhahe wrote: > On Aug 13, 4:07 pm, Peter Otten <__pete...@web.de> wrote: >> inhahe wrote: >> > say i have this definition: >> >> > 1 typedef struct SDL_Surface { >> > 2 Uint32 flags; /* Read-only */ >> > 3 SDL_PixelFormat *format;/* Read-only */ >> > 4 int w, h; /* Read-only */ >> > 5 Uint16 pitch; /* Read-only */ >> > 6 void *pixels; /* Read-write */ >> > 7 SDL_Rect clip_rect; /* Read-only */ >> > 8 int refcount; /* Read-mostly */ >> > 9 >> > 10 /* This structure also contains private fields not shown here >> > */ >> > 11 } SDL_Surface; >> >> > notice two pointers, format and pixels. >> > say format has this definition. >> >> > 1 typedef struct { >> > 2 SDL_Palette *palette; >> > 3 Uint8 BitsPerPixel; >> > 4 Uint8 BytesPerPixel; >> > 5 Uint8 Rloss, Gloss, Bloss, Aloss; >> > 6 Uint8 Rshift, Gshift, Bshift, Ashift; >> > 7 Uint32 Rmask, Gmask, Bmask, Amask; >> > 8 Uint32 colorkey; >> > 9 Uint8 alpha; >> > 10 } SDL_PixelFormat; >> >> > so say i want to create a mock sdl handle and pass it to some library >> > function that requires an sdl handle. (would it even work? would i >> > need to use an SDL_SWSURFACE?) >> >> > so i make the pixelformat data using struct.pack, and make the surface >> > data using struct.pack, but how do i link the surface data to the >> > pixelformat data? if i just use id() it'll give me the memory address >> > of the "box" for the string and not the string data itself. thanks. >> >> I think you are looking at the wrong module; you need ctypes, not struct. >> >> http://docs.python.org/library/ctypes.html >> >> Peter > > can you (or anybody) tell me how to link one c struct to another using > ctypes? Thx I know it sounds old-fashioned, but the documentation is worth reading. It contains examples for structs, pointers and arrays, e. g. """ >>> from ctypes import * >>> class cell(Structure): ... pass ... >>> cell._fields_ = [("name", c_char_p), ... ("next", POINTER(cell))] >>> """ Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi BAba, On 08/13/2010 09:25 PM, Ian Kelly wrote: > On Fri, Aug 13, 2010 at 12:25 PM, Baba wrote: >> Hi News 123, >> >> Ok i'm getting closer. I am able to write code that will output values >> that can be bought in exact quantity (truelist) and values that cannot >> be bought in exact quantities. >> >> For a range up to 29 i get this: >> true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] >> false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, >> 28] >> >> the sixth value that passes the test of having an exact solution is 20 >> so that would mean that the last number i got that cannot be bought in >> exact quantity is 19 >> >> that doesn't seem quite right, does it? As Thomas says: > > It's not. You're not just trying to find the sixth value that can be > bought in exact quantity, but a sequence of six values that can all be > bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not > sequential. Six True values in a row without a False value n between tells you, that you can stop searching. So you that's what you have to write A piece of code, which fetches true fals values for 0 to e.g. 200 nuggets and stops if you had 6 True values in a row. Think how you do it manually: you can try this even without the can_buy function and plug in th can_buy() function only if you ahve your detection of 6 True values in a row working. test_sequence = "0010011011101110011101" # below I use the enumerate function. # rather useful for going through a list AND having a counter value. # when plugging in your function you can switch back to # for n_nuggets in xramge(200): # perhaps here some initialisation for your searching for i, a_char in enumerat(test_suequence): print "entry %2d (%s) is %s" % (i,a_char,result) result = a_char == '1' # result is now true for a '1' # and false for a '0' # here some code to determine the length of the sequence if sequence_length == 6: print "I found a sequence of 6 and can stop searching" print "my solution is " -- http://mail.python.org/mailman/listinfo/python-list
Re: segfault with small pyqt script
On 08/13/2010 09:11 AM, Gelonida wrote: > Lee, > > On 08/13/2010 12:53 AM, Lee Harr wrote: >> >>> I'm desperate. I'm having a real application, which fails rather often >>> when finishing it. I'm not sure, whether any serious problem could be >>> hidden behind it >>> >>> The script is a pyqt script, which segfaults most of the time on my >>> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. >> >> >> Looks to be a known issue: >> http://www.google.com/search?q=pyqt+segfault+on+exit >> https://launchpad.net/bugs/561303 >> >> The last activity on that bug is almost 2 months ago... >> Hopefully the fix will be distributed soon. > > > > This seems to be the problem. > > > In my case I can workaround the issue by adding one line. > > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > myform = None # THIS IS THE WORK AROUND > print "last" > For more complex multi widget examples it doesn't seem enough to just destroy the main widget. probably I had to recursively assign all widgets / dialogues sub widgets to None. So I'll just try to stay away from this pyqt release and stick with older or newer ones. -- http://mail.python.org/mailman/listinfo/python-list
Re: shelf-like list?
On Aug 12, 1:37 pm, Thomas Jollans wrote: > On Tuesday 10 August 2010, it occurred to kj to exclaim: > > > I'm looking for a module that implements "persistent lists": objects > > that behave like lists except that all their elements are stored > > on disk. IOW, the equivalent of "shelves", but for lists rather > > than a dictionaries. . . . > You could simply use pickle to save the data every once in a while. That is a very reasonable solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: segfault with small pyqt script
On 08/13/2010 09:11 AM, Gelonida wrote: > Lee, > > On 08/13/2010 12:53 AM, Lee Harr wrote: >> >>> I'm desperate. I'm having a real application, which fails rather often >>> when finishing it. I'm not sure, whether any serious problem could be >>> hidden behind it >>> >>> The script is a pyqt script, which segfaults most of the time on my >>> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why. >> >> >> Looks to be a known issue: >> http://www.google.com/search?q=pyqt+segfault+on+exit >> https://launchpad.net/bugs/561303 >> >> The last activity on that bug is almost 2 months ago... >> Hopefully the fix will be distributed soon. > > > > This seems to be the problem. > > > In my case I can workaround the issue by adding one line. > > if __name__ == "__main__": > app = QApplication([]) > myform = MyForm() > myform.show() > retcode = app.exec_() > myform = None # THIS IS THE WORK AROUND > print "last" > For more complex multi widget examples it doesn't seem enough to just destroy the main widget. probably I had to recursively assign all widgets / dialogues sub widgets to None. So I'll just try to stay away from this pyqt release and stick with older or newer ones. -- http://mail.python.org/mailman/listinfo/python-list
math symbols in unicode (grouped by purpose)
some collection of math symbols in unicode. • Math Symbols in Unicode http://xahlee.org/comp/unicode_math_operators.html • Arrows in Unicode http://xahlee.org/comp/unicode_arrows.html • Matching Brackets in Unicode http://xahlee.org/comp/unicode_matching_brackets.html these are grouped by the symbol's purpose as much as possible. i made them because i can't find unicode symbols grouped by purpose elsewhere. The unicode “plane -> block” structure does not group symbols well, because the chars are added throughout the decades. Some symbols get added in one block, but later on related symbols get added elsewhere. For example, binary relational symbols are scattered in different unicode blocks. Same for binary operators, or all symbols used for set theory, etc. Sometimes a symbol has multiple uses in different math fields, so which block it gets added into unicode is not well defined. hope it's useful to some one. Xah ∑ http://xahlee.org/ ☄ -- http://mail.python.org/mailman/listinfo/python-list
Re: Floating numbers
In article <595969e7-354f-456d-82b5-6aeafbabe...@d8g2000yqf.googlegroups.com>, Mark Dickinson wrote: > > - If you *really* need a number that represents the *exact* value >34.52, then use the decimal module, or perhaps consider using a simple >home-brewed fixed-point representation. Don't use a home-brew fixed-point, rely on Uncle Tim! http://pythoncraft.com/FixedPoint.py -- Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On 8/13/2010 11:27 AM, Den wrote: I smile every time I see the non-nonsensical sentence "The first thing, therefore, is in thing[0]" in a programming language learning book or tutorial. I laugh every time I hear someone defend that as common sense. If one thinks in terms of slicing at gap positions, the 'proper' indexes would range from 0.5 (average of 0 and 1) to n-0.5. For convenience, we round down or up. To put it another way, seq[n:n+1] is abbreviated as either seq[n] or seq[n+1]. Put this way, the first choice is at least as sensible as the second. Given that Python allows indexing from both end, I prefer 0,1,2,... and -1,-2,-3,... to 1,2,3... and 0,-1,-2,... or 1,2,3,... and -1,-2,-3. As someone else pointed out, discretizing a continuous variable starting at 0 gives 0,1,2,... so having indexes that match is handy. If a problem is formulated in terms of 1,2,3, one can simply leave the first cell blank rather than reformulate. If a problem is formulated in terms of 0,1,2,... and indexes are 1 based, then one must reformulate. Every three year old watching Sesame Street knows counting things starts with '1', not '0'. And that is the same mistake that most societies make, the mistake that put a lid on Greak math, science, and finance. All fresh counts begin with 0. Counting by people usually begins with a silent 0, just as fresh tallies begin with a blank stick or paper. But not always. For instance, lets count the people who have, up to noe, become billionaires with Python. We start with an overt 0. Now we can discuss whether the founders of Google should increase that to 2. Mechanical counting requires an overt 0. A car odometer starts at 0, not 1 and not . Have you never written a counting program? Starting with n = 1 instead of n = 0 before counting the first item would be a bad bug. There may be loads of reasons for it, but don't throw common sense around as one of them. I won't. Only a few (about 3 or 4) societies included a proper 0 in their number systems. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: EXOR or symmetric difference for the Counter class
On Aug 13, 6:36 am, Steven D'Aprano wrote: > On Thu, 12 Aug 2010 13:20:19 -0700, Paddy wrote: > > I find myself needing to calculate the difference between two Counters > > or multisets or bags. > > Is this collections.Counter from Python 3.1? If so, you should say so, > and if not, you should tell us which Counter class this is. It will save > people (by which I mean *me*) from spending an unrewarding few minutes > trying to import Counter in Python 2.5 and writing up a sarcastic > response ... :) > > > I want those items that are unique to each bag. I know how to calculate > > it: > > > >>> b = Counter(a=1, b=2) > > >>> c = Counter(a=3, b=1) > > >>> diff = (b - c) + (c - b) > > >>> (b - c) > > Counter({'b': 1}) > > >>> (c - b) > > Counter({'a': 2}) > > >>> diff > > Counter({'a': 2, 'b': 1}) > > > But thought why doesn't this operation appear already as a method of the > > class? > > Don't know. Perhaps you should put in a feature request. > > -- > Steven Yes it is Counter in both 3.1 and 2.7 (And somewhere on Activestate too). Before I put in a feature request, I wanted to know if other have seen the need. -- http://mail.python.org/mailman/listinfo/python-list
Re: writing \feff at the begining of a file
A short background to MRAB's answer which I will try to get right. The byte-order-mark was invented for UTF-16 encodings so the reader could determine whether the pairs of bytes are in little or big endiean order, depending on whether the first two bute are fe and ff or ff and fe (or maybe vice versa, does not matter here). The concept is meaningless for utf-8 which consists only of bytes in a defined order. This is part of the Unicode standard. However, Microsoft (or whoever) re-purposed (hijacked) that pair of bytes to serve as a non-standard indicator of utf-8 versus any non-unicode encoding. The result is a corrupted utf-8 stream that python accommodates with the utf-8-sig(nature) codec (versus the standard utf-8 codec). -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie wrote: > In a higher level language 1-based indexing is just as limiting as 0- > based indexing. What you really want is the ability to declare the index > range to suit the problem: in Algol 60 it is very useful to be able to > declare something like: > > real sample[-500:750]; Ugh, no. The ability to change the minimum index is evil. I don't much care whether a high-level language uses 0-based or 1-based indexing, but I do care that it is consistent. On the occasions when I am forced to use Visual Basic, the single biggest wart that drives me up a wall is constantly having to figure out whether the particular thing that I am currently indexing is 0-based or 1-based. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Help to convert Number to String
Hi Vamsi, On 2010-08-13 22:50, Vamsi wrote: > I am trying to count the number of lines in a file and insert into > the file but getting the error message "TypeError: must be string or > read-only character buffer, not int", Could you please help me how to > correct this? Which Python version do you use? For which statement exactly do you get the message? > here is the code > > lines1 = sum(1 for line in open('C:/test1.txt')) > wfile = open('C:/test1.txt'', 'a') You have two quotes here after the filename. These give a SyntaxError here. Python sees two concatenated strings, "C:/test1.txt" and ", " and stumbles over the a immediately after the closing quote of the second string. > wfile.write(str(lines1).zfill(9)) > wfile.close() If I remove the redundant quote character and substitute filenames appropriate for my system, everything works. Maybe the code you included in this post isn't the same which led to the error? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Simple Python Sandbox
Howdy-ho. So, I'm working on a project which embeds Python into a bigger system to provide extensibility. In this project, there's basically two types of people who will be entering python code. The trusted folks, who write code which are in files, and which can do anything. The untrusted folks, who are writing very simple chunks of code which can only do limited things. This latter group we want to sandbox as good as possible. Now, I know that its not possible to perfectly sandbox Python, and I know certain things will never be perfectly safe (like someone doing some crazy [0] * 10 * 10 and similar things). That's OK. For this sandbox, we're killing import, execfile, open, eval, reload in __builtin__. This all works well. However in previous discussions, I learned about: >>> [b for b in (1).__class__.__bases__[0].__class__.__subclasses__((1).__class__.__bases__[0]) if b.__name__ == 'file'][0]('../blahblah', 'w').write("Hi!") >>> ^D ixokai$ more ../blahblah Hi! And things like that. (The above may not be the most efficient way to do it). So, I had an idea: why not just do some simple sanitization. When input comes in, just directly replace __ with DISALLOWED, and add getattr/setattr/delattr to the mix of things we kill out of builtins. This second group of people are doing simple little scripting tasks, and not things that would ever involve needing to access a __method__, not even a normal one like __init__. Most of what they do is me.this or me.that("hi") and such. Occasionally there's a little simple logic, but that's it. Can you think of a way out of such a sandbox? A way to access disallowed stuff, not a way to DOS. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Python Sandbox
On Fri, Aug 13, 2010 at 4:37 PM, Stephen Hansen wrote: > Howdy-ho. > > So, I'm working on a project which embeds Python into a bigger system to > provide extensibility. In this project, there's basically two types of > people who will be entering python code. > > The trusted folks, who write code which are in files, and which can do > anything. > > The untrusted folks, who are writing very simple chunks of code which > can only do limited things. > > This latter group we want to sandbox as good as possible. Now, I know > that its not possible to perfectly sandbox Python, and I know certain > things will never be perfectly safe (like someone doing some crazy [0] * > 10 * 10 and similar things). That's OK. > > For this sandbox, we're killing import, execfile, open, eval, reload in > __builtin__. This all works well. However in previous discussions, I > learned about: > [b for b in > (1).__class__.__bases__[0].__class__.__subclasses__((1).__class__.__bases__[0]) > if b.__name__ == 'file'][0]('../blahblah', 'w').write("Hi!") ^D > ixokai$ more ../blahblah > Hi! > > And things like that. (The above may not be the most efficient way to do > it). So, I had an idea: why not just do some simple sanitization. When > input comes in, just directly replace __ with DISALLOWED, and add > getattr/setattr/delattr to the mix of things we kill out of builtins. > > This second group of people are doing simple little scripting tasks, and > not things that would ever involve needing to access a __method__, not > even a normal one like __init__. Most of what they do is me.this or > me.that("hi") and such. Occasionally there's a little simple logic, but > that's it. > > Can you think of a way out of such a sandbox? A way to access disallowed > stuff, not a way to DOS. You may want to check out repy- they use it in the Seattle restricted execution environment, and some pretty smart people claim it has decent security properties. Here's a summary of some of the things they don't allow: https://seattle.cs.washington.edu/wiki/PythonVsRepy Full disclosure: while I don't directly work on the repy environment, I have worked on some other parts of the Seattle project. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Python Sandbox
On 8/13/10 4:57 PM, geremy condra wrote: > You may want to check out repy- they use it in the Seattle restricted > execution environment, and some pretty smart people claim it has > decent security properties. Here's a summary of some of the things > they don't allow: > > https://seattle.cs.washington.edu/wiki/PythonVsRepy Thanks, I'll look at it. However, its essential we have a fully capable and powered Python for the first-class of people. They're not sandboxed at all. However, I'll check out what they've done for inspiration. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Help to convert Number to String
On Fri, 13 Aug 2010 13:50:48 -0700, Vamsi wrote: > I am trying to count the number of lines in a file and insert into the > file but getting the error message "TypeError: must be string or > read-only character buffer, not int", Could you please help me how to > correct this? > > > here is the code > > lines1 = sum(1 for line in open('C:/test1.txt')) > wfile = open('C:/test1.txt'', 'a') > wfile.write(str(lines1).zfill(9)) > wfile.close() No, that ISN'T the code you are using. Don't re-type the code (introducing syntax errors), but copy and paste WORKING code. Also you need to copy and paste the EXACT error message you get, not just paraphrasing it. When I correct the obvious errors in your code above, it works for me: >>> f = open('test', 'w') >>> f.write('hello\nworld\n') 12 >>> f.close() >>> lines1 = sum(1 for line in open('test')) >>> wfile = open('test', 'a') >>> wfile.write(str(lines1).zfill(9)) 9 >>> wfile.close() and the file is correctly updated: >>> open('test').read() 'hello\nworld\n2' -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: writing \feff at the begining of a file
On Fri, 13 Aug 2010 18:25:46 -0400, Terry Reedy wrote: > A short background to MRAB's answer which I will try to get right. > > The byte-order-mark was invented for UTF-16 encodings so the reader > could determine whether the pairs of bytes are in little or big endiean > order, depending on whether the first two bute are fe and ff or ff and > fe (or maybe vice versa, does not matter here). The concept is > meaningless for utf-8 which consists only of bytes in a defined order. > This is part of the Unicode standard. > > However, Microsoft (or whoever) re-purposed (hijacked) that pair of > bytes to serve as a non-standard indicator of utf-8 versus any > non-unicode encoding. The result is a corrupted utf-8 stream that python > accommodates with the utf-8-sig(nature) codec (versus the standard utf-8 > codec). Is there a standard way to autodetect the encoding of a text file? I do this: Open the file in binary mode; if the first three bytes are codecs.BOM_UTF8, then it's a Microsoft UTF-8 text file; otherwise if the first two byes are codecs.BOM_BE or codecs.BOM_LE, the encoding is utf-16- be or utf-16-le respectively. (I don't bother to check for other BOMs, such as for utf-32. There are *lots* of them, but in my experience the encodings are rarely used, and the BOMs aren't defined in the codecs module, so I don't bother to support them.) If there's no BOM, then re-open the file and read the first two lines. If either of them match this regex 'coding[=:]\s*([-\w.]+)' then I take the encoding name from that. This matches Python's behaviour, and supports EMACS and vi encoding declarations. Otherwise, there is no declared encoding, and I use whatever encoding I like (whatever was specified by the user or the application default). -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Help to convert Number to String
On Aug 13, 7:27 pm, Stefan Schwarzer wrote: > Hi Vamsi, > > On 2010-08-13 22:50, Vamsi wrote: > > > I am trying to count the number of lines in a file and insert into > > the file but getting the error message "TypeError: must be string or > > read-only character buffer, not int", Could you please help me how to > > correct this? > > Which Python version do you use? > > For which statement exactly do you get the message? > > > here is the code > > > lines1 = sum(1 for line in open('C:/test1.txt')) > > wfile = open('C:/test1.txt'', 'a') > > You have two quotes here after the filename. These give a > SyntaxError here. Python sees two concatenated strings, > "C:/test1.txt" and ", " and stumbles over the a immediately > after the closing quote of the second string. > > > wfile.write(str(lines1).zfill(9)) > > wfile.close() > > If I remove the redundant quote character and substitute > filenames appropriate for my system, everything works. > > Maybe the code you included in this post isn't the same > which led to the error? > > Stefan Thank you Stefan,I pasted only part of the code.I am new to Python and using 2.7.My actual code is as below, If I run the below code I am getting the error "TypeError: 'str' object is not callable" ,Now I found that I am using the "str" variable which is a function.Thanks a lot for your help. fileopen = open('C:/MPython/test.txt', 'r') str = fileopen.read() print str fileopen.close() lines1 = sum(1 for line in open('C:/MPython/test.txt')) wfile = open('C:/MPython/test.txt', 'a') wfile.write("\n") wfile.write(str(lines1).zfill(9)) wfile.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Help to convert Number to String
On Aug 13, 9:06 pm, Steven D'Aprano wrote: > On Fri, 13 Aug 2010 13:50:48 -0700, Vamsi wrote: > > I am trying to count the number of lines in a file and insert into the > > file but getting the error message "TypeError: must be string or > > read-only character buffer, not int", Could you please help me how to > > correct this? > > > here is the code > > > lines1 = sum(1 for line in open('C:/test1.txt')) > > wfile = open('C:/test1.txt'', 'a') > > wfile.write(str(lines1).zfill(9)) > > wfile.close() > > No, that ISN'T the code you are using. > > Don't re-type the code (introducing syntax errors), but copy and paste > WORKING code. Also you need to copy and paste the EXACT error message you > get, not just paraphrasing it. > > When I correct the obvious errors in your code above, it works for me: > > > > >>> f = open('test', 'w') > >>> f.write('hello\nworld\n') > 12 > >>> f.close() > >>> lines1 = sum(1 for line in open('test')) > >>> wfile = open('test', 'a') > >>> wfile.write(str(lines1).zfill(9)) > 9 > >>> wfile.close() > > and the file is correctly updated: > > >>> open('test').read() > > 'hello\nworld\n2' > > -- > Steven Thank you Steve for your response. I pasted only part of the code.I am new to Python and using 2.7.My actual code is as below, If I run the below code I am getting the error "TypeError: 'str' object is not callable" ,Now I found that I am using the "str" variable which is a function.Thanks a lot for your help. fileopen = open('C:/MPython/test.txt', 'r') str = fileopen.read() print str fileopen.close() lines1 = sum(1 for line in open('C:/MPython/test.txt')) wfile = open('C:/MPython/test.txt', 'a') wfile.write("\n") wfile.write(str(lines1).zfill(9)) wfile.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Python Sandbox
On Fri, 13 Aug 2010 16:37:40 -0700, Stephen Hansen wrote: > Howdy-ho. > > So, I'm working on a project which embeds Python into a bigger system to > provide extensibility. In this project, there's basically two types of > people who will be entering python code. > > The trusted folks, who write code which are in files, and which can do > anything. > > The untrusted folks, who are writing very simple chunks of code which > can only do limited things. I suggest that if the untrusted code is only supposed to be simple and limited, you would be best off to write your own "mini-language" using Python syntax. E.g. if the untrusted users are only going to write code that does (say) simple arithmetic, then why give them the ability to create closures, use generator expressions, connect to web servers, etc? You might think that it's a lot of work to write a mini-language, even with the tools in the standard library, and it is. But it will probably be less work than securing Python :) The fact is that Python is not designed to be used by untrusted users, and it is REALLY hard to keep it in a sandbox. There was an attempt to sandbox Python, if I recall correctly it was the bastion module, but it turned out to be so leaky that it was removed from the standard library with extreme prejudice. Since then, others have been working on it, including Google, but I don't know how successful they've been. Here's an example... suppose you wish to allow reading files, but not writing them. Sounds simple? http://tav.espians.com/a-challenge-to-break-python-security.html Now, I'm not suggesting that the exploits there are directly applicable to your sandbox, but they give a small idea of the sorts of things you need to consider. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Help to convert Number to String
Vamsi writes: > fileopen = open('C:/MPython/test.txt', 'r') > str = fileopen.read() The above statement clobbers the existing binding of ‘str’ to the built-in string type. From that point on, the built-in string type is no longer accessible by the name ‘str’; that name accesses a different object. Choose a better name for the return value; make it describe what the value is for in the context of the program. in_file = open('C:/MPython/test.txt', 'r') in_file_content = in_file.read() print in_file_content in_file.close() # … It also has the advantage of making your code more readable, since the names help indicate *why* the code is written the way it is. -- \ “Creativity can be a social contribution, but only in so far as | `\society is free to use the results.” —Richard Stallman | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
minidom help -- line number
Hi All, I am writing a little program that reads the minidom tree built from an xml file. I would like to print out the line number of the xml file on the parts of the tree that are not valid. But I do not seem to find a way to correspond minidom nodes to line numbers. Can anyone give me some help? Thanks, gz -- http://mail.python.org/mailman/listinfo/python-list