Q_CreationDate,Title,Question,Answer,Score,Is_accepted,N_answers,Q_Id 2008-08-05 22:26:00.797,Create a directly-executable cross-platform GUI app using Python,"Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?","I'm not sure that this is the best way to do it, but when I'm deploying Ruby GUI apps (not Python, but has the same ""problem"" as far as .exe's are concerned) on Windows, I just write a short launcher in C# that calls on my main script. It compiles to an executable, and I then have an application executable.",0.1249325528793103,False,2,0 2008-08-05 22:26:00.797,Create a directly-executable cross-platform GUI app using Python,"Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?","Since python is installed on nearly every non-Windows OS by default now, the only thing you really need to make sure of is that all of the non-standard libraries you use are installed. Having said that, it is possible to build executables that include the python interpreter, and any libraries you use. This is likely to create a large executable, however. MacOS X even includes support in the Xcode IDE for creating full standalone GUI apps. These can be run by any user running OS X.",0.1861857744855677,False,2,0 2008-08-22 10:51:19.057,"How do content discovery engines, like Zemanta and Open Calais work?","I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against? How would a service like Zemanta know what images to suggest to a piece of text for instance?","Open Calais probably use language parsing technology and language statics to guess which words or phrases are Names, Places, Companies, etc. Then, it is just another step to do some kind of search for those entities and return meta data. Zementa probably does something similar, but matches the phrases against meta-data attached to images in order to acquire related results. It certainly isn't easy.",0.0,False,1,1 2008-08-22 15:34:13.760,How to download a file over HTTP?,"I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes. The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows .bat file to download the actual MP3 file. I would prefer to have the entire utility written in Python. I struggled to find a way to actually download the file in Python, thus why I resorted to using wget. So, how do I download the file using Python?","Following are the most commonly used calls for downloading files in python: urllib.urlretrieve ('url_to_file', file_name) urllib2.urlopen('url_to_file') requests.get(url) wget.download('url', file_name) Note: urlopen and urlretrieve are found to perform relatively bad with downloading large files (size > 500 MB). requests.get stores the file in-memory until download is complete.",0.2934554576941812,False,1,2 2008-08-29 04:59:31.200,Find out how much memory is being used by an object in Python,"How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.","For big objects you may use a somewhat crude but effective method: check how much memory your Python process occupies in the system, then delete the object and compare. This method has many drawbacks but it will give you a very fast estimate for very big objects.",0.1618299653758019,False,1,3 2008-09-04 13:36:46.917,Modulus operation with negatives values - weird thing?,"Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.","Your Python interpreter is correct. One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus − 1). e.g.: 13 mod 5 = (13 − 5) mod 5 = (13 − 10) mod 5 = 3 or in your case: −2 mod 5 = (−2 + 5) mod 5 = 3",0.4431875092007125,False,6,4 2008-09-04 13:36:46.917,Modulus operation with negatives values - weird thing?,"Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.","There seems to be a common confusion between the terms ""modulo"" and ""remainder"". In math, a remainder should always be defined consistent with the quotient, so that if a / b == c rem d then (c * b) + d == a. Depending on how you round your quotient, you get different remainders. However, modulo should always give a result 0 <= r < divisor, which is only consistent with round-to-minus-infinity division if you allow negative integers. If division rounds towards zero (which is common), modulo and remainder are only equivalent for non-negative values. Some languages (notably C and C++) don't define the required rounding/remainder behaviours and % is ambiguous. Many define rounding as towards zero, yet use the term modulo where remainder would be more correct. Python is relatively unusual in that it rounds to negative infinity, so modulo and remainder are equivalent. Ada rounds towards zero IIRC, but has both mod and rem operators. The C policy is intended to allow compilers to choose the most efficient implementation for the machine, but IMO is a false optimisation, at least these days. A good compiler will probably be able to use the equivalence for optimisation wherever a negative number cannot occur (and almost certainly if you use unsigned types). On the other hand, where negative numbers can occur, you almost certainly care about the details - for portability reasons you have to use very carefully designed overcomplex algorithms and/or checks to ensure that you get the results you want irrespective of the rounding and remainder behaviour. In other words, the gain for this ""optimisation"" is mostly (if not always) an illusion, whereas there are very real costs in some cases - so it's a false optimisation.",0.0,False,6,4 2008-09-04 13:36:46.917,Modulus operation with negatives values - weird thing?,"Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.","The result depends on the language. Python returns the sign of the divisor, where for example c# returns the sign of the dividend (ie. -2 % 5 returns -2 in c#).",0.0,False,6,4 2008-09-04 13:36:46.917,Modulus operation with negatives values - weird thing?,"Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.","Well, 0 % 5 should be 0, right? -1 % 5 should be 4 because that's the next allowed digit going in the reverse direction (i.e., it can't be 5, since that's out of range). And following along by that logic, -2 must be 3. The easiest way to think of how it will work is that you keep adding or subtracting 5 until the number falls between 0 (inclusive) and 5 (exclusive). I'm not sure about machine dependence - I've never seen an implementation that was, but I can't say it's never done.",0.1352210990936997,False,6,4 2008-09-04 13:36:46.917,Modulus operation with negatives values - weird thing?,"Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.","By the way: most programming languages would disagree with Python and give the result -2. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of a and b is the (strictly positive) rest r of the division of a / b. More precisely, 0 <= r < b by definition.",1.2,True,6,4 2008-09-04 13:36:46.917,Modulus operation with negatives values - weird thing?,"Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.","Well, -2 divided by 5 would be 0 with a remainder of 3. I don't believe that should be very platform dependent, but I've seen stranger things.",0.0,False,6,4 2008-09-15 21:11:30.050,Using boost-python with C++ in Linux,"My development shop has put together a fairly useful Python-based test suite, and we'd like to test some Linux-based C++ code with it. We've gotten the test project they ship with Boost to compile (type 'bjam' in the directory and it works), but we're having issues with our actual project. Building the boost libraries and bjam from source (v1.35.0), when I run bjam I get a .so in the bin/gcc-4.1.2/debug directory. I run python and ""import "" and I get: ImportError: libboost_python-gcc41-d-1_35.so.1.35.0: cannot open shared object file: No such file or directory Looking in the library directory, I have the following: libboost_python-gcc41-mt-1_35.so libboost_python-gcc41-mt-1_35.so.1.35.0 libboost_python-gcc41-mt.so Obviously I need the -d instead of the -mt libraries, or to point at the -mt libraries instead of -d, but I can't figure out how to make my Jamroot file do that. When I install Debian Etch's versions of the libraries, I get ""No Jamfile in /usr/include"" - and there's a debian bug that says they left out the system-level jamfile. I'm more hopeful about getting it working from source, so if anyone has any suggestions to resolve the library issues, I'd like to hear them. Response to answer 1: Thanks for the tip. So, do you know how I'd go about getting it to use the MT libraries instead? It appears to be more of a problem with bjam or the Jamfile I am using thinking I am in debug mode, even though I can't find any flags for that. While I know how to include specific libraries in a call to GCC, I don't see a way to configure that from the Boost end.","Found the solution! Boost builds a debug build by default. Typing ""bjam release"" builds the release configuration. (This isn't listed in any documentation anywhere, as far as I can tell.) Note that this is not the same as changing your build-type to release, as that doesn't build a release configuration. Doing a 'complete' build as Torsten suggests also does not stop it from building only a debug version. It's also worth noting that the -d libraries were in /bin.v2/libs/python/build//debug/ and the release libraries were in /release, and not installed into the top-level 'libs' directory. Thanks for the other suggestions!",0.2655860252697744,False,2,5 2008-09-15 21:11:30.050,Using boost-python with C++ in Linux,"My development shop has put together a fairly useful Python-based test suite, and we'd like to test some Linux-based C++ code with it. We've gotten the test project they ship with Boost to compile (type 'bjam' in the directory and it works), but we're having issues with our actual project. Building the boost libraries and bjam from source (v1.35.0), when I run bjam I get a .so in the bin/gcc-4.1.2/debug directory. I run python and ""import "" and I get: ImportError: libboost_python-gcc41-d-1_35.so.1.35.0: cannot open shared object file: No such file or directory Looking in the library directory, I have the following: libboost_python-gcc41-mt-1_35.so libboost_python-gcc41-mt-1_35.so.1.35.0 libboost_python-gcc41-mt.so Obviously I need the -d instead of the -mt libraries, or to point at the -mt libraries instead of -d, but I can't figure out how to make my Jamroot file do that. When I install Debian Etch's versions of the libraries, I get ""No Jamfile in /usr/include"" - and there's a debian bug that says they left out the system-level jamfile. I'm more hopeful about getting it working from source, so if anyone has any suggestions to resolve the library issues, I'd like to hear them. Response to answer 1: Thanks for the tip. So, do you know how I'd go about getting it to use the MT libraries instead? It appears to be more of a problem with bjam or the Jamfile I am using thinking I am in debug mode, even though I can't find any flags for that. While I know how to include specific libraries in a call to GCC, I don't see a way to configure that from the Boost end.","If you want to build the debug variants of the boost libraries as well, you have to invoke bjam with the option --build-type=complete. On Debian, you get the debug Python interpreter in the python2.x-dbg packages. Debug builds of the Boost libraries are in libboost1.xy-dbg, if you want to use the system Boost.",0.2655860252697744,False,2,5 2008-09-16 07:07:42.550,Can I implement a web user authentication system in python without POST?,"My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible? If it's not, how would you do it with POST? Just out of curiosity. Cheers!","You can actually do it all with GET methods. However, you'll want to use a full challenge response protocol for the logins. (You can hash on the client side using javascript. You just need to send out a unique challenge each time.) You'll also want to use SSL to ensure that no one can see the strings as they go across. In some senses there's no real security difference between GET and POST requests as they both go across in plaintext, in other senses and in practice... GET is are a hell of a lot easier to intercept and is all over most people's logs and your web browser's history. :) (Or as suggested by the other posters, use a different method entirely like HTTP auth, digest auth or some higher level authentication scheme like AD, LDAP, kerberos or shib. However I kinda assumed that if you didn't have POST you wouldn't have these either.)",1.2,True,3,6 2008-09-16 07:07:42.550,Can I implement a web user authentication system in python without POST?,"My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible? If it's not, how would you do it with POST? Just out of curiosity. Cheers!","You could use HTTP Authentication, if supported. You'd have to add SSL, as all methods, POST, GET and HTTP Auth (well, except Digest HHTP authentication) send plaintext. GET is basically just like POST, it just has a limit on the amount of data you can send which is usually a lot smaller than POST and a semantic difference which makes GET not a good candidate from that point of view, even if technically they both can do it. As for examples, what are you using? There are many choices in Python, like the cgi module or some framework like Django, CherryPy, and so on",0.0679224682270276,False,3,6 2008-09-16 07:07:42.550,Can I implement a web user authentication system in python without POST?,"My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible? If it's not, how would you do it with POST? Just out of curiosity. Cheers!","With a bit of JavaScript, you could have the client hash the entered password and a server-generated nonce, and use that in an HTTP GET.",0.0,False,3,6 2008-09-16 09:44:59.477,How to prompt for user input and read command-line arguments,How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?,"Careful not to use the input function, unless you know what you're doing. Unlike raw_input, input will accept any python expression, so it's kinda like eval",0.5691458279783562,False,1,7 2008-09-16 12:46:28.150,Using the docstring from one method to automatically overwrite that of another method,"The problem: I have a class which contains a template method execute which calls another method _execute. Subclasses are supposed to overwrite _execute to implement some specific functionality. This functionality should be documented in the docstring of _execute. Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use execute, so he won't see the correct docstring if he uses help(execute). Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of execute is automatically replaced with that of _execute. Any ideas how this might be done? I was thinking of metaclasses to do this, to make this completely transparent to the user.","Look at the functools.wraps() decorator; it does all of this, but I don't know offhand if you can get it to run in the right context",0.0814518047658113,False,2,8 2008-09-16 12:46:28.150,Using the docstring from one method to automatically overwrite that of another method,"The problem: I have a class which contains a template method execute which calls another method _execute. Subclasses are supposed to overwrite _execute to implement some specific functionality. This functionality should be documented in the docstring of _execute. Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use execute, so he won't see the correct docstring if he uses help(execute). Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of execute is automatically replaced with that of _execute. Any ideas how this might be done? I was thinking of metaclasses to do this, to make this completely transparent to the user.","Well the doc-string is stored in __doc__ so it wouldn't be too hard to re-assign it based on the doc-string of _execute after the fact. Basically: class MyClass(object): def execute(self): '''original doc-string''' self._execute() class SubClass(MyClass): def _execute(self): '''sub-class doc-string''' pass # re-assign doc-string of execute def execute(self,*args,**kw): return MyClass.execute(*args,**kw) execute.__doc__=_execute.__doc__ Execute has to be re-declared to that the doc string gets attached to the version of execute for the SubClass and not for MyClass (which would otherwise interfere with other sub-classes). That's not a very tidy way of doing it, but from the POV of the user of a library it should give the desired result. You could then wrap this up in a meta-class to make it easier for people who are sub-classing.",0.0,False,2,8 2008-09-16 20:11:22.217,Which of these scripting languages is more appropriate for pen-testing?,"First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I have to know how it's made. If I see a Ruby DSL or some Ruby voodoo, I'm hooked on Ruby for a while. Right now I'm working as a Java developer, but plan on taking CEH in the near future. My question is: for tool writing and exploit development, which language do you find to be the most appropriate? Again, I don't want to cause a flame-war or any trouble, I just want honest opinions from scripters that know what they're doing. One more thing: maybe some of you will ask ""Why settle on one language?"". To answer this: I would like to choose only one language, in order to try to master it.","That depends on the implementation, if it will be distributed I would go with Java, seeing as you know that, because of its portability. If it is just for internal use, or will be used in semi-controlled environments, then go with whatever you are the most comfortable maintaining, and whichever has the best long-term outlook. Now to just answer the question, I would go with Perl, but I'm a linux guy so I may be a bit biased in this.",0.1016881243684853,False,7,9 2008-09-16 20:11:22.217,Which of these scripting languages is more appropriate for pen-testing?,"First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I have to know how it's made. If I see a Ruby DSL or some Ruby voodoo, I'm hooked on Ruby for a while. Right now I'm working as a Java developer, but plan on taking CEH in the near future. My question is: for tool writing and exploit development, which language do you find to be the most appropriate? Again, I don't want to cause a flame-war or any trouble, I just want honest opinions from scripters that know what they're doing. One more thing: maybe some of you will ask ""Why settle on one language?"". To answer this: I would like to choose only one language, in order to try to master it.",I'm with tqbf. I've worked with Python and Ruby. Currently I'm working with JRuby. It has all the power of Ruby with access to the Java libraries so if there is something you absolutely need a low-level language to solve you can do so with a high-level language. So far I haven't needed to really use much Java as Ruby has had the ability to do everything I've needed as an API tester.,0.0,False,7,9 2008-09-16 20:11:22.217,Which of these scripting languages is more appropriate for pen-testing?,"First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I have to know how it's made. If I see a Ruby DSL or some Ruby voodoo, I'm hooked on Ruby for a while. Right now I'm working as a Java developer, but plan on taking CEH in the near future. My question is: for tool writing and exploit development, which language do you find to be the most appropriate? Again, I don't want to cause a flame-war or any trouble, I just want honest opinions from scripters that know what they're doing. One more thing: maybe some of you will ask ""Why settle on one language?"". To answer this: I would like to choose only one language, in order to try to master it.","If you plan on using Metasploit for pen-testing and exploit development I would recommend ruby as mentioned previously Metasploit is written in ruby and any exploit/module development you may wish to do will require ruby. If you will be using Immunity CANVAS for pen testing then for the same reasons I would recommend Python as CANVAS is written in python. Also allot of fuzzing frameworks like Peach and Sulley are written in Python. I would not recommend Perl as you will find very little tools/scripts/frameworks related to pen testing/fuzzing/exploits/... in Perl. As your question is ""tool writing and exploit development"" I would recommend Ruby if you choose Metasploit or python if you choose CANVAS. hope that helps :)",0.1016881243684853,False,7,9 2008-09-16 20:11:22.217,Which of these scripting languages is more appropriate for pen-testing?,"First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I have to know how it's made. If I see a Ruby DSL or some Ruby voodoo, I'm hooked on Ruby for a while. Right now I'm working as a Java developer, but plan on taking CEH in the near future. My question is: for tool writing and exploit development, which language do you find to be the most appropriate? Again, I don't want to cause a flame-war or any trouble, I just want honest opinions from scripters that know what they're doing. One more thing: maybe some of you will ask ""Why settle on one language?"". To answer this: I would like to choose only one language, in order to try to master it.","[Disclaimer: I am primarily a Perl programmer, which may be colouring my judgement. However, I am not a particularly tribal one, and I think on this particular question my argument is reasonably objective.] Perl was designed to blend seamlessly into the Unix landscape, and that is why it feels so alien to people with a mainly-OO background (particularly the Java school of OOP). For that reason, though, it’s incredibly widely installed on machines with any kind of Unixoid OS, and many vendor system utilities are written in it. Also for the same reason, servers that have neither Python nor Ruby installed are still likely to have Perl on them, again making it important to have some familiarity with. So if your CEH activity includes extensive activity on Unix, you will have to have some amount of familiarity with Perl anyway, and you might as well focus on it. That said, it is largely a matter of preference. There is not much to differentiate the languages; their expressive power is virtually identical. Some things are a little easier in one of the languages, some a little easier in another. In terms of libraries I do not know how Ruby and Python compare against each other – I do know that Perl has them beat by a margin. Then again, sometimes (particularly when you’re looking for libraries for common needs) the only effect of that is that you get deluged with choices. And if you are only looking to do things in some particular area which is well covered by libraries for Python or Ruby, the mass of other stuff on CPAN isn’t necessarily an advantage. In niche areas, however, it matters, and you never know what unforeseen need you will eventually have (err, by definition). For one-liner use on the command line, Python is kind of a non-starter. In terms of interactive interpreter environment, Perl… uhm… well, you can use the debugger, which is not that great, or you can install one from CPAN, but Perl doesn’t ship a good one itself. So I think Perl does have a very slight edge for your needs in particular, but only just. If you pick Ruby you’ll probably not be much worse off at all. Python might inconvenience you a little more noticeably, but it too is hardly a bad choice.",0.2655860252697744,False,7,9 2008-09-16 20:11:22.217,Which of these scripting languages is more appropriate for pen-testing?,"First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I have to know how it's made. If I see a Ruby DSL or some Ruby voodoo, I'm hooked on Ruby for a while. Right now I'm working as a Java developer, but plan on taking CEH in the near future. My question is: for tool writing and exploit development, which language do you find to be the most appropriate? Again, I don't want to cause a flame-war or any trouble, I just want honest opinions from scripters that know what they're doing. One more thing: maybe some of you will ask ""Why settle on one language?"". To answer this: I would like to choose only one language, in order to try to master it.","If you're looking for a scripting language that will play well with Java, you might want to look at Groovy. It has the flexibility and power of Perl (closures, built in regexes, associative arrays on every corner) but you can access Java code from it thus you have access to a huge number of libraries, and in particular the rest of the system you're developing.",0.0340004944420038,False,7,9 2008-09-16 20:11:22.217,Which of these scripting languages is more appropriate for pen-testing?,"First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I have to know how it's made. If I see a Ruby DSL or some Ruby voodoo, I'm hooked on Ruby for a while. Right now I'm working as a Java developer, but plan on taking CEH in the near future. My question is: for tool writing and exploit development, which language do you find to be the most appropriate? Again, I don't want to cause a flame-war or any trouble, I just want honest opinions from scripters that know what they're doing. One more thing: maybe some of you will ask ""Why settle on one language?"". To answer this: I would like to choose only one language, in order to try to master it.","All of them should be sufficient for that. Unless you need some library that is only available in one language, I'd let personal preference guide me.",0.0340004944420038,False,7,9 2008-09-16 20:11:22.217,Which of these scripting languages is more appropriate for pen-testing?,"First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I have to know how it's made. If I see a Ruby DSL or some Ruby voodoo, I'm hooked on Ruby for a while. Right now I'm working as a Java developer, but plan on taking CEH in the near future. My question is: for tool writing and exploit development, which language do you find to be the most appropriate? Again, I don't want to cause a flame-war or any trouble, I just want honest opinions from scripters that know what they're doing. One more thing: maybe some of you will ask ""Why settle on one language?"". To answer this: I would like to choose only one language, in order to try to master it.","Well, what kind of exploits are you thinking about? If you want to write something that needs low level stuff (ptrace, raw sockets, etc.) then you'll need to learn C. But both Perl and Python can be used. The real question is which one suits your style more? As for toolmaking, Perl has good string-processing abilities, is closer to the system, has good support, but IMHO it's very confusing. I prefer Python: it's a clean, easy to use, easy to learn language with good support (complete language/lib reference, 3rd party libs, etc.). And it's (strictly IMHO) cool.",0.0,False,7,9 2008-09-16 21:05:26.673,"Which is faster, python webpages or php webpages?","Which is faster, python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.","It's about the same. The difference shouldn't be large enough to be the reason to pick one or the other. Don't try to compare them by writing your own tiny benchmarks (""hello world"") because you will probably not have results that are representative of a real web site generating a more complex page.",0.0814518047658113,False,9,10 2008-09-16 21:05:26.673,"Which is faster, python webpages or php webpages?","Which is faster, python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.","If it ain't broke don't fix it. Just write a quick test, but bear in mind that each language will be faster with certain functions then the other.",0.0407936753323291,False,9,10 2008-09-16 21:05:26.673,"Which is faster, python webpages or php webpages?","Which is faster, python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.","I would assume that PHP (>5.5) is faster and more reliable for complex web applications because it is optimized for website scripting. Many of the benchmarks you will find at the net are only made to prove that the favoured language is better. But you can not compare 2 languages with a mathematical task running X-times. For a real benchmark you need two comparable frameworks with hundreds of classes/files an a web application running 100 clients at once.",0.2781854903257024,False,9,10 2008-09-16 21:05:26.673,"Which is faster, python webpages or php webpages?","Which is faster, python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.","You need to be able to make a business case for switching, not just that ""it's faster"". If a site built on technology B costs 20% more in developer time for maintenance over a set period (say, 3 years), it would likely be cheaper to add another webserver to the system running technology A to bridge the performance gap. Just saying ""we should switch to technology B because technology B is faster!"" doesn't really work. Since Python is far less ubiquitous than PHP, I wouldn't be surprised if hosting, developer, and other maintenance costs for it (long term) would have it fit this scenario.",0.0407936753323291,False,9,10 2008-09-16 21:05:26.673,"Which is faster, python webpages or php webpages?","Which is faster, python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.","The only right answer is ""It depends"". There's a lot of variables that can affect the performance, and you can optimize many things in either situation.",0.0,False,9,10 2008-09-16 21:05:26.673,"Which is faster, python webpages or php webpages?","Which is faster, python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.","PHP and Python are similiar enough to not warrent any kind of switching. Any performance improvement you might get from switching from one language to another would be vastly outgunned by simply not spending the money on converting the code (you don't code for free right?) and just buy more hardware.",0.0814518047658113,False,9,10 2008-09-16 21:05:26.673,"Which is faster, python webpages or php webpages?","Which is faster, python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.","There's no point in attempting to convince your employer to port from PHP to Python, especially not for an existing system, which is what I think you implied in your question. The reason for this is that you already have a (presumably) working system, with an existing investment of time and effort (and experience). To discard this in favour of a trivial performance gain (not that I'm claiming there would be one) would be foolish, and no manager worth his salt ought to endorse it. It may also create a problem with maintainability, depending on who else has to work with the system, and their experience with Python.",0.9950547536867304,False,9,10 2008-09-16 21:05:26.673,"Which is faster, python webpages or php webpages?","Which is faster, python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.","an IS organization would not ponder this unless availability was becoming an issue. if so the case, look into replication, load balancing and lots of ram.",0.0407936753323291,False,9,10 2008-09-16 21:05:26.673,"Which is faster, python webpages or php webpages?","Which is faster, python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.","I had to come back to web development at my new job, and, if not Pylons/Python, maybe I would have chosen to live in jungle instead :) In my subjective opinion, PHP is for kindergarten, I did it in my 3rd year of uni and, I believe, many self-respecting (or over-estimating) software engineers will not want to be bothered with PHP code. Why my employers agreed? We (the team) just switched to Python, and they did not have much to say. The website still is and will be PHP, but we are developing other applications, including web, in Python. Advantages of Pylons? You can integrate your python libraries into the web app, and that is, imho, a huge advantage. As for performance, we are still having troubles.",-0.0407936753323291,False,9,10 2008-09-17 17:23:23.030,Search for host with MAC-address using Python,"I'd like to search for a given MAC address on my network, all from within a Python script. I already have a map of all the active IP addresses in the network but I cannot figure out how to glean the MAC address. Any ideas?","You would want to parse the output of 'arp', but the kernel ARP cache will only contain those IP address(es) if those hosts have communicated with the host where the Python script is running. ifconfig can be used to display the MAC addresses of local interfaces, but not those on the LAN.",0.0,False,4,11 2008-09-17 17:23:23.030,Search for host with MAC-address using Python,"I'd like to search for a given MAC address on my network, all from within a Python script. I already have a map of all the active IP addresses in the network but I cannot figure out how to glean the MAC address. Any ideas?","I don't think there is a built in way to get it from Python itself. My question is, how are you getting the IP information from your network? To get it from your local machine you could parse ifconfig (unix) or ipconfig (windows) with little difficulty.",0.0509761841073563,False,4,11 2008-09-17 17:23:23.030,Search for host with MAC-address using Python,"I'd like to search for a given MAC address on my network, all from within a Python script. I already have a map of all the active IP addresses in the network but I cannot figure out how to glean the MAC address. Any ideas?","Depends on your platform. If you're using *nix, you can use the 'arp' command to look up the mac address for a given IP (assuming IPv4) address. If that doesn't work, you could ping the address and then look, or if you have access to the raw network (using BPF or some other mechanism), you could send your own ARP packets (but that is probably overkill).",0.0,False,4,11 2008-09-17 17:23:23.030,Search for host with MAC-address using Python,"I'd like to search for a given MAC address on my network, all from within a Python script. I already have a map of all the active IP addresses in the network but I cannot figure out how to glean the MAC address. Any ideas?","It seems that there is not a native way of doing this with Python. Your best bet would be to parse the output of ""ipconfig /all"" on Windows, or ""ifconfig"" on Linux. Consider using os.popen() with some regexps.",0.0509761841073563,False,4,11 2008-09-17 20:48:45.610,"If it is decided that our system needs an overhaul, what is the best way to go about it?","We are mainting a web application that is built on Classic ASP using VBScript as the primary language. We are in agreement that our backend (framework if you will) is out dated and doesn't provide us with the proper tools to move forward in a quick manner. We have pretty much embraced the current webMVC pattern that is all over the place, and cannot do it, in a reasonable manner, with the current technology. The big missing features are proper dispatching and templating with inheritance, amongst others. Currently there are two paths being discussed: Port the existing application to Classic ASP using JScript, which will allow us to hopefully go from there to .NET MSJscript without too much trouble, and eventually end up on the .NET platform (preferably the MVC stuff will be done by then, ASP.NET isn't much better than were we are on now, in our opinions). This has been argued as the safer path with less risk than the next option, albeit it might take slightly longer. Completely rewrite the application using some other technology, right now the leader of the pack is Python WSGI with a custom framework, ORM, and a good templating solution. There is wiggle room here for even django and other pre-built solutions. This method would hopefully be the quickest solution, as we would probably run a beta beside the actual product, but it does have the potential for a big waste of time if we can't/don't get it right. This does not mean that our logic is gone, as what we have built over the years is fairly stable, as noted just difficult to deal with. It is built on SQL Server 2005 with heavy use of stored procedures and published on IIS 6, just for a little more background. Now, the question. Has anyone taken either of the two paths above? If so, was it successful, how could it have been better, etc. We aren't looking to deviate much from doing one of those two things, but some suggestions or other solutions would potentially be helpful.","It works out better than you'd believe. Recently I did a large reverse-engineering job on a hideous old collection of C code. Function by function I reallocated the features that were still relevant into classes, wrote unit tests for the classes, and built up what looked like a replacement application. It had some of the original ""logic flow"" through the classes, and some classes were poorly designed [Mostly this was because of a subset of the global variables that was too hard to tease apart.] It passed unit tests at the class level and at the overall application level. The legacy source was mostly used as a kind of ""specification in C"" to ferret out the really obscure business rules. Last year, I wrote a project plan for replacing 30-year old COBOL. The customer was leaning toward Java. I prototyped the revised data model in Python using Django as part of the planning effort. I could demo the core transactions before I was done planning. Note: It was quicker to build a the model and admin interface in Django than to plan the project as a whole. Because of the ""we need to use Java"" mentality, the resulting project will be larger and more expensive than finishing the Django demo. With no real value to balance that cost. Also, I did the same basic ""prototype in Django"" for a VB desktop application that needed to become a web application. I built the model in Django, loaded legacy data, and was up and running in a few weeks. I used that working prototype to specify the rest of the conversion effort. Note: I had a working Django implementation (model and admin pages only) that I used to plan the rest of the effort. The best part about doing this kind of prototyping in Django is that you can mess around with the model, unit tests and admin pages until you get it right. Once the model's right, you can spend the rest of your time fiddling around with the user interface until everyone's happy.",0.1352210990936997,False,7,12 2008-09-17 20:48:45.610,"If it is decided that our system needs an overhaul, what is the best way to go about it?","We are mainting a web application that is built on Classic ASP using VBScript as the primary language. We are in agreement that our backend (framework if you will) is out dated and doesn't provide us with the proper tools to move forward in a quick manner. We have pretty much embraced the current webMVC pattern that is all over the place, and cannot do it, in a reasonable manner, with the current technology. The big missing features are proper dispatching and templating with inheritance, amongst others. Currently there are two paths being discussed: Port the existing application to Classic ASP using JScript, which will allow us to hopefully go from there to .NET MSJscript without too much trouble, and eventually end up on the .NET platform (preferably the MVC stuff will be done by then, ASP.NET isn't much better than were we are on now, in our opinions). This has been argued as the safer path with less risk than the next option, albeit it might take slightly longer. Completely rewrite the application using some other technology, right now the leader of the pack is Python WSGI with a custom framework, ORM, and a good templating solution. There is wiggle room here for even django and other pre-built solutions. This method would hopefully be the quickest solution, as we would probably run a beta beside the actual product, but it does have the potential for a big waste of time if we can't/don't get it right. This does not mean that our logic is gone, as what we have built over the years is fairly stable, as noted just difficult to deal with. It is built on SQL Server 2005 with heavy use of stored procedures and published on IIS 6, just for a little more background. Now, the question. Has anyone taken either of the two paths above? If so, was it successful, how could it have been better, etc. We aren't looking to deviate much from doing one of those two things, but some suggestions or other solutions would potentially be helpful.","Use this as an opportunity to remove unused features! Definitely go with the new language. Call it 2.0. It will be a lot less work to rebuild the 80% of it that you really need. Start by wiping your brain clean of the whole application. Sit down with a list of its overall goals, then decide which features are needed based on which ones are used. Then redesign it with those features in mind, and build. (I love to delete code.)",0.1352210990936997,False,7,12 2008-09-17 20:48:45.610,"If it is decided that our system needs an overhaul, what is the best way to go about it?","We are mainting a web application that is built on Classic ASP using VBScript as the primary language. We are in agreement that our backend (framework if you will) is out dated and doesn't provide us with the proper tools to move forward in a quick manner. We have pretty much embraced the current webMVC pattern that is all over the place, and cannot do it, in a reasonable manner, with the current technology. The big missing features are proper dispatching and templating with inheritance, amongst others. Currently there are two paths being discussed: Port the existing application to Classic ASP using JScript, which will allow us to hopefully go from there to .NET MSJscript without too much trouble, and eventually end up on the .NET platform (preferably the MVC stuff will be done by then, ASP.NET isn't much better than were we are on now, in our opinions). This has been argued as the safer path with less risk than the next option, albeit it might take slightly longer. Completely rewrite the application using some other technology, right now the leader of the pack is Python WSGI with a custom framework, ORM, and a good templating solution. There is wiggle room here for even django and other pre-built solutions. This method would hopefully be the quickest solution, as we would probably run a beta beside the actual product, but it does have the potential for a big waste of time if we can't/don't get it right. This does not mean that our logic is gone, as what we have built over the years is fairly stable, as noted just difficult to deal with. It is built on SQL Server 2005 with heavy use of stored procedures and published on IIS 6, just for a little more background. Now, the question. Has anyone taken either of the two paths above? If so, was it successful, how could it have been better, etc. We aren't looking to deviate much from doing one of those two things, but some suggestions or other solutions would potentially be helpful.","Whatever you do, see if you can manage to follow a plan where you do not have to port the application all in one big bang. It is tempting to throw it all away and start from scratch, but if you can manage to do it gradually the mistakes you do will not cost so much and cause so much panic.",0.0904550252145576,False,7,12 2008-09-17 20:48:45.610,"If it is decided that our system needs an overhaul, what is the best way to go about it?","We are mainting a web application that is built on Classic ASP using VBScript as the primary language. We are in agreement that our backend (framework if you will) is out dated and doesn't provide us with the proper tools to move forward in a quick manner. We have pretty much embraced the current webMVC pattern that is all over the place, and cannot do it, in a reasonable manner, with the current technology. The big missing features are proper dispatching and templating with inheritance, amongst others. Currently there are two paths being discussed: Port the existing application to Classic ASP using JScript, which will allow us to hopefully go from there to .NET MSJscript without too much trouble, and eventually end up on the .NET platform (preferably the MVC stuff will be done by then, ASP.NET isn't much better than were we are on now, in our opinions). This has been argued as the safer path with less risk than the next option, albeit it might take slightly longer. Completely rewrite the application using some other technology, right now the leader of the pack is Python WSGI with a custom framework, ORM, and a good templating solution. There is wiggle room here for even django and other pre-built solutions. This method would hopefully be the quickest solution, as we would probably run a beta beside the actual product, but it does have the potential for a big waste of time if we can't/don't get it right. This does not mean that our logic is gone, as what we have built over the years is fairly stable, as noted just difficult to deal with. It is built on SQL Server 2005 with heavy use of stored procedures and published on IIS 6, just for a little more background. Now, the question. Has anyone taken either of the two paths above? If so, was it successful, how could it have been better, etc. We aren't looking to deviate much from doing one of those two things, but some suggestions or other solutions would potentially be helpful.","I would not recommend JScript as that is definitely the road less traveled. ASP.NET MVC is rapidly maturing, and I think that you could begin a migration to it, simultaneously ramping up on the ASP.NET MVC framework as its finalization comes through. Another option would be to use something like ASP.NET w/Subsonic or NHibernate.",0.0,False,7,12 2008-09-17 20:48:45.610,"If it is decided that our system needs an overhaul, what is the best way to go about it?","We are mainting a web application that is built on Classic ASP using VBScript as the primary language. We are in agreement that our backend (framework if you will) is out dated and doesn't provide us with the proper tools to move forward in a quick manner. We have pretty much embraced the current webMVC pattern that is all over the place, and cannot do it, in a reasonable manner, with the current technology. The big missing features are proper dispatching and templating with inheritance, amongst others. Currently there are two paths being discussed: Port the existing application to Classic ASP using JScript, which will allow us to hopefully go from there to .NET MSJscript without too much trouble, and eventually end up on the .NET platform (preferably the MVC stuff will be done by then, ASP.NET isn't much better than were we are on now, in our opinions). This has been argued as the safer path with less risk than the next option, albeit it might take slightly longer. Completely rewrite the application using some other technology, right now the leader of the pack is Python WSGI with a custom framework, ORM, and a good templating solution. There is wiggle room here for even django and other pre-built solutions. This method would hopefully be the quickest solution, as we would probably run a beta beside the actual product, but it does have the potential for a big waste of time if we can't/don't get it right. This does not mean that our logic is gone, as what we have built over the years is fairly stable, as noted just difficult to deal with. It is built on SQL Server 2005 with heavy use of stored procedures and published on IIS 6, just for a little more background. Now, the question. Has anyone taken either of the two paths above? If so, was it successful, how could it have been better, etc. We aren't looking to deviate much from doing one of those two things, but some suggestions or other solutions would potentially be helpful.",Don't try and go 2.0 ( more features then currently exists or scheduled) instead build your new platform with the intent of resolving the current issues with the code base (maintainability/speed/wtf) and go from there.,0.0,False,7,12 2008-09-17 20:48:45.610,"If it is decided that our system needs an overhaul, what is the best way to go about it?","We are mainting a web application that is built on Classic ASP using VBScript as the primary language. We are in agreement that our backend (framework if you will) is out dated and doesn't provide us with the proper tools to move forward in a quick manner. We have pretty much embraced the current webMVC pattern that is all over the place, and cannot do it, in a reasonable manner, with the current technology. The big missing features are proper dispatching and templating with inheritance, amongst others. Currently there are two paths being discussed: Port the existing application to Classic ASP using JScript, which will allow us to hopefully go from there to .NET MSJscript without too much trouble, and eventually end up on the .NET platform (preferably the MVC stuff will be done by then, ASP.NET isn't much better than were we are on now, in our opinions). This has been argued as the safer path with less risk than the next option, albeit it might take slightly longer. Completely rewrite the application using some other technology, right now the leader of the pack is Python WSGI with a custom framework, ORM, and a good templating solution. There is wiggle room here for even django and other pre-built solutions. This method would hopefully be the quickest solution, as we would probably run a beta beside the actual product, but it does have the potential for a big waste of time if we can't/don't get it right. This does not mean that our logic is gone, as what we have built over the years is fairly stable, as noted just difficult to deal with. It is built on SQL Server 2005 with heavy use of stored procedures and published on IIS 6, just for a little more background. Now, the question. Has anyone taken either of the two paths above? If so, was it successful, how could it have been better, etc. We aren't looking to deviate much from doing one of those two things, but some suggestions or other solutions would potentially be helpful.","Half a year ago I took over a large web application (fortunately already in Python) which had some major architectural deficiencies (templates and code mixed, code duplication, you name it...). My plan is to eventually have the system respond to WSGI, but I am not there yet. I found the best way to do it, is in small steps. Over the last 6 month, code reuse has gone up and progress has accelerated. General principles which have worked for me: Throw away code which is not used or commented out Throw away all comments which are not useful Define a layer hierarchy (models, business logic, view/controller logic, display logic, etc.) of your application. This has not to be very clear cut architecture but rather should help you think about the various parts of your application and help you better categorize your code. If something grossly violates this hierarchy, change the offending code. Move the code around, recode it at another place, etc. At the same time adjust the rest of your application to use this code instead of the old one. Throw the old one away if not used anymore. Keep you APIs simple! Progress can be painstakingly slow, but should be worth it.",0.0453204071731508,False,7,12 2008-09-17 20:48:45.610,"If it is decided that our system needs an overhaul, what is the best way to go about it?","We are mainting a web application that is built on Classic ASP using VBScript as the primary language. We are in agreement that our backend (framework if you will) is out dated and doesn't provide us with the proper tools to move forward in a quick manner. We have pretty much embraced the current webMVC pattern that is all over the place, and cannot do it, in a reasonable manner, with the current technology. The big missing features are proper dispatching and templating with inheritance, amongst others. Currently there are two paths being discussed: Port the existing application to Classic ASP using JScript, which will allow us to hopefully go from there to .NET MSJscript without too much trouble, and eventually end up on the .NET platform (preferably the MVC stuff will be done by then, ASP.NET isn't much better than were we are on now, in our opinions). This has been argued as the safer path with less risk than the next option, albeit it might take slightly longer. Completely rewrite the application using some other technology, right now the leader of the pack is Python WSGI with a custom framework, ORM, and a good templating solution. There is wiggle room here for even django and other pre-built solutions. This method would hopefully be the quickest solution, as we would probably run a beta beside the actual product, but it does have the potential for a big waste of time if we can't/don't get it right. This does not mean that our logic is gone, as what we have built over the years is fairly stable, as noted just difficult to deal with. It is built on SQL Server 2005 with heavy use of stored procedures and published on IIS 6, just for a little more background. Now, the question. Has anyone taken either of the two paths above? If so, was it successful, how could it have been better, etc. We aren't looking to deviate much from doing one of those two things, but some suggestions or other solutions would potentially be helpful.",I agree with Michael Pryor and Joel that it's almost always a better idea to continue evolving your existing code base rather than re-writing from scratch. There are typically opportunities to just re-write or re-factor certain components for performance or flexibility.,0.0,False,7,12 2008-09-18 04:04:58.170,"How do I verify that a string only contains letters, numbers, underscores and dashes?",I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.,"You could always use a list comprehension and check the results with all, it would be a little less resource intensive than using a regex: all([c in string.letters + string.digits + [""_"", ""-""] for c in mystring])",-0.0370887312438237,False,1,13 2008-09-18 12:51:07.733,"Python, beyond the basics",I've gotten to grips with the basics of Python and I've got a small holiday which I want to use some of to learn a little more Python. The problem is that I have no idea what to learn or where to start. I'm primarily web development but in this case I don't know how much difference it will make.,"I'd suggest writing a non-trivial webapp using either Django or Pylons, something that does some number crunching. No better way to learn a new language than commiting yourself to a problem and learning as you go!",0.0407936753323291,False,3,14 2008-09-18 12:51:07.733,"Python, beyond the basics",I've gotten to grips with the basics of Python and I've got a small holiday which I want to use some of to learn a little more Python. The problem is that I have no idea what to learn or where to start. I'm primarily web development but in this case I don't know how much difference it will make.,"Search ""Alex Martelli"", ""Alex Martelli patterns"" and ""Thomas Wouters"" on Google video. There's plenty of interesting talks on advanced Python, design patterns in Python, and so on.",0.0407936753323291,False,3,14 2008-09-18 12:51:07.733,"Python, beyond the basics",I've gotten to grips with the basics of Python and I've got a small holiday which I want to use some of to learn a little more Python. The problem is that I have no idea what to learn or where to start. I'm primarily web development but in this case I don't know how much difference it will make.,"The Python Cookbook is absolutely essential if you want to master idiomatic Python. Besides, that's the book that made me fall in love with the language.",0.0814518047658113,False,3,14 2008-09-19 12:47:32.310,Algorithm to detect similar documents in python script,"I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this?","I think Jeremy has hit the nail on the head - if you just want to detect if files are different, a hash algorithm like MD5 or SHA1 is a good way to go. Linus Torvalds' Git source control software uses SHA1 hashing in just this way - to check when files have been modified.",0.0,False,2,15 2008-09-19 12:47:32.310,Algorithm to detect similar documents in python script,"I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this?","You need to make your question more concrete. If you've already read the fingerprinting papers, you already know the principles at work, so describing common approaches here would not be beneficial. If you haven't, you should also check out papers on ""duplicate detection"" and various web spam detection related papers that have come out of Stanford, Google, Yahoo, and MS in recent years. Are you having specific problems with coding the described algorithms? Trouble getting started? The first thing I'd probably do is separate the tokenization (the process of extracting ""words"" or other sensible sequences) from the duplicate detection logic, so that it is easy to plug in different parsers for different languages and keep the duplicate detection piece the same.",0.1218406379589197,False,2,15 2008-09-19 19:53:19.447,"What is ""thread local storage"" in Python, and why do I need it?","In Python specifically, how do variables get shared between threads? Although I have used threading.Thread before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing? I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. Thanks in advance!","I may be wrong here. If you know otherwise please expound as this would help explain why one would need to use thread local(). This statement seems off, not wrong: ""If you want to atomically modify anything that another thread has access to, you have to protect it with a lock."" I think this statement is ->effectively<- right but not entirely accurate. I thought the term ""atomic"" meant that the Python interpreter created a byte-code chunk that left no room for an interrupt signal to the CPU. I thought atomic operations are chunks of Python byte code that does not give access to interrupts. Python statements like ""running = True"" is atomic. You do not need to lock CPU from interrupts in this case (I believe). The Python byte code breakdown is safe from thread interruption. Python code like ""threads_running[5] = True"" is not atomic. There are two chunks of Python byte code here; one to de-reference the list() for an object and another byte code chunk to assign a value to an object, in this case a ""place"" in a list. An interrupt can be raised -->between<- the two byte-code ->chunks<-. That is were bad stuff happens. How does thread local() relate to ""atomic""? This is why the statement seems misdirecting to me. If not can you explain?",0.0679224682270276,False,3,16 2008-09-19 19:53:19.447,"What is ""thread local storage"" in Python, and why do I need it?","In Python specifically, how do variables get shared between threads? Although I have used threading.Thread before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing? I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. Thanks in advance!","Worth mentioning threading.local() is not a singleton. You can use more of them per thread. It is not one storage.",0.0679224682270276,False,3,16 2008-09-19 19:53:19.447,"What is ""thread local storage"" in Python, and why do I need it?","In Python specifically, how do variables get shared between threads? Although I have used threading.Thread before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing? I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. Thanks in advance!","Just like in every other language, every thread in Python has access to the same variables. There's no distinction between the 'main thread' and child threads. One difference with Python is that the Global Interpreter Lock means that only one thread can be running Python code at a time. This isn't much help when it comes to synchronising access, however, as all the usual pre-emption issues still apply, and you have to use threading primitives just like in other languages. It does mean you need to reconsider if you were using threads for performance, however.",0.2012947653214861,False,3,16 2008-09-24 12:21:02.957,Checking for code changes in all imported python modules,"Almost every Python web framework has a simple server that runs a wsgi application and automatically reloads the imported modules every time the source gets changed. I know I can look at the code and see how it's done, but that may take some time and I'm asking just out of curiosity. Does anyone have any idea how this is implemented?","As the author of one of the reloader mechanisms (the one in werkzeug) I can tell you that it doesn't work. What all the reloaders do is forking one time and restarting the child process if a monitor thread notices that one module changed on the file system. Inline reload()ing doesn't work because references to the reloaded module are not updated.",1.2,True,1,17 2008-09-25 21:18:09.800,How do you manage your custom modules?,"I write tons of python scripts, and I find myself reusing lots code that I've written for other projects. My solution has been to make sure the code is separated into logical modules/packages (this one's a given). I then make them setuptools-aware and publish them on PyPI. This allows my other scripts to always have the most up-to-date code, I get a warm fuzzy feeling because I'm not repeating myself, and my development, in general, is made less complicated. I also feel good that there MAY be someone out there that finds my code handy for something they're working on, but it's mainly for selfish reasons :) To all the pythonistas, how do you handle this? Do you use PyPI or setuptools (easy_install)? or something else?","I store it all offline in a logical directory structure, with commonly used modules grouped as utilities. This means it's easier to control which versions I publish, and manage. I also automate the build process to interpret the logical directory structure.",0.0,False,2,18 2008-09-25 21:18:09.800,How do you manage your custom modules?,"I write tons of python scripts, and I find myself reusing lots code that I've written for other projects. My solution has been to make sure the code is separated into logical modules/packages (this one's a given). I then make them setuptools-aware and publish them on PyPI. This allows my other scripts to always have the most up-to-date code, I get a warm fuzzy feeling because I'm not repeating myself, and my development, in general, is made less complicated. I also feel good that there MAY be someone out there that finds my code handy for something they're working on, but it's mainly for selfish reasons :) To all the pythonistas, how do you handle this? Do you use PyPI or setuptools (easy_install)? or something else?","What kind of modules are we talking about here? If you're planning on distributing your projects to other python developers, setuptools is great. But it's usually not a very good way to distribute apps to end users. Your best bet in the latter case is to tailor your packaging to the platforms you're distributing it for. Sure, it's a pain, but it makes life for end users far easier. For example, in my Debian system, I usually don't use easy_install because it is a little bit more difficult to get eggs to work well with the package manager. In OS X and windows, you'd probably want to package everything up using py2app and py2exe respectively. This makes life for the end user better. After all, they shouldn't know or care what language your scripts are written in. They just need them to install.",0.1352210990936997,False,2,18 2008-09-26 12:05:29.377,PyQt - QScrollBar,"Dear Stacktoverflow, can you show me an example of how to use a QScrollBar? Thanks.","It will come down to you using the QScrollArea, it is a widget that implements showing something that is larger than the available space. You will not need to use QScrollBar directly. I don't have a PyQt example but there is a C++ example in the QT distribution it is called the ""Image Viewer"". The object hierarchy will still be the same",1.2,True,1,19 2008-09-26 23:59:47.337,How to make a cross-module variable?,"The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it? The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.","I believe that there are plenty of circumstances in which it does make sense and it simplifies programming to have some globals that are known across several (tightly coupled) modules. In this spirit, I would like to elaborate a bit on the idea of having a module of globals which is imported by those modules which need to reference them. When there is only one such module, I name it ""g"". In it, I assign default values for every variable I intend to treat as global. In each module that uses any of them, I do not use ""from g import var"", as this only results in a local variable which is initialized from g only at the time of the import. I make most references in the form g.var, and the ""g."" serves as a constant reminder that I am dealing with a variable that is potentially accessible to other modules. If the value of such a global variable is to be used frequently in some function in a module, then that function can make a local copy: var = g.var. However, it is important to realize that assignments to var are local, and global g.var cannot be updated without referencing g.var explicitly in an assignment. Note that you can also have multiple such globals modules shared by different subsets of your modules to keep things a little more tightly controlled. The reason I use short names for my globals modules is to avoid cluttering up the code too much with occurrences of them. With only a little experience, they become mnemonic enough with only 1 or 2 characters. It is still possible to make an assignment to, say, g.x when x was not already defined in g, and a different module can then access g.x. However, even though the interpreter permits it, this approach is not so transparent, and I do avoid it. There is still the possibility of accidentally creating a new variable in g as a result of a typo in the variable name for an assignment. Sometimes an examination of dir(g) is useful to discover any surprise names that may have arisen by such accident.",0.7408590612005881,False,2,20 2008-09-26 23:59:47.337,How to make a cross-module variable?,"The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it? The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.","You can already do this with module-level variables. Modules are the same no matter what module they're being imported from. So you can make the variable a module-level variable in whatever module it makes sense to put it in, and access it or assign to it from other modules. It would be better to call a function to set the variable's value, or to make it a property of some singleton object. That way if you end up needing to run some code when the variable's changed, you can do so without breaking your module's external interface. It's not usually a great way to do things — using globals seldom is — but I think this is the cleanest way to do it.",0.1684471436049839,False,2,20 2008-09-30 16:50:38.440,Python GUI Application redistribution,"I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints. What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either? Also, how would I go about packaging everything up in binaries of reasonable size for each target OS? (my main targets are Windows and Mac OS X) Addition: I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx_freeze and getting 30mb+ binaries, and no real advice on how to actually do the packaging and how trust-worthy it is.",I've used py2Exe myself - it's really easy (at least for small apps).,0.0,False,1,21 2008-10-06 21:03:55.827,"Writing a reliable, totally-ordered multicast system in Python","I have to write a reliable, totally-ordered multicast system from scratch in Python. I can't use any external libraries. I'm allowed to use a central sequencer. There seems to be two immediate approaches: write an efficient system, attaching a unique id to each multicasted message, having the sequencer multicast sequence numbers for the message id's it receives, and sending back and forth ACK's and NACK's. write an inefficient flooding system, where each multicaster simply re-sends each message it receives once (unless it was sent by that particular multicaster.) I'm allowed to use the second option, and am inclined to do so. I'm currently multicasting UDP messages (which seems to be the only option,) but that means that some messages might get lost. That means I have to be able to uniquely identify each sent UDP message, so that it can be re-sent according to #2. Should I really generate unique numbers (e.g. using the sender address and a counter) and pack them into each and every UDP message sent? How would I go about doing that? And how do I receive a single UDP message in Python, and not a stream of data (i.e. socket.recv)?","The approach you take is going to depend very much on the nature of the data that you're sending, the scale of your network and the quantity of data you're sending. In particular it is going to depend on the number of targets each of your nodes is connected to. If you're expecting this to scale to a large number of targets for each node and a large quantity of data then you may well find that the overhead of adding an ACK/NAK to every packet is sufficient to adversely limit your throughput, particularly when you add retransmissions into the mix. As Frank Szczerba has said multimedia data has the benefit of being able to recover from lost packets. If you have any control over the data that you're sending you should try to design the payloads so that you minimise the susceptibility to dropped packets. If the data that you're sending cannot tolerate dropped packets and you're trying to scale to high utilisation of your network then perhaps udp is not the best protocol to use. Implementing a series of tcp proxies (where each node retransmits, unicast, to all other connected nodes - similar to your flooding idea) would be a more reliable mechanism. With all of that said, have you considered using true multicast for this application? Just saw the ""homework"" tag... these suggestions might not be appropriate for a homework problem.",0.1352210990936997,False,2,22 2008-10-06 21:03:55.827,"Writing a reliable, totally-ordered multicast system in Python","I have to write a reliable, totally-ordered multicast system from scratch in Python. I can't use any external libraries. I'm allowed to use a central sequencer. There seems to be two immediate approaches: write an efficient system, attaching a unique id to each multicasted message, having the sequencer multicast sequence numbers for the message id's it receives, and sending back and forth ACK's and NACK's. write an inefficient flooding system, where each multicaster simply re-sends each message it receives once (unless it was sent by that particular multicaster.) I'm allowed to use the second option, and am inclined to do so. I'm currently multicasting UDP messages (which seems to be the only option,) but that means that some messages might get lost. That means I have to be able to uniquely identify each sent UDP message, so that it can be re-sent according to #2. Should I really generate unique numbers (e.g. using the sender address and a counter) and pack them into each and every UDP message sent? How would I go about doing that? And how do I receive a single UDP message in Python, and not a stream of data (i.e. socket.recv)?","The flooding approach can cause a bad situation to get worse. If messages are dropped due to high network load, having every node resend every message will only make the situation worse. The best approach to take depends on the nature of the data you are sending. For example: Multimedia data: no retries, a dropped packet is a dropped frame, which won't matter when the next frame gets there anyway. Fixed period data: Recipient node keeps a timer that is reset each time an update is received. If the time expires, it requests the missing update from the master node. Retries can be unicast to the requesting node. If neither of these situations applies (every packet has to be received by every node, and the packet timing is unpredictable, so recipients can't detect missed packets on their own), then your options include: Explicit ACK from every node for each packet. Sender retries (unicast) any packet that is not ACKed. TCP-based grid approach, where each node is manually repeats received packets to neighbor nodes, relying on TCP mechanisms to ensure delivery. You could possibly rely on recipients noticing a missed packet upon reception of one with a later sequence number, but this requires the sender to keep the packet around until at least one additional packet has been sent. Requiring positive ACKs is more reliable (and provable).",1.2,True,2,22 2008-10-07 18:18:48.450,Average difference between dates in Python,"I have a series of datetime objects and would like to calculate the average delta between them. For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes. Any suggestions on how to calculate this using Python?","Since you seem to be throwing out the 20 minute delta between times 1 and 3 in your example, I'd say you should just sort the list of datetimes, add up the deltas between adjacent times, then divide by n-1. Do you have any code you can share with us, so we can help you debug it?",0.1618299653758019,False,2,23 2008-10-07 18:18:48.450,Average difference between dates in Python,"I have a series of datetime objects and would like to calculate the average delta between them. For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes. Any suggestions on how to calculate this using Python?","You can subtract each successive date from the one prior (resulting in a timedelta object which represents the difference in days, seconds). You can then average the timedelta objects to find your answer.",1.2,True,2,23 2008-10-08 06:27:12.350,What is the problem with reduce()?,"There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it. What am I missing? What is the problem with reduce()?","reduce() is not being removed -- it's simply being moved into the functools module. Guido's reasoning is that except for trivial cases like summation, code written using reduce() is usually clearer when written as an accumulation loop.",0.9999992527404032,False,3,24 2008-10-08 06:27:12.350,What is the problem with reduce()?,"There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it. What am I missing? What is the problem with reduce()?","People worry it encourages an obfuscated style of programming, doing something that can be achieved with clearer methods. I'm not against reduce myself, I also find it a useful tool sometimes.",0.6259286199743823,False,3,24 2008-10-08 06:27:12.350,What is the problem with reduce()?,"There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it. What am I missing? What is the problem with reduce()?","The primary reason of reduce's existence is to avoid writing explicit for loops with accumulators. Even though python has some facilities to support the functional style, it is not encouraged. If you like the 'real' and not 'pythonic' functional style - use a modern Lisp (Clojure?) or Haskell instead.",0.3153999413393242,False,3,24 2008-10-08 07:49:01.903,When to use the Python debugger,"Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick. So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use? I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.","In 30 years of programming I've used a debugger exactly 4 times. All four times were to read the core file produced from a C program crashing to locate the traceback information that's buried in there. I don't think debuggers help much, even in compiled languages. Many people like debuggers, there are some reasons for using them, I'm sure, or people wouldn't lavish such love and care on them. Here's the point -- software is knowledge capture. Yes, it does have to run. More importantly, however, software has meaning. This is not an indictment of your use of a debugger. However, I find that the folks who rely on debugging will sometimes produce really odd-looking code and won't have a good justification for what it means. They can only say ""it may be a hack, but it works."" My suggestion on debuggers is ""don't bother"". ""But, what if I'm totally stumped?"" you ask, ""should I learn the debugger then?"" Totally stumped by what? The language? Python's too simple for utter befuddlement. Some library? Perhaps. Here's what you do -- with or without a debugger. You have the source, read it. You write small tests to exercise the library. Using the interactive shell, if possible. [All the really good libraries seem to show their features using the interactive Python mode -- I strive for this level of tight, clear simplicity.] You have the source, add print functions.",0.4961739557460144,False,4,25 2008-10-08 07:49:01.903,When to use the Python debugger,"Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick. So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use? I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.","I find it very useful to drop into a debugger in a failing test case. I add import pdb; pdb.set_trace() just before the failure point of the test. The test runs, building up a potentially quite large context (e.g. importing a database fixture or constructing an HTTP request). When the test reaches the pdb.set_trace() line, it drops into the interactive debugger and I can inspect the context in which the failure occurs with the usual pdb commands looking for clues as to the cause.",0.0679224682270276,False,4,25 2008-10-08 07:49:01.903,When to use the Python debugger,"Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick. So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use? I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.","Any time you want to inspect the contents of variables that may have caused the error. The only way you can do that is to stop execution and take a look at the stack. pydev in Eclipse is a pretty good IDE if you are looking for one.",0.1352210990936997,False,4,25 2008-10-08 07:49:01.903,When to use the Python debugger,"Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick. So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use? I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.","I use pdb for basic python debugging. Some of the situations I use it are: When you have a loop iterating over 100,000 entries and want to break at a specific point, it becomes really helpful.(conditional breaks) Trace the control flow of someone else's code. Its always better to use a debugger than litter the code with prints. Normally there can be more than one point of failures resulting in a bug, all are not obvious in the first look. So you look for obvious places, if nothing is wrong there, you move ahead and add some more prints.. debugger can save you time here, you dont need to add the print and run again.",1.2,True,4,25 2008-10-10 14:52:04.360,Configuring python,"I am new to python and struggling to find how to control the amount of memory a python process can take? I am running python on a Cento OS machine with more than 2 GB of main memory size. Python is taking up only 128mb of this and I want to allocate it more. I tried to search all over the internet on this for last half an hour and found absolutely nothing! Why is it so difficult to find information on python related stuff :( I would be happy if someone could throw some light on how to configure python for various things like allowed memory size, number of threads etc. A link to a site where most controllable parameters of python are described would be appreciated well.","Forget all that, python just allocates more memory as needed, there is not a myriad of comandline arguments for the VM as in java, just let it run. For all comandline switches you can just run python -h or read man python.",1.2,True,2,26 2008-10-10 14:52:04.360,Configuring python,"I am new to python and struggling to find how to control the amount of memory a python process can take? I am running python on a Cento OS machine with more than 2 GB of main memory size. Python is taking up only 128mb of this and I want to allocate it more. I tried to search all over the internet on this for last half an hour and found absolutely nothing! Why is it so difficult to find information on python related stuff :( I would be happy if someone could throw some light on how to configure python for various things like allowed memory size, number of threads etc. A link to a site where most controllable parameters of python are described would be appreciated well.","Are you sure that the machine does not have a 128M process limit? If you are running the python script as a CGI inside a web server, it is quite likely that there is a process limit set - you will need to look at the web server configuration.",0.3869120172231254,False,2,26 2008-10-13 14:26:10.293,Dealing with a string containing multiple character encodings,"I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string: ""^LThis is an example ^Gstring with multiple ^Jcharacter encodings"" Where the different encoding starts and ends is marked using special escape chars: ^L - Latin1 ^E - Central Europe ^T - Turkish ^B - Baltic ^J - Japanese ^C - Cyrillic ^G - Greek And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host. I hope someone can help me with how to get started on this.","I would write a codec that incrementally scanned the string and decoded the bytes as they came along. Essentially, you would have to separate strings into chunks with a consistent encoding and decode those and append them to the strings that followed them.",0.2401167094949473,False,2,27 2008-10-13 14:26:10.293,Dealing with a string containing multiple character encodings,"I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string: ""^LThis is an example ^Gstring with multiple ^Jcharacter encodings"" Where the different encoding starts and ends is marked using special escape chars: ^L - Latin1 ^E - Central Europe ^T - Turkish ^B - Baltic ^J - Japanese ^C - Cyrillic ^G - Greek And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host. I hope someone can help me with how to get started on this.","I don't suppose you have any way of convincing the person who hosts the other machine to switch to unicode? This is one of the reasons Unicode was invented, after all.",0.0814518047658113,False,2,27 2008-10-15 06:59:50.787,Does python support multiprocessor/multicore programming?,"What is the difference between multiprocessor programming and multicore programming? preferably show examples in python how to write a small program for multiprogramming & multicore programming","The main difference is how you organize and distribute data. Multicore typically has higher bandwidths between the different cores in a cpu, and multiprocessor needs to involve the bus between the cpus more. Python 2.6 has gotten multiprocess (process, as in program running) and more synchronization and communication objects for multithreaded programming.",0.0582430451621389,False,1,28 2008-10-16 03:02:27.847,Extracting a parenthesized Python expression from a string,"I've been wondering about how hard it would be to write some Python code to search a string for the index of a substring of the form ${expr}, for example, where expr is meant to be a Python expression or something resembling one. Given such a thing, one could easily imagine going on to check the expression's syntax with compile(), evaluate it against a particular scope with eval(), and perhaps even substitute the result into the original string. People must do very similar things all the time. I could imagine solving such a problem using a third-party parser generator [oof], or by hand-coding some sort of state machine [eek], or perhaps by convincing Python's own parser to do the heavy lifting somehow [hmm]. Maybe there's a third-party templating library somewhere that can be made to do exactly this. Maybe restricting the syntax of expr is likely to be a worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies -- for example, maybe all I really need is something that matches any expr that has balanced curly braces. What's your sense? Update: Thanks very much for your responses so far! Looking back at what I wrote yesterday, I'm not sure I was sufficiently clear about what I'm asking. Template substitution is indeed an interesting problem, and probably much more useful to many more people than the expression extraction subproblem I'm wondering about, but I brought it up only as a simple example of how the answer to my question might be useful in real life. Some other potential applications might include passing the extracted expressions to a syntax highlighter; passing the result to a real Python parser and looking at or monkeying with the parse tree; or using the sequence of extracted expressions to build up a larger Python program, perhaps in conjunction with some information taken from the surrounding text. The ${expr} syntax I mentioned is also intended as an example, and in fact I wonder if I shouldn't have used $(expr) as my example instead, because it makes the potential drawbacks of the obvious approach, along the lines of re.finditer(r'$\{([^}]+)\}', s), a bit easier to see. Python expressions can (and often do) contain the ) (or }) character. It seems possible that handling any of those cases might be much more trouble than it's worth, but I'm not convinced of that yet. Please feel free to try to make this case! Prior to posting this question, I spent quite a bit of time looking at Python template engines hoping that one might expose the sort of low-level functionality I'm asking about -- namely, something that can find expressions in a variety of contexts and tell me where they are rather than being limited to finding expressions embedded using a single hard-coded syntax, always evaluating them, and always substituting the results back into the original string. I haven't figured out how to use any of them to solve my problem yet, but I do very much appreciate the suggestions regarding more to look at (can't believe I missed that wonderful list on the wiki!). The API documentation for these things tends to be pretty high-level, and I'm not too familiar with the internals of any of them, so I'm sure I could use help looking at those and figuring out how to get them to do this sort of thing. Thanks for your patience!","If you want to handle arbitrary expressions like {'{spam': 42}[""spam}""], you can't get away without full-blown parser.",0.1016881243684853,False,1,29 2008-10-17 09:02:12.737,Using SQLite in a Python program,"I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially ""inline"", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production. What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better). I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn). Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.","SQLite automatically creates the database file the first time you try to use it. The SQL statements for creating tables can use IF NOT EXISTS to make the commands only take effect if the table has not been created This way you don't need to check for the database's existence beforehand: SQLite can take care of that for you. The main thing I would still be worried about is that executing CREATE TABLE IF EXISTS for every web transaction (say) would be inefficient; you can avoid that by having the program keep an (in-memory) variable saying whether it has created the database today, so it runs the CREATE TABLE script once per run. This would still allow for you to delete the database and start over during debugging.",0.3426949069654599,False,5,30 2008-10-17 09:02:12.737,Using SQLite in a Python program,"I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially ""inline"", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production. What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better). I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn). Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.","AFAIK an SQLITE database is just a file. To check if the database exists, check for file existence. When you open a SQLITE database it will automatically create one if the file that backs it up is not in place. If you try and open a file as a sqlite3 database that is NOT a database, you will get this: ""sqlite3.DatabaseError: file is encrypted or is not a database"" so check to see if the file exists and also make sure to try and catch the exception in case the file is not a sqlite3 database",1.2,True,5,30 2008-10-17 09:02:12.737,Using SQLite in a Python program,"I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially ""inline"", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production. What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better). I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn). Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.","Doing SQL in overall is horrible in any language I've picked up. SQLalchemy has shown to be easiest from them to use because actual query and committing with it is so clean and absent from troubles. Here's some basic steps on actually using sqlalchemy in your app, better details can be found from the documentation. provide table definitions and create ORM-mappings load database ask it to create tables from the definitions (won't do so if they exist) create session maker (optional) create session After creating a session, you can commit and query from the database.",0.1518770276964961,False,5,30 2008-10-17 09:02:12.737,Using SQLite in a Python program,"I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially ""inline"", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production. What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better). I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn). Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.","Don't make this more complex than it needs to be. The big, independent databases have complex setup and configuration requirements. SQLite is just a file you access with SQL, it's much simpler. Do the following. Add a table to your database for ""Components"" or ""Versions"" or ""Configuration"" or ""Release"" or something administrative like that. CREATE TABLE REVISION( RELEASE_NUMBER CHAR(20) ); In your application, connect to your database normally. Execute a simple query against the revision table. Here's what can happen. The query fails to execute: your database doesn't exist, so execute a series of CREATE statements to build it. The query succeeds but returns no rows or the release number is lower than expected: your database exists, but is out of date. You need to migrate from that release to the current release. Hopefully, you have a sequence of DROP, CREATE and ALTER statements to do this. The query succeeds, and the release number is the expected value. Do nothing more, your database is configured correctly.",0.9985806592017988,False,5,30 2008-10-17 09:02:12.737,Using SQLite in a Python program,"I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially ""inline"", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production. What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better). I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn). Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.","Yes, I was nuking out the problem. All I needed to do was check for the file and catch the IOError if it didn't exist. Thanks for all the other answers. They may come in handy in the future.",0.0,False,5,30 2008-10-20 17:19:57.223,How do I use Tkinter with Python on Windows Vista?,"I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: import Tkinter, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve this?",Maybe you should downgrade to 2.5 version?,1.2,True,3,31 2008-10-20 17:19:57.223,How do I use Tkinter with Python on Windows Vista?,"I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: import Tkinter, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve this?","It seems this is a one of the many weird Vista problems and some random reinstalling, installing/upgrading of the visual studio runtime or some such seems sometimes to help, or disabling sxs in the system configuration or writing a manifest file etc. Though I think you should downgrade to windows XP.",0.1352210990936997,False,3,31 2008-10-20 17:19:57.223,How do I use Tkinter with Python on Windows Vista?,"I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: import Tkinter, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve this?","python 2.6.2 + tkinter 8.5, no problems",-0.1352210990936997,False,3,31 2008-10-22 02:54:17.533,Alternatives to a wizard,"I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game. However, I'm realizing that the limitations of the wizard are making it difficult to design ""elegant"" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated. I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window. However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the ""wxPython in Action"" book doesn't mention it. Are there any tutorials for making ""dynamic panels"" or better management of a wizard?","The wxPython demo has an example of a ""dynamic"" wizard. Pages override GetNext() and GetPrev() to show pages dynamically. This shows the basic technique; you can extend it to add and remove pages, change pages on the fly, and rearrange pages dynamically. The wizard class is just a convenience, though. You can modify it, or create your own implementation. A style that seems popular nowadays is to use an HTML-based presentation; you can emulate this with the wxHtml control, or the IEHtmlWindow control if your app is Windows only.",0.0814518047658113,False,2,32 2008-10-22 02:54:17.533,Alternatives to a wizard,"I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game. However, I'm realizing that the limitations of the wizard are making it difficult to design ""elegant"" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated. I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window. However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the ""wxPython in Action"" book doesn't mention it. Are there any tutorials for making ""dynamic panels"" or better management of a wizard?","I'd get rid of wizard in whole. They are the most unpleasant things I've ever used. The problem that requires a wizard-application where you click 'next' is perhaps a problem where you could apply a better user interface in a bit different manner. Instead of bringing up a dialog with annoying 'next' -button. Do this: Bring up a page. When the user inserts the information to the page, extend or shorten it according to the input. If your application needs to do some processing to continue, and it's impossible to revert after that, write a new page or disable the earlier section of the current page. When you don't need any input from the user anymore or the app is finished, you can show a button or enable an existing such. I don't mean you should implement it all in browser. Make simply a scrolling container that can contain buttons and labels in a flat list. Benefit: The user can just click a tab, and you are encouraged to put all the processing into the end of filling the page.",0.0,False,2,32 2008-10-23 23:50:15.687,Will Django be a good choice for a permissions based web-app?,"I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface. What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to restrict access to client groups based on tiers. Continually expanding. I have a fairly good idea how I'm going to do this, but am not sure if I'll be able to integrate it well into the pre-built admin interface. I've done absolutely zero Django development otherwise I'd probably have a better idea on whether this would work or not. I probably won't use Django if the generated admin interface is going to be useless to this project - but like I said, there is a heavy reliance on fine-grained custom permissions. Will Django let me build custom permissions/rules and integrate it seamlessly into the admin CRUD interface? Update One: I want to use the admin app to minimise the repitition of generating CRUD interfaces, so yes I consider it a must have. Update Two: I want to describe the permissions required for this project. A client can belong to one or many 'stores'. Full time employees should only be able to edit clients at their store (even if they belong to another store). However, they should not be able to see/edit clients at another store. Casuals should only be able to view clients based on what store they are rostered too (or if the casual is logged in as the store user - more likely). Management above them need to be able to see all employees for the stores they manage, nothing more. Senior management should be able to edit ALL employees and grant permissions below themselves. After reading the django documentation, it says you can't (autmoatically) set permissions for a sub-set of a group. Only the entire group. Is it easy enough to mock up your own permissions for this purpose?","The Django permission system totally rules. Each model has a default set of permissions. You can add new permissions to your models, also. Each User has a set of permissions as well as group memberships. Individual users can have individual permissions. And they inherit permissions from their group membership. Your view functions (and templates) can easily check the presence of absence of those permissions at any level of granularity you need to use. And if this isn't enough for you, the Profile add-on gives you yet more options for defining a ""User"" and their capabilities, permissions, roles, responsibilities, etc. And if this isn't enough for you, you can define your own authentication schemes. What's important is not to try and define groups that are actual subsets of users, not casually defined titles or roles. You never need to ""set permissions for a sub-set of a group"". You need to have smaller groups. Groups defined around subsets of people. Django's default permissions are around model access, not row access within a model. On the other hand, your problem is about subsets of rows in several models: Client, Store, Employee, Manager. You'll need a basic set of FK's among these items, and some filters to subset the rows. You may have trouble doing this with default admin pages. You may need your own version of admin to make use of specialized filters. If you can't do it with the Django permission system, you should rethink your use cases. Seriously. [The Django-REST Interface, however, is another beast entirely, and requires some care and feeding.]",0.2655860252697744,False,1,33 2008-10-25 13:30:27.933,How can I use Python for large scale development?,"I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base? When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python? When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup? How do you handle/prevent typing errors (typos)? Are UnitTest's used as a substitute for static type checking? As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.","The usual answer to that is testing testing testing. You're supposed to have an extensive unit test suite and run it often, particularly before a new version goes online. Proponents of dynamically typed languages make the case that you have to test anyway because even in a statically typed language conformance to the crude rules of the type system covers only a small part of what can potentially go wrong.",0.1016881243684853,False,4,34 2008-10-25 13:30:27.933,How can I use Python for large scale development?,"I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base? When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python? When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup? How do you handle/prevent typing errors (typos)? Are UnitTest's used as a substitute for static type checking? As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.","My general rule of thumb is to use dynamic languages for small non-mission-critical projects and statically-typed languages for big projects. I find that code written in a dynamic language such as python gets ""tangled"" more quickly. Partly that is because it is much quicker to write code in a dynamic language and that leads to shortcuts and worse design, at least in my case. Partly it's because I have IntelliJ for quick and easy refactoring when I use Java, which I don't have for python.",0.1518770276964961,False,4,34 2008-10-25 13:30:27.933,How can I use Python for large scale development?,"I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base? When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python? When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup? How do you handle/prevent typing errors (typos)? Are UnitTest's used as a substitute for static type checking? As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.","I had some experience with modifying ""Frets On Fire"", an open source python ""Guitar Hero"" clone. as I see it, python is not really suitable for a really large scale project. I found myself spending a large part of the development time debugging issues related to assignment of incompatible types, things that static typed laguages will reveal effortlessly at compile-time. also, since types are determined on run-time, trying to understand existing code becomes harder, because you have no idea what's the type of that parameter you are currently looking at. in addition to that, calling functions using their name string with the __getattr__ built in function is generally more common in Python than in other programming languages, thus getting the call graph to a certain function somewhat hard (although you can call functions with their name in some statically typed languages as well). I think that Python really shines in small scale software, rapid prototype development, and gluing existing programs together, but I would not use it for large scale software projects, since in those types of programs maintainability becomes the real issue, and in my opinion python is relatively weak there.",0.9999092042625952,False,4,34 2008-10-25 13:30:27.933,How can I use Python for large scale development?,"I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base? When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python? When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup? How do you handle/prevent typing errors (typos)? Are UnitTest's used as a substitute for static type checking? As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.","Since nobody pointed out pychecker, pylint and similar tools, I will: pychecker and pylint are tools that can help you find incorrect assumptions (about function signatures, object attributes, etc.) They won't find everything that a compiler might find in a statically typed language -- but they can find problems that such compilers for such languages can't find, too. Python (and any dynamically typed language) is fundamentally different in terms of the errors you're likely to cause and how you would detect and fix them. It has definite downsides as well as upsides, but many (including me) would argue that in Python's case, the ease of writing code (and the ease of making it structurally sound) and of modifying code without breaking API compatibility (adding new optional arguments, providing different objects that have the same set of methods and attributes) make it suitable just fine for large codebases.",1.2,True,4,34 2008-10-27 03:32:24.250,getting pywin32 to work inside open office 2.4 built in python 2.3 interpreter,"I need to update data to a mssql 2005 database so I have decided to use adodbapi, which is supposed to come built into the standard installation of python 2.1.1 and greater. It needs pywin32 to work correctly and the open office python 2.3 installation does not have pywin32 built into it. It also seems like this built int python installation does not have adodbapi, as I get an error when I go import adodbapi. Any suggestions on how to get both pywin32 and adodbapi installed into this open office 2.4 python installation? thanks oh yeah I tried those ways. annoyingly nothing. So i have reverted to jython, that way I can access Open Office for its conversion capabilities along with decent database access. Thanks for the help.","maybe the best way to install pywin32 is to place it in (openofficedir)\program\python-core-2.3.4\lib\site-packages it is easy if you have a python 2.3 installation (with pywin installed) under C:\python2.3 move the C:\python2.3\Lib\site-packages\ to your (openofficedir)\program\python-core-2.3.4\lib\site-packages",0.1352210990936997,False,1,35 2008-10-27 18:43:41.087,Possible to integrate Google AppEngine and Google Code for continuous integration?,"Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code? I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit. I don't mind if things are broken on the live site since the project is for personal use mainly and for learning. Anyone have any thoughts on how to tie into the subversion commit for the Code repository and/or how to kickoff the deployment to AppEngine? Ideally the solution would not require anything manual from me nor any type of server/listener software on my machine.","Very interesting, but not yet possible, AFAIK. I have been looking for that option in Google Code with no success. The only solution I can figure out is to install something in your machine that checks for changes in your SVN repository. I'll be happy to hear about other approaches.",0.0814518047658113,False,2,36 2008-10-27 18:43:41.087,Possible to integrate Google AppEngine and Google Code for continuous integration?,"Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code? I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit. I don't mind if things are broken on the live site since the project is for personal use mainly and for learning. Anyone have any thoughts on how to tie into the subversion commit for the Code repository and/or how to kickoff the deployment to AppEngine? Ideally the solution would not require anything manual from me nor any type of server/listener software on my machine.","For those of us who are using Github, this feature from the GAE team would make us all seriously consider switching to Google Code...",0.0814518047658113,False,2,36 2008-10-28 02:34:19.140,Python + Leopard + Fink + Mac Ports + Python.org + Idiot = broken Python - fresh start?,"I have been enjoying learning the basics of python, but before I started reading things I tried to install various python versions and modules clumsily. Now that I have some ideas of what I want to do and how to do it I'm finding that various aspects are broken. For instance, 2.6 IDLE won't launch, and when I try to import modules they usually don't work. My question is, how would you recommend I clean this up and start fresh? I have read information about modifying the 2.6 install, but I still can't get it to work. IDLE 2.4 works, and when I launch python from the terminal I am running python 2.4.4.","Macports should be easy to get rid of; just delete /opt/local/. I think that Fink does something similar. You can do which python to see what python is the default one. The system python should be in /System/Library/Frameworks/Python.framework/Versions/2.5/bin/python The MacPython you may have downloaded would either be in /Library/Frameworks/Python.framework. You can delete this as well. Also, both MacPython and MacPorts edit your ~/.profile and change the PYTHONPATH, make sure to edit it and remove the extra paths there.",0.1352210990936997,False,1,37 2008-10-28 18:35:06.173,wxPython wxDC object from win32gui.GetDC,I am getting a DC for a window handle of an object in another program using win32gui.GetDC which returns an int/long. I need to blit this DC into a memory DC in python. The only thing I can't figure out how to do is get a wxDC derived object from the int/long that win32gui returns. None of the wxDC objects allow me to pass an actual DC handle to them from what I can tell. This of course keeps me from doing my blit. Is there any way to do this?,"From what I can tell, DCs in python are abstracted due to platform variation. So a device context in python doesn't directly map to a device context in Windows even though many of the methods are direct Windows method calls. To make this happen it appears you would need to make your own DelegateDC class or something similar that is intended just for Windows so that you could set the DC handle directly. There might also be some way to attach a wxWindow to the window handle after which you could get a wxWindowDC from the wxWindow...can't figure this out though.",0.0,False,1,38 2008-10-31 08:13:00.170,Extending PythonCE to Access gsm/camera/gps Easily from PythonCE,"As it seems there is no scripting language for Windows mobile devices that gives access to phone (sms, mms, make a call, take photo). I wonder how complex it would be to make a Python library that would enable that (write something in C, compile, and import in PythonCE). Question: Where shall start to understand how to compile a PythonCE module that will give additional functionality to Python on Windows mobile. Also, what is the required toolkit. Is it at all possible on Mac (Leopard)?","MSDN has plenty of samples for C++ development on Windows Mobile, and the SDK comes with several sample application. Unfortunately VS Express editions (the free ones) do not come with compilers for Smart Devices. The only free option is the older eMbedded Visual C++ (eVC), which is now something like 8 years old and not supported (though it can still create apps for devices at least up through CE 5.0).",0.1352210990936997,False,1,39 2008-11-04 22:47:39.493,How can I ask for root password but perform the action at a later time?,"I have a python script that I would like to add a ""Shutdown when done"" feature to. I know I can use gksudo (when the user clicks on ""shutdown when done"") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished). I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that. Any ideas how I can achieve this? Thanks in advance, Ashy.","Instead of chmod u+sing the shutdown command, allowing passwordless sudo access to that command would be better.. As for allowing shutdown at the end of the script, I suppose you could run the entire script with sudo, then drop privileges to the initial user at the start of the script?",0.4961739557460144,False,3,40 2008-11-04 22:47:39.493,How can I ask for root password but perform the action at a later time?,"I have a python script that I would like to add a ""Shutdown when done"" feature to. I know I can use gksudo (when the user clicks on ""shutdown when done"") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished). I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that. Any ideas how I can achieve this? Thanks in advance, Ashy.","Escalate priority, spawn (fork (2)) a separate process that will wait (2), and drop priority in the main process.",0.1352210990936997,False,3,40 2008-11-04 22:47:39.493,How can I ask for root password but perform the action at a later time?,"I have a python script that I would like to add a ""Shutdown when done"" feature to. I know I can use gksudo (when the user clicks on ""shutdown when done"") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished). I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that. Any ideas how I can achieve this? Thanks in advance, Ashy.","gksudo should have a timeout, I believe it's from the time you last executed a gksudo command. So I think I'd just throw out a ""gksudo echo meh"" or something every minute. Should reset the timer and keep you active until you reboot.",1.2,True,3,40 2008-11-05 21:50:04.180,Using Python's smtplib with Tor,"I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending. Ideas how this can be done?","Because of abuse by spammers, many Tor egress nodes decline to emit port 25 (SMTP) traffic, so you may have problems.",1.2,True,1,41 2008-11-06 09:39:20.723,Multiple database support in django,"From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet. Can anyone please tell me how one can achieve multiple database connections in Django. Does anyone have any idea by when Django will fully/officially support Multiple database connections.","If you read a few of the many (many) threads on this subject in django-dev, you will see that what looks straightforward, isn't. If you pick a single use case, then it looks easy, but as soon as you start to generalize in any way you start to run into trouble. To use the above-referenced thread as an example, when you say ""multiple databases"", which of the following are you talking about? All DB on the same machine under the same engine. All DB on same machine, different engines (E.g. MySQL + PostgreSQL) One Master DB with N read-only slaves on different machines. Sharding of tables across multiple DB servers. Will you need: Foreign keys across DBs JOINs across machines and/or engines etc. etc. One of the problems with a slick ORM like Django's is that it hides all of those messy details under a nice paint job. To continue to do that, but to then add in any of the above, is Not Easy (tm).",0.1218406379589197,False,1,42 2008-11-07 11:35:00.583,How should I stress test / load test a client server application?,"I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as: • How many clients can a server support? • How many concurrent searches can a server support? • How much data can we store in the database? • Etc. Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration. Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though. I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems. One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work. So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with!","For performance you are looking at two things: latency (the responsiveness of the application) and throughput (how many ops per interval). For latency you need to have an acceptable benchmark. For throughput you need to have a minimum acceptable throughput. These are you starting points. For telling a client how many xyz's you can do per interval then you are going to need to know the hardware and software configuration. Knowing the production hardware is important to getting accurate figures. If you do not know the hardware configuration then you need to devise a way to map your figures from the test hardware to the eventual production hardware. Without knowledge of hardware then you can really only observe trends in performance over time rather than absolutes. Knowing the software configuration is equally important. Do you have a clustered server configuration, is it load balanced, is there anything else running on the server? Can you scale your software or do you have to scale the hardware to meet demand. To know how many clients you can support you need to understand what is a standard set of operations. A quick test is to remove the client and write a stub client and the spin up as many of these as you can. Have each one connect to the server. You will eventually reach the server connection resource limit. Without connection pooling or better hardware you can't get higher than this. Often you will hit a architectural issue before here but in either case you have an upper bounds. Take this information and design a script that your client can enact. You need to map how long your script takes to perform the action with respect to how long it will take the expected user to do it. Start increasing your numbers as mentioned above to you hit the point where the increase in clients causes a greater decrease in performance. There are many ways to stress test but the key is understanding expected load. Ask your client about their expectations. What is the expected demand per interval? From there you can work out upper loads. You can do a soak test with many clients operating continously for many hours or days. You can try to connect as many clients as you can as fast you can to see how well your server handles high demand (also a DOS attack). Concurrent searches should be done through your standard behaviour searches acting on behalf of the client or, write a script to establish a semaphore that waits on many threads, then you can release them all at once. This is fun and punishes your database. When performing searches you need to take into account any caching layers that may exist. You need to test both caching and without caching (in scenarios where everyone makes unique search requests). Database storage is based on physical space; you can determine row size from the field lengths and expected data population. Extrapolate this out statistically or create a data generation script (useful for your load testing scenarios and should be an asset to your organisation) and then map the generated data to business objects. Your clients will care about how many ""business objects"" they can store while you will care about how much raw data can be stored. Other things to consider: What is the expected availability? What about how long it takes to bring a server online. 99.9% availability is not good if it takes two days to bring back online the one time it does go down. On the flip side a lower availablility is more acceptable if it takes 5 seconds to reboot and you have a fall over.",0.3869120172231254,False,2,43 2008-11-07 11:35:00.583,How should I stress test / load test a client server application?,"I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as: • How many clients can a server support? • How many concurrent searches can a server support? • How much data can we store in the database? • Etc. Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration. Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though. I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems. One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work. So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with!","If you have the budget, LoadRunner would be perfect for this.",0.0,False,2,43 2008-11-16 22:11:25.050,How do I find userid by login (Python under *NIX),"I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find uid if I have login? I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?","Never directly scan /etc/passwd. For instance, on a Linux system I administer, the user accounts are not on /etc/passwd, but on a LDAP server. The correct way is to use getpwent/getgrent and related C functions (as in @TFKyle's answer), which will get the information on the correct way for each system (on Linux glibc, it reads /etc/nsswitch.conf to know which NSS dynamic libraries to load to get the information).",0.9866142981514304,False,1,44 2008-11-17 14:24:32.683,What is a partial class?,"What is and how can it be used in C#. Can you use the same concept in Python/Perl?",Because python is a dynamic language you don't need a concept like partial class. In python is possible to extend object with functionality in runtime so it possible to break class declaration into different files,0.0509761841073563,False,3,45 2008-11-17 14:24:32.683,What is a partial class?,"What is and how can it be used in C#. Can you use the same concept in Python/Perl?","A Partial type is a type whose declaration is separated across multiple files. It makes sense to use them if you have a big class, which is hard to handle and read for a typical developer, to separate that class definition in separate files and to put in each file a logically separated section of code (for instance all public methods and proprieties in one file, private in other, db handling code in third and so on..) No you don't have the same syntactical element in Python.",0.0,False,3,45 2008-11-17 14:24:32.683,What is a partial class?,"What is and how can it be used in C#. Can you use the same concept in Python/Perl?",Python also has meta classes but that is more like a template class than a partial class. A good example of meta class usage is the Django ORM. All of your table models inherit from a base model class which also gets functionality included from a meta class. It is a pretty cool concept that enables an active record like pattern (is it full active record?).,0.0,False,3,45 2008-11-17 18:56:12.727,How do I remove a specific number of files using python (version 2.5)?,I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance.,"It is perfectly acceptable to have a 'cleanup()' function that you call at the end of your script, which will call 'os.remove()' on your files.",0.0,False,1,46 2008-11-18 13:52:31.717,Django Template Variables and Javascript,"When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}. Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.","For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library.",0.2012947653214861,False,1,47 2008-11-18 16:22:39.447,How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line?,"I am familiar with using the os.system to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (located in my 'test' folder) requires a file inside of my 'test' folder. So, how would I write a function in my script that does the following: c:\test>java -jar run_this.jar required_parameter.ext ? I'm a python newbie so details are greatly appreciated. Thanks in advance.","In general: Use os.chdir to change the directory of the parent process, then os.system to run the jar file. If you need to keep Python's working directory stable, you need to chdir back to original working directory - you need to record that with os.getcwd(). On Unix: Create a child process with os.fork explicitly. In the parent, wait for the child with os.waitpid. In the child, use os.chdir, then os.exec to run java.",0.2012947653214861,False,1,48 2008-11-18 18:39:05.350,What are good ways to make my Python code run first time?,"I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?",Eric4 IDE also has a great built-in debugger.,0.0,False,6,49 2008-11-18 18:39:05.350,What are good ways to make my Python code run first time?,"I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?","The PyDev plugin for eclipse is my tool of choice. It recognizes simple syntax mistakes and indentation errors and underlines the error with a red line. It has a powerful debugger and even has a plugin called PyLint which warns you about dangerous code. Edit: It also has a user friendly stack trace on runtime errors, partial auto complete and some other nifty features. Edit again: I didn't notice that pydev was mentioned in the top post. I hope I brought something else to the table.",0.1016881243684853,False,6,49 2008-11-18 18:39:05.350,What are good ways to make my Python code run first time?,"I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?","I am new to python, and have been trying several different debuggers. Here are the options I've come across so far: Eclipse with Pydev - If you're already using eclipse, this is probably the way to go. The debugger works well, and is pretty featureful. Komodo IDE - A light-weight python IDE. Basically a text editor + a debugger. It was really easy to figure out and be productive with immediately. WinPDB - Trying this one next. Looks very featureful, and I get to use whichever editor I choose. PDB - Haven't tried yet since I've read about how WinPDB is a better alternative. Ipython with %run command - I've used IPython, but not as a debugger like this. I need to try this out. (Thanks for the tip, EOL) Eric IDE - Also on the list to try. Old-school print, assert statements - Simple, useful, but not a full solution. Memory debugging - To debug memory problems, I've come across a few tools: objgraph - Will generate png's of reference graphs. Neat. There's other functionality as well, like: import objgraph;print(objgraph.show_most_common_types(limit=10)) will print the top 10 most common types in memory. gc module - Interact directly with the garbage collector. heapy - Heap analyzer. For example: from guppy import hpy; hp = hpy(); print(hp.heap()) will print the most common types, their memory usage, etc. This is a very incomplete list, but hopefully it's a good start.",0.2497086294969975,False,6,49 2008-11-18 18:39:05.350,What are good ways to make my Python code run first time?,"I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?",Using assert statement liberally.,0.126863772113723,False,6,49 2008-11-18 18:39:05.350,What are good ways to make my Python code run first time?,"I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?","All the really cool stuff is easily demonstrated in the interactive interpreter. I think this might be the ""gold standard"" for good design: Can you exercise your class interactively? If you can do stuff interactively, then you can write unittests and doctests with confidence that it's testable, simple, reliable. And, more important, you can explore it interactively. There's nothing better than the instant gratification that comes from typing code and seeing exactly what happens. The compiled language habits (write a bunch of stuff, debug a bunch of stuff, test a bunch of stuff) can be left behind. Instead, you can write a little bit of stuff, explore it, write a formal test and then attach your little bit of stuff to your growing final project. You still do overall design. But you don't squander time writing code that may or may not work. In Python you write code that works. If you're not sure, you play with it interactively until you're sure. Then you write code that works.",0.3650092804034399,False,6,49 2008-11-18 18:39:05.350,What are good ways to make my Python code run first time?,"I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?","Test early and test often. This doesn't necessarily mean to jump into the test driven design pool head first (though that's not such a bad idea). It just means, test your objects and methods as soon as you have something that works. Don't wait until you have a huge pile of code before doing testing. Invest some time in learning a testing framework. If it's trivial for you to type in a test case you'll more likely do it. If you don't have any sort of framework testing can be a pain so you'll avoid it. So, establish some good habits early on and you'll have fewer problems down the road.",0.1766972496294356,False,6,49 2008-11-18 19:51:54.423,Calling Java (or python or perl) from a PHP script,"I've been trying to build a simple prototype application in Django, and am reaching the point of giving up, sadly, as it's just too complicated (I know it would be worth it in the long-run, but I really just don't have enough time available -- I need something up and running in a few days). So, I'm now thinking of going with PHP instead, as it's the method for creating dynamic web content I'm most familiar with, and I know I can get something working quickly. My application, while simple, is probably going to be doing some reasonably complex AI stuff, and it may be that libraries don't exist for what I need in PHP. So I'm wondering how easy / possible it is for a PHP script to ""call"" a Java program or Python script or a program or script in another language. It's not entirely clear to me what exactly I mean by ""call"" in this context, but I guess I probably mean that ideally I'd like to define a function in, let's say Java, and then be able to call it from PHP. If that's not possible, then I guess my best bet (assuming I do go with PHP) will be to pass control directly to the external program explicitly through a POST or GET to a CGI program or similar. Feel free to convince me I should stick with Django, although I'm really at the point where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex... Alternatively, anyone who can offer any advice on linking PHP and other languages, that'll be grateful received.","""where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex"" Common problem. Root cause: Too much programming. Solution. Do less programming. Seriously. Define the Django model. Use the default admin pages to see if it's right. Fix the model. Regenerate the database. Look at the default admin pages. Repeat until the default admin pages work correctly and simply. Once it's right in the default admin pages, you have a model that works. It's testable. And the automatic stuff is hooked up correctly. Choices are defined correctly. Computations are in the model mmethods. Queries work. Now you can start working on other presentations of the data. Django generally starts (and ends) with the model. The forms, view and templates are derived from the model.",1.2,True,1,50 2008-11-20 20:47:28.740,"With Python, how can I ensure that compression of a folder takes place within a particular folder?","I have been able to zip the contents of my folder. But I would like the zipped file to remain in the folder that was just compressed. For example, I've zipped a folder called test in my C: drive. But I would like my ""test.zip"" file to be contained in C:\test. How can I do this? Thanks in advance. clarification of question with code example: Someone kindly pointed out that my question is confusing, but for a python newbie a lot of things are confusing :) - my advance apologies if this question is too basic or the answer is obvious. I don't know how I can ensure that the resulting zip file is inside the folder that has been zipped. In other words, I would like the zip process to take place in 'basedir.' That way the user does not waste time searching for it somewhere on the C drive. def zip_folder(basedir, zip_file): z = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(basedir): print ""zipping files:"" for fn in filenames: print fn absfn = os.path.join(dirpath, fn) z.write(absfn) z.close","Whatever you pass as zip_file to your function will be the file that the ZipFile object will write to. So if you pass it a full path, then it will be put there. If you pass it just a filename, then it will be written to that filename under the current working path. It sounds like you just need to make sure that zip_file is an absolute path.",1.2,True,1,51 2008-11-24 22:21:17.943,Running a function periodically in twisted protocol,I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reactor as needed. I don't know how to tie it from reactor to all protocol instances...,"I'd imagine the easiest way to do that is to manage a list of clients in the protocol with connectionMade and connectionLost in the client and then use a LoopingCall to ask each client to send data. That feels a little invasive, but I don't think you'd want to do it without the protocol having some control over the transmission/reception. Of course, I'd have to see your code to really know how it'd fit in well. Got a github link? :)",0.5457054096481145,False,1,52 2008-11-26 06:20:40.703,How do I skip processing the attachments of an email which is an attachment of a different email,"using jython I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file. I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments. What I want to do is skip that attached email and all its attachments. using python/jythons std email lib how can i do this? to make it clearer I need to parse an email (named ROOT email), I want to get the attachments from this email using jython. Next certain attachments are supported ie .pdf .doc etc now it just so happens that, the clients send an email (ROOT email) with another email message (CHILD email) as an attachment, and in CHILD email it has .pdf attachments and such like. What I need is: to get rid of any CHILD emails attached to the ROOT email AND the CHILD emails attachments. What happens is I walk over the whole email and it just parses every attachment, BOTH ROOT attachments and CHILD attachments as if they were ROOT attachments. I cannot have this. I am only interested in ROOT attachements that are legal ie .pdf .doc. xls .rtf .tif .tiff That should do for now, I have to run to catch a bus! thanks!","Have you tried the get_payload( [i[, decode]]) method? Unlike walk it is not documented to recursively open attachments.",0.0,False,1,53 2008-11-26 19:09:08.440,Comparing XML in a unit test in Python,"I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).","Why are you examining the XML data at all? The way to test object serialization is to create an instance of the object, serialize it, deserialize it into a new object, and compare the two objects. When you make a change that breaks serialization or deserialization, this test will fail. The only thing checking the XML data is going to find for you is if your serializer is emitting a superset of what the deserializer requires, and the deserializer silently ignores stuff it doesn't expect. Of course, if something else is going to be consuming the serialized data, that's another matter. But in that case, you ought to be thinking about establishing a schema for the XML and validating it.",0.1218406379589197,False,2,54 2008-11-26 19:09:08.440,Comparing XML in a unit test in Python,"I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).","The Java component dbUnit does a lot of XML comparisons, so you might find it useful to look at their approach (especially to find any gotchas that they may have already addressed).",0.0,False,2,54 2008-12-05 12:02:54.363,How do I submit a form given only the HTML source?,"I would like to be able to submit a form in an HTML source (string). In other words I need at least the ability to generate POST parameters from a string containing HTML source of the form. This is needed in unit tests for a Django project. I would like a solution that possibly; Uses only standard Python library and Django. Allows parameter generation from a specific form if there is more than one form present. Allows me to change the values before submission. A solution that returns a (Django) form instance from a given form class is best. Because it would allow me to use validation. Ideally it would consume the source (which is a string), a form class, and optionally a form name and return the instance as it was before rendering. NOTE: I am aware this is not an easy task, and probably the gains would hardly justify the effort needed. But I am just curious about how this can be done, in a practical and reliable way. If possible.","It is simple... and hard at the same time. Disclaimer: I don't know much about Python and nothing at all about Django... So I give general, language agnostic advices... If one of the above advices doesn't work for you, you might want to do it manually: Load the page with an HTML parser, list the forms. If the method attribute is POST (case insensitive), get the action attribute to get the URL of the request (can be relative). In the form, get all input and select tags. The name (or id if no name) attributes are the keys of the request parameters. The value attributes (empty if absent) are the corresponding values. For select, the value is the one of the selected option or the displayed text is no value attribute. These names and values must be URL encoded in GET requests, but not in POST ones. HTH.",0.2012947653214861,False,1,55 2008-12-06 12:41:36.813,Read file object as string in python,"I'm using urllib2 to read in a page. I need to do a quick regex on the source and pull out a few variables but urllib2 presents as a file object rather than a string. I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string?","You can use Python in interactive mode to search for solutions. if f is your object, you can enter dir(f) to see all methods and attributes. There's one called read. Enter help(f.read) and it tells you that f.read() is the way to retrieve a string from an file object.",1.2,True,1,56 2008-12-13 10:30:41.947,Can you change a field label in the Django Admin application?,"As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?",Building on Javier's answer; if you need one label in forms (on the front-end) and another label on admin it is best to set internal (admin) one in the model and overwrite it on forms. Admin will of course use the label in the model field automatically.,0.3275988531455109,False,1,57 2008-12-17 18:54:03.843,Prevent ftplib from Downloading a File in Progress?,"We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list. We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in. What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased. What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method. Yet again let me reiterate this, we have 0 control over the remote ftp sites. Thanks. UPDATE1: I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail? We don't have any real options here... do we? UPDATE2: Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts. E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete. Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file. :'(","You can't know when the OS copy is done. It could slow down or wait. For absolute certainty, you really need two files. The massive file. And a tiny trigger file. They can mess with the massive file all they want. But when they touch the trigger file, you're downloading both. If you can't get a trigger, you have to balance the time required to poll vs. the time required to download. Do this. Get a listing. Check timestamps. Check sizes vs. previous size of file. If size isn't even close, it's being copied right now. Wait; loop on this step until size is close to previous size. While you're not done: a. Get the file. b. Get a listing AGAIN. Check the size of the new listing, previous listing and your file. If they agree: you're done. If they don't agree: file changed while you were downloading; you're not done.",0.0,False,4,58 2008-12-17 18:54:03.843,Prevent ftplib from Downloading a File in Progress?,"We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list. We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in. What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased. What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method. Yet again let me reiterate this, we have 0 control over the remote ftp sites. Thanks. UPDATE1: I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail? We don't have any real options here... do we? UPDATE2: Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts. E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete. Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file. :'(","“Damn the torpedoes! Full speed ahead!” Just download the file. If it is a large file then after the download completes wait as long as is reasonable for your scenario and continue the download from the point it stopped. Repeat until there is no more stuff to download.",1.2,True,4,58 2008-12-17 18:54:03.843,Prevent ftplib from Downloading a File in Progress?,"We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list. We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in. What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased. What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method. Yet again let me reiterate this, we have 0 control over the remote ftp sites. Thanks. UPDATE1: I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail? We don't have any real options here... do we? UPDATE2: Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts. E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete. Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file. :'(","If you are dealing with multiple files, you could get the list of all the sizes at once, wait ten seconds, and see which are the same. Whichever are still the same should be safe to download.",0.0,False,4,58 2008-12-17 18:54:03.843,Prevent ftplib from Downloading a File in Progress?,"We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list. We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in. What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased. What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method. Yet again let me reiterate this, we have 0 control over the remote ftp sites. Thanks. UPDATE1: I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail? We don't have any real options here... do we? UPDATE2: Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts. E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete. Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file. :'(","As you say you have 0 control over the servers and can't make your clients post trigger files as suggested by S. Lott, you must deal with the imperfect solution and risk incomplete file transmission, perhaps by waiting for a while and compare file sizes before and after. You can try to rename as you suggested, but as you have 0 control you can't be sure that the ftp-server-administrator (or their successor) doesn't change platforms or ftp servers or restricts your permissions. Sorry.",0.0,False,4,58 2008-12-18 09:41:52.897,Code not waiting for class initialization!,"I have a block of code that basically intializes several classes, but they are placed in a sequential order, as later ones reference early ones. For some reason the last one initializes before the first one...it seems to me there is some sort of threading going on. What I need to know is how can I stop it from doing this? Is there some way to make a class init do something similar to sending a return value? Or maybe I could use the class in an if statement of some sort to check if the class has already been initialized? I'm a bit new to Python and am migrating from C, so I'm still getting used to the little differences like naming conventions.","Python upto 3.0 has a global lock, so everything is running in a single thread and in sequence. My guess is that some side effect initializes the last class from a different place than you expect. Throw an exception in __init__ of that last class to see where it gets called.",1.2,True,2,59 2008-12-18 09:41:52.897,Code not waiting for class initialization!,"I have a block of code that basically intializes several classes, but they are placed in a sequential order, as later ones reference early ones. For some reason the last one initializes before the first one...it seems to me there is some sort of threading going on. What I need to know is how can I stop it from doing this? Is there some way to make a class init do something similar to sending a return value? Or maybe I could use the class in an if statement of some sort to check if the class has already been initialized? I'm a bit new to Python and am migrating from C, so I'm still getting used to the little differences like naming conventions.","Spaces vs. Tabs issue...ugh. >.> Well, atleast it works now. I admit that I kind of miss the braces from C instead of forced-indentation. It's quite handy as a prototyping language though. Maybe I'll grow to love it more when I get a better grasp of it.",0.0,False,2,59 2008-12-18 21:23:50.017,How to integrate the StringTemplate engine into the CherryPy web server,"I love the StringTemplate engine, and I love the CherryPy web server, and I know that they can be integrated. Who has done it? How? EDIT: The TurboGears framework takes the CherryPy web server and bundles other related components such as a template engine, data access tools, JavaScript kit, etc. I am interested in MochiKit, demand CherryPy, but I don't want any other template engine than StringTemplate (architecture is critical--I don't want another broken/bad template engine). Therefore, it would be acceptable to answer this question by addressing how to integrate StringTemplate with TurboGears. It may also be acceptable to answer this question by addressing how to use CherryPy and StringTemplate in the Google App Engine. Thanks.","Rob, There's reason behind people's selection of tools. StringTemplate is not terribly popular for Python, there are templating engines that are much better supported and with a much wider audience. If you don't like Kid, there's also Django's templating, Jinja, Cheetah and others. Perhaps you can find in one of them the features you like so much in StringTemplate and live happily ever after.",0.0,False,2,60 2008-12-18 21:23:50.017,How to integrate the StringTemplate engine into the CherryPy web server,"I love the StringTemplate engine, and I love the CherryPy web server, and I know that they can be integrated. Who has done it? How? EDIT: The TurboGears framework takes the CherryPy web server and bundles other related components such as a template engine, data access tools, JavaScript kit, etc. I am interested in MochiKit, demand CherryPy, but I don't want any other template engine than StringTemplate (architecture is critical--I don't want another broken/bad template engine). Therefore, it would be acceptable to answer this question by addressing how to integrate StringTemplate with TurboGears. It may also be acceptable to answer this question by addressing how to use CherryPy and StringTemplate in the Google App Engine. Thanks.","Based on the tutorials for both, it looks pretty straightforward: import stringtemplate import cherrypy class HelloWorld(object): def index(self): hello = stringtemplate.StringTemplate(""Hello, $name$"") hello[""name""] = ""World"" return str(hello) index.exposed = True cherrypy.quickstart(HelloWorld()) You'll probably want to have the CherryPy functions find the StringTemplate's in some location on disk instead, but the general idea will be like this. Django is conceptually similar: url's are mapped to python functions, and the python functions generally build up a context dictionary, render a template with that context object, and return the result.",0.6730655149877884,False,2,60 2008-12-18 21:52:22.050,How much slower is a wxWidget written in Python versus C++?,"I'm looking into writing a wxWidget that displays a graphical node network, and therefore does a lot of drawing operations. I know that using Python to do it is going to be slower, but I'd rather get it working and port it later when its functional. Ideally, if the performance hit isn't too great, I'd prefer to keep the codebase in Python for easy updates. What I'm wondering is how much slower should I expect things to go? I realize this is vague and open ended, but I just need a sense of what to expect. Will drawing 500 circles bog down? Will it be noticeable at all? What are your experiences?","For drawing, people have suggested PyGame. I like PyGame, its easy to work with and works well. Other choices would be Pyglet, or using PyOpenGL (you can most likely draw to a wx widget too, though I've never done it). Personally, I'd do it in Python using whatever library I'm most familiar with (in my case, I'd use pygtk and cairo) and worry about performance only when it becomes a problem - then profile and optimize the bottleneck, if its Python code thats slow, I'll know which bits to run in C instead.",0.1352210990936997,False,1,61 2008-12-22 02:25:02.243,"Prototype based object orientation. The good, the bad and the ugly?","I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO. The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects. In summary, what is the good, the bad and the ugly parts of such approach?","Okay, first of all, the prototype model isn't all that different in reality; Smalltalk uses a similar sort of scheme; the class is an object with the classes methods. Looked at from the class POV, a class is really the equivalence class of objects with the same data, and all the same methods; you can look at adding a method to a prototype as creating a new subclass. The implementation is simple, but makes it very difficult to do effective typechecking.",0.0,False,2,62 2008-12-22 02:25:02.243,"Prototype based object orientation. The good, the bad and the ugly?","I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO. The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects. In summary, what is the good, the bad and the ugly parts of such approach?","Classical inheritance is inherently flawed in terms of flexibility, in that we are saying ""this object is of this type and no other"". Some languages introduce multiple inheritance to alleviate this, but multiple inheritance has its own pitfalls, and so the benefits of pure composition over inheritance (which, in a statically typed language, is a runtime rather than a compile time mechanism) become clear. Taking the concept of composition to this ""pure"" level, we can eliminate classical inheritance altogether along with static typing. By composing objects at runtime and using them as blueprints (the prototypal approach), we need never concern ourselves with boxing objects too tightly through inheritance, nor burden ourselves with the issues inherent in multiple inheritance approaches. So prototypal means much more flexible development of modules. Of course, it's quite another thing to say it's EASY to develop without static typing. IMO, it is not.",0.0814518047658113,False,2,62 2008-12-22 22:37:08.520,Using user input to find information in a Mysql database,"I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. I am a bit stuck on how to get started. Does anyone have any tips for me?","That is a very ambiguous question. What you want can be done in many ways depending on what you actually want to do. How are your users going to enter the bar code? Are they going to use a bar code scanner? Are they entering the bar code numbers manually? Is this going to run on a desktop/laptop computer or is it going to run on a handheld device? Is the bar code scanner storing the bar codes for later retrieval or is it sending them directly to the computer. Will it send them through a USB cable or wireless?",0.0,False,3,63 2008-12-22 22:37:08.520,Using user input to find information in a Mysql database,"I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. I am a bit stuck on how to get started. Does anyone have any tips for me?","A barcode is simply a graphical representation of a series of characters (alphanumeric) So if you have a method for users to enter this code (a barcode scanner), then its just an issue of querying the mysql database for the character string.",0.1016881243684853,False,3,63 2008-12-22 22:37:08.520,Using user input to find information in a Mysql database,"I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. I am a bit stuck on how to get started. Does anyone have any tips for me?","To start with, treat the barcode input as plain old text. It has been quite a while since I worked with barcode scanners, but I doubt they have changed that much, the older ones used to just piggyback on the keyboard input, so from a programming perspective, the net result was a stream of characters in the keyboard buffer, either typed or scanned made no difference. If the device you are targeting differs from that, you will need to write something to deal with that before you get to the database query. If you have one of the devices to play with, plug it in, start notepad, start scanning some barcodes and see what happens.",0.0,False,3,63 2008-12-23 22:37:51.123,Interpreting Excel Currency Values,"I am using python to read a currency value from excel. The returned from the range.Value method is a tuple that I don't know how to parse. For example, the cell appears as $548,982, but in python the value is returned as (1, 1194857614). How can I get the numerical amount from excel or how can I convert this tuple value into the numerical value? Thanks!","I tried this with Excel 2007 and VBA. It is giving correct value. 1) Try pasting this value in a new excel workbook 2) Press Alt + F11. Gets you to VBA Editor. 3) Press Ctrl + G. Gets you to immediate window. 4) In the immediate window, type ?cells(""a1"").Value here ""a1"" is the cell where you have pasted the value. I am doubting that the cell has some value or character due to which it is interpreted this way. Post your observations here.",0.0,False,1,64 2009-01-01 00:55:16.753,Python program to calculate harmonic series,Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...,"The harmonic series diverges, i.e. its sum is infinity.. edit: Unless you want partial sums, but you weren't really clear about that.",0.1473426351731879,False,2,65 2009-01-01 00:55:16.753,Python program to calculate harmonic series,Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...,Just a footnote on the other answers that used floating point; starting with the largest divisor and iterating downward (toward the reciprocals with largest value) will put off accumulated round-off error as much as possible.,0.1834289726823514,False,2,65 2009-01-03 19:37:41.127,What versions of Python and wxPython correspond to each version of OSX?,I'd like to know what versions of Python and wxPython correspond to each version of OSX. I'm interested to know exactly how far back some of my apps will remain compatible on a mac before having to install newer versions of Python and wxPython.,"Tiger shipped with Python 2.3.5 and wxPython 2.5.3, Leopard ships with python 2.5.1 and wxPython 2.8.4. wxPython was not shipped with previous versions. OSX Lion has 2.7.1",1.2,True,1,66 2009-01-08 05:45:02.847,Using global variables in a function,"How can I create or use a global variable in a function? If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?","If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global. You don't have to use it in all cases (as someone here incorrectly claims) - if the name referenced in an expression cannot be found in local scope or scopes in the functions in which this function is defined, it is looked up among global variables. However, if you assign to a new variable not declared as global in the function, it is implicitly declared as local, and it can overshadow any existing global variable with the same name. Also, global variables are useful, contrary to some OOP zealots who claim otherwise - especially for smaller scripts, where OOP is overkill.",0.9941605004152156,False,2,67 2009-01-08 05:45:02.847,Using global variables in a function,"How can I create or use a global variable in a function? If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?","You're not actually storing the global in a local variable, just creating a local reference to the same object that your original global reference refers to. Remember that pretty much everything in Python is a name referring to an object, and nothing gets copied in usual operation. If you didn't have to explicitly specify when an identifier was to refer to a predefined global, then you'd presumably have to explicitly specify when an identifier is a new local variable instead (for example, with something like the 'var' command seen in JavaScript). Since local variables are more common than global variables in any serious and non-trivial system, Python's system makes more sense in most cases. You could have a language which attempted to guess, using a global variable if it existed or creating a local variable if it didn't. However, that would be very error-prone. For example, importing another module could inadvertently introduce a global variable by that name, changing the behaviour of your program.",0.4154472204360744,False,2,67 2009-01-08 20:17:05.613,Drag button between panels in wxPython,"Does anyone know of an example where it is shown how to drag a button from one panel to another in wxPython? I have created a bitmap button in a panel, and I would like to be able to drag it to a different panel and drop I there. I haven't found any examples using buttons, just text and files. I am using the latest version of Python and wxPython.","If you want to graphically represent the drag, one good way to do this is to create a borderless Frame that follows the mouse during a drag. You remove the button from your source Frame, temporarily put it in this ""drag Frame"", and then, when the user drops, add it to your destination Frame.",1.2,True,1,68 2009-01-10 00:10:56.947,"Best way to poll a web service (eg, for a twitter app)","I need to poll a web service, in this case twitter's API, and I'm wondering what the conventional wisdom is on this topic. I'm not sure whether this is important, but I've always found feedback useful in the past. A couple scenarios I've come up with: The querying process starts every X seconds, eg a cron job runs a python script A process continually loops and queries at each iteration, eg ... well, here is where I enter unfamiliar territory. Do I just run a python script that doesn't end? Thanks for your advice. ps - regarding the particulars of twitter: I know that it sends emails for following and direct messages, but sometimes one might want the flexibility of parsing @replies. In those cases, I believe polling is as good as it gets. pps - twitter limits bots to 100 requests per 60 minutes. I don't know if this also limits web scraping or rss feed reading. Anyone know how easy or hard it is to be whitelisted? Thanks again.","You should have a page that is like a Ping or Heartbeat page. The you have another process that ""tickles"" or hits that page, usually you can do this in your Control Panel of your web host, or use a cron if you have a local access. Then this script can keep statistics of how often it has polled in a database or some data store and then you poll the service as often as you really need to, of course limiting it to whatever the providers limit is. You definitely don't want to (and certainly don't want to rely) on a python scrip that ""doesn't end."" :)",0.0,False,1,69 2009-01-10 23:57:46.473,Programming Design Help - How to Structure a Sudoku Solver program?,"I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this... Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class? Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array? And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object? Thanks.",Don't over-engineer it. It's a 2-D array or maybe a Board class that represents a 2-D array at best. Have functions that calculate a given row/column and functions that let you access each square. Additional methods can be used validate that each sub-3x3 and row/column don't violate the required constraints.,0.5457054096481145,False,5,70 2009-01-10 23:57:46.473,Programming Design Help - How to Structure a Sudoku Solver program?,"I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this... Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class? Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array? And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object? Thanks.","Maybe a design that had a box per square, and another class to represent the puzzle itself that would have a collection of boxes, contain all the rules for box interactions, and control the overall game would be a good design.",0.0,False,5,70 2009-01-10 23:57:46.473,Programming Design Help - How to Structure a Sudoku Solver program?,"I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this... Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class? Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array? And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object? Thanks.","First, it looks like there are two kinds of cells. Known calls; those with a fixed value, no choices. Unknown cells; those with a set of candidate values that reduces down to a single final value. Second, there are several groups of cells. Horizontal rows and Vertical columns which must have one cell of each value. That constraint is used to remove values from various cells in the row or column. 3x3 blocks which must have one cell of each value. That constraint is used to remove values from various cells in the block. Finally, there's the overall grid. This has several complementary views. It's 81 cells. The cells are also collected into a 3x3 grid of 3x3 blocks. The cells are also collected into 9 columns. The cells are also collected into 9 rows. And you have a solver strategy object. Each Unknown cell it set to having set( range(1,10) ) as the candidate values. For each row, column and 3x3 block (27 different collections): a. For each cell: If it has definite value (Known cells and Unknown cells implement this differently): remove that value from all other cells in this grouping. The above must be iterated until no changes are found. At this point, you either have it solved (all cells report a definite value), or, you have some cells with multiple values. Now you have to engage in a sophisticated back-tracking solver to find a combination of the remaining values that ""works"".",0.0,False,5,70 2009-01-10 23:57:46.473,Programming Design Help - How to Structure a Sudoku Solver program?,"I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this... Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class? Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array? And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object? Thanks.","Well, I would use one class for the sudoku itself, with a 9 x 9 array and all the functionality to add numbers and detect errors in the pattern. Another class will be used to solve the puzzle.",0.1016881243684853,False,5,70 2009-01-10 23:57:46.473,Programming Design Help - How to Structure a Sudoku Solver program?,"I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this... Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class? Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array? And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object? Thanks.","The simplest way to do it is to represent the board by a 2D 9x9 array. You'll want to have references to each row, column and 3x3 box as a separate object, so storing each cell in a String makes more sense (in Java) than using a primitive. With a String you can keep references to the same object in multiple containers.",0.0509761841073563,False,5,70 2009-01-12 04:05:35.690,Installing certain packages using virtualenv,"So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this? Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages'","If you want django to be installed on EACH virtualenv, you might as well install it in the site-packages directory? Just a thought.",0.1618299653758019,False,2,71 2009-01-12 04:05:35.690,Installing certain packages using virtualenv,"So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this? Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages'","The other option (one I've used) is to easy_install Django after you've created the virtual environment. This is easily scripted. The penalty you pay is waiting for Django installation in each of your virtual environments. I'm with Toby, though: Unless there's a compelling reason why you have to have a separate copy of Django in each virtual environment, you should just consider installing it in your main Python area, and allowing each virtual environment to use it from there.",0.0,False,2,71 2009-01-12 18:38:15.180,Python: import the containing package,"In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function? Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names... Is there a pythonic way to do this?","In Django, the file manage.py has from django.core.management import execute_manager, but execute_manager is not a module. It is a function within the __init__.py module of the management directory.",0.0814518047658113,False,3,72 2009-01-12 18:38:15.180,Python: import the containing package,"In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function? Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names... Is there a pythonic way to do this?","If the package is named testmod and your init file is therefore testmod/__init__.py and your module within the package is submod.py then from within submod.py file, you should just be able to say import testmod and use whatever you want that's defined in testmod.",0.3869120172231254,False,3,72 2009-01-12 18:38:15.180,Python: import the containing package,"In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function? Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names... Is there a pythonic way to do this?","This doesn't exactly answer your question, but I'm going to suggest that you move the function outside of the __init__.py file, and into another module inside that package. You can then easily import that function into your other module. If you want, you can have an import statement in the __init__.py file that will import that function (when the package is imported) as well.",0.9997979416121844,False,3,72 2009-01-12 21:11:44.310,How to implement a python REPL that nicely handles asynchronous output?,"I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using raw_input('> ') to get the input. On Unix-based systems, I also import readline to make things behave a little better. All this is working fine. The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The ""> "" string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something. This seems like it must be a solved problem. What's the proper way to do this? Also note that some of my users are Windows-based. TIA Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated!","I think you have 2 basic options: Synchronize your output (i.e. block until it comes back) Separate your input and your (asyncronous) output, perhaps in two separate columns.",-0.0679224682270276,False,1,73 2009-01-13 16:21:17.920,PIL vs RMagick/ruby-gd,"For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick and ruby-gd). From what I can gather PIL had better documentation (does ruby-gd even have a homepage?) and more features. Just wanted to hear a few opinions to help me decide. Thanks. Vince","PIL is a good library, use it. ImageMagic (what RMagick wraps) is a very heavy library that should be avoided if possible. Its good for doing local processing of images, say, a batch photo editor, but way too processor inefficient for common image manipulation tasks for web. EDIT: In response to the question, PIL supports drawing vector shapes. It can draw polygons, curves, lines, fills and text. I've used it in a project to produce rounded alpha corners to PNG images on the fly over the web. It essentially has most of the drawing features of GDI+ (in Windows) or GTK (in Gnome on Linux).",0.7408590612005881,False,1,74 2009-01-14 20:17:06.353,How are debug consoles implemented in Python?,"I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool. Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated!","You could try looking at the python debugger pdb. It's like gdb in how you use it, but implemented in pure python. Have a look for pdb.py in your python install directory.",0.4540544406412981,False,1,75 2009-01-14 22:57:53.610,How to make a wx Toolbar buttons larger?,"I've got a wx.Toolbar and I'd like to make the buttons larger. I've searched and can't seem to find any concrete documentation on how to do this. I'm also wondering how well this will translate across platforms; what will happen to the buttons and icons on OSX?","Doesn't the size of the toolbar adapts itself automatically to the size of the bitmap icons? I think if you want a bigger toolbar, you need bigger bitmaps.",0.2655860252697744,False,1,76 2009-01-15 13:21:14.040,How can I deploy a Perl/Python/Ruby script without installing an interpreter?,"I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name. This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them. Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer? Thought about web for a second but it would not work for business reasons.","""installing Perl on Windows would not be worth it for them"" Really? It's that complex? Python has a simple .MSI that neatly installs itself with no muss or fuss. A simple application program is just a few .py files, so, I don't see a big pain factor there. You know your customers best. I find that the following isn't so bad. And it's much easier to support, since your upgrades will just be a single .MSI with simple, easy-to-live with source. 1) double click this .MSI file to install Python (or Perl or whatever) 2) double click this other .MSI to install the good stuff",0.0,False,1,77 2009-01-15 22:58:46.447,How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?,"I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities. I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely. The problem is that I don't know where to start investigating how to do this. Let's say I have a script called: file_arranger.py What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts? edit: The first answer made me realize I forgot to include that this is a Win2k3 system.","When setting this up, please be careful to restrict access to the scripts that take some action on your web server. It is not sufficient to place them in a directory where you just don't publish the URL, because sooner or later somebody will find them. At the very least, put these scripts in a location that is password protected. You don't want just anybody out there on the internet being able to run your scripts.",0.0,False,2,78 2009-01-15 22:58:46.447,How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?,"I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities. I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely. The problem is that I don't know where to start investigating how to do this. Let's say I have a script called: file_arranger.py What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts? edit: The first answer made me realize I forgot to include that this is a Win2k3 system.","A simple cgi script (or set of scripts) is all you need to get started. The other answers have covered how to do this so I won't repeat it; instead, I will stress that using plain text will get you a long way. Just output the header (print(""Content-type: text/plain\n"") plus print adds its own newline to give you the needed blank line) and then run your normal program. This way, any normal output from your script gets sent to the browser and you don't have to worry about HTML, escaping, frameworks, anything. ""Do the simplest thing that could possibly work."" This is especially appropriate for non-interactive private administrative tasks like you describe, and lets you use identical programs from a shell with a minimum of fuss. Your driver, the page with the buttons, can be a static HTML file with single-button forms. Or even a list of links. To advance from there, look at the logging module (for example, sending INFO messages to the browser but not the command line, or easily categorizing messages by using different loggers, by configuring your handlers), and then start to consider template engines and frameworks. Don't output your own HTML and skip to using one of the many existing libraries—it'll save a ton of headache even spending a bit of extra time to learn the library. Or at the very least encapsulate your output by effectively writing your own mini-engine.",0.0453204071731508,False,2,78 2009-01-16 12:01:24.867,How to check if a file can be created inside given directory on MS XP/Vista?,"I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it. I have created directory for test purposes, let's call it C:\foo. I have following permissions to C:\foo: Traversing directory/Execute file Removing subfolders and files Removing Read permissions Change permissions Take ownership I don't have any of the following permissions to C:\foo: Full Control File creation Folder creation I have tried following approaches, so far: os.access('C:\foo', os.W_OK) == True st = os.stat('C:\foo') mode = st[stat.ST_MODE] mode & stat.S_IWRITE == True I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not. Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory? In brief - I want to check if current user has File creation and Folder creation permissions for given folder name. EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states: The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case. Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?' Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?","I wouldn't waste time and LOCs on checking for permissions. Ultimate test of file creation in Windows is the creation itself. Other factors may come into play (such as existing files (or worse, folders) with the same name, disk space, background processes. These conditions can even change between the time you make the initial check and the time you actually try to create your file. So, if I had a scenario like that, I would just design my method to not lose any data in case of failure, to go ahead and try to create my file, and offer the user an option to change the selected directory and try again if creation fails.",0.3869120172231254,False,2,79 2009-01-16 12:01:24.867,How to check if a file can be created inside given directory on MS XP/Vista?,"I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it. I have created directory for test purposes, let's call it C:\foo. I have following permissions to C:\foo: Traversing directory/Execute file Removing subfolders and files Removing Read permissions Change permissions Take ownership I don't have any of the following permissions to C:\foo: Full Control File creation Folder creation I have tried following approaches, so far: os.access('C:\foo', os.W_OK) == True st = os.stat('C:\foo') mode = st[stat.ST_MODE] mode & stat.S_IWRITE == True I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not. Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory? In brief - I want to check if current user has File creation and Folder creation permissions for given folder name. EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states: The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case. Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?' Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?","I recently wrote a App to pass a set of test to obtain the ISV status from Microsoft and I also add that condition. The way I understood it was that if the user is Least Priveledge then he won't have permission to write in the system folders. So I approached the problem the the way Ishmaeel described. I try to create the file and catch the exception then inform the user that he doesn't have permission to write files to that directory. In my understanding an Least-Priviledged user will not have the necessary permissions to write to those folders, if he has then he is not a Least-Priveledge user. Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%? In my opinion? Yes.",1.2,True,2,79 2009-01-16 12:33:20.120,Python Path,"I am installing active python, django. I really dont know how to set the python path in vista environment system. first of all will it work in vista.","Remember that in addition to setting PYTHONPATH in your system environment, you'll also want to assign DJANGO_SETTINGS_MODULE.",0.0,False,1,80 2009-01-20 03:43:14.223,Python/Twisted - Sending to a specific socket object?,"I have a ""manager"" process on a node, and several worker processes. The manager is the actual server who holds all of the connections to the clients. The manager accepts all incoming packets and puts them into a queue, and then the worker processes pull the packets out of the queue, process them, and generate a result. They send the result back to the manager (by putting them into another queue which is read by the manager), but here is where I get stuck: how do I send the result to a specific socket? When dealing with the processing of the packets on a single process, it's easy, because when you receive a packet you can reply to it by just grabbing the ""transport"" object in-context. But how would I do this with the method I'm using?","It sounds like you might need to keep a reference to the transport (or protocol) along with the bytes the just came in on that protocol in your 'event' object. That way responses that came in on a connection go out on the same connection. If things don't need to be processed serially perhaps you should think about setting up functors that can handle the data in parallel to remove the need for queueing. Just keep in mind that you will need to protect critical sections of your code. Edit: Judging from your other question about evaluating your server design it would seem that processing in parallel may not be possible for your situation, so my first suggestion stands.",1.2,True,1,81 2009-01-20 16:37:53.927,Python with Netbeans 6.5,"Can you give me some links or explain how to configure an existing python project onto Netbeans? I'm trying it these days and it continues to crash also code navigation doesn't work well and I've problems with debugging. Surely these problems are related to my low eperience about python and I need support also in trivial things as organizing source folders, imports ecc,, thank you very much. Valerio","Python support is in beta, and as someone who works with NB for a past 2 years, I can say that even a release versions are buggy and sometimes crashes. Early Ruby support was also very shaky.",0.3869120172231254,False,1,82 2009-01-21 07:14:19.397,Python - Hits per minute implementation?,"This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that? I was thinking of maybe summing a dictionary that uses the current second as a key, and when receiving a packet it increments that value by one, as well as setting the second+1 key above it to 0, but this just seems sloppy. Any ideas?","When you say the last minute, do you mean the exact last seconds or the last full minute from x:00 to x:59? The latter will be easier to implement and would probably give accurate results. You have one prev variable holding the value of the hits for the previous minute. Then you have a current value that increments every time there is a new hit. You return the value of prev to the users. At the change of the minute you swap prev with current and reset current. If you want higher analysis you could split the minute in 2 to 6 slices. You need a variable or list entry for every slice. Let's say you have 6 slices of 10 seconds. You also have an index variable pointing to the current slice (0..5). For every hit you increment a temp variable. When the slice is over, you replace the value of the indexed variable with the value of temp, reset temp and move the index forward. You return the sum of the slice variables to the users.",1.2,True,3,83 2009-01-21 07:14:19.397,Python - Hits per minute implementation?,"This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that? I was thinking of maybe summing a dictionary that uses the current second as a key, and when receiving a packet it increments that value by one, as well as setting the second+1 key above it to 0, but this just seems sloppy. Any ideas?","For what it's worth, your implementation above won't work if you don't receive a packet every second, as the next second entry won't necessarily be reset to 0. Either way, afaik the ""correct"" way to do this, ala logs analysis, is to keep a limited record of all the queries you receive. So just chuck the query, time received etc. into a database, and then simple database queries will give you the use over a minute, or any minute in the past. Not sure whether this is too heavyweight for you, though.",0.1352210990936997,False,3,83 2009-01-21 07:14:19.397,Python - Hits per minute implementation?,"This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that? I was thinking of maybe summing a dictionary that uses the current second as a key, and when receiving a packet it increments that value by one, as well as setting the second+1 key above it to 0, but this just seems sloppy. Any ideas?","A common pattern for solving this in other languages is to let the thing being measured simply increment an integer. Then you leave it to the listening client to determine intervals and frequencies. So you basically do not let the socket server know about stuff like ""minutes"", because that's a feature the observer calculates. Then you can also support multiple listeners with different interval resolution. I suppose you want some kind of ring-buffer structure to do the rolling logging.",0.3869120172231254,False,3,83 2009-01-21 19:40:34.663,How can I return system information in Python?,"Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc? Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment?","It looks like you want to get a lot more information than the standard Python library offers. If I were you, I would download the source code for 'ps' or 'top', or the Gnome/KDE version of the same, or any number of system monitoring/graphing programs which are more likely to have all the necessary Unix cross platform bits, see what they do, and then make the necessary native calls with ctypes. It's trivial to detect the platform. For example with ctypes you might try to load libc.so, if that throws an exception try to load 'msvcrt.dll' and so on. Not to mention simply checking the operating system's name with os.name. Then just delegate calls to your new cross-platform API to the appropriate platform-specific (sorry) implementation. When you're done, don't forget to upload the resulting package to pypi.",0.0582430451621389,False,1,84 2009-01-22 23:25:40.950,Organising a GUI application,"This is going to be a generic question. I am struggling in designing a GUI application, esp. with dealing with interactions between different parts. I don't know how I should deal with shared state. On one hand, shared state is bad, and things should be as explicit as possible. On the other hand, not having shared state introduces unwanted coupling between components. An example: I want my application to be extendable in an Emacs/Vim sort of way, via scripts. Clearly, some sort of shared state needs to be modified, so that the GUI will use it. My initial plan was having a global ""session"" that is accessible from everywhere, but I'm not so sure about it. One tricky use case is key bindings. I want the user to be able to specify custom keybindings from a script. Each keybinding maps to an arbitrary command, that receives the session as the only argument. Now, the editor component captures keypresses. It has to have access to the keymappings, which are per-session, so it needs access to the session. Is coupling the editor to the session a good idea? Other components will also need to access the keybindings, so the session now becomes shared and can be a singleton... Is there any good reading about designing GUI applications that goes beyond MVC? This is Python and wxPython, FWIW. [EDIT]: Added concrete usecase.","If you've looked at MVC you're probably moving in the right direction. MVC, MVP, Passive View, Supervising Controller. Those are all different ways, each with their own pros and cons, of accomplishing what you're after. I find that Passive View is the ""ideal"", but it causes you to introduce far too many widgets into your GUI interfaces (i.e. IInterface). In general I find that Supervising Controller is a good compromise.",0.2655860252697744,False,2,85 2009-01-22 23:25:40.950,Organising a GUI application,"This is going to be a generic question. I am struggling in designing a GUI application, esp. with dealing with interactions between different parts. I don't know how I should deal with shared state. On one hand, shared state is bad, and things should be as explicit as possible. On the other hand, not having shared state introduces unwanted coupling between components. An example: I want my application to be extendable in an Emacs/Vim sort of way, via scripts. Clearly, some sort of shared state needs to be modified, so that the GUI will use it. My initial plan was having a global ""session"" that is accessible from everywhere, but I'm not so sure about it. One tricky use case is key bindings. I want the user to be able to specify custom keybindings from a script. Each keybinding maps to an arbitrary command, that receives the session as the only argument. Now, the editor component captures keypresses. It has to have access to the keymappings, which are per-session, so it needs access to the session. Is coupling the editor to the session a good idea? Other components will also need to access the keybindings, so the session now becomes shared and can be a singleton... Is there any good reading about designing GUI applications that goes beyond MVC? This is Python and wxPython, FWIW. [EDIT]: Added concrete usecase.","In MVC, the Model stuff is the shared state of the information. The Control stuff is the shared state of the GUI control settings and responses to mouse-clicks and what-not. Your scripting angle can 1) Update the Model objects. This is good. The Control can be ""Observers"" of the model objects and the View be updated to reflect the observed changes. 2) Update the Control objects. This is not so good, but... The Control objects can then make appropriate changes to the Model and/or View. I'm not sure what the problem is with MVC. Could you provide a more detailed design example with specific issues or concerns?",0.1352210990936997,False,2,85 2009-01-23 16:16:33.017,"When printing an image, what determines how large it will appear on a page?","Using Python's Imaging Library I want to create a PNG file. I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page. Is the resolution encoded in the image? If so, how do I specify it? And even if it is, does this have any relevance when it goes to the printer?","Printers have various resolutions in which they print. If you select a print resolution of 200 DPI for instance (or if it's set as default in the printer driver), then a 200 pixel image should be one inch in size.",0.0814518047658113,False,4,86 2009-01-23 16:16:33.017,"When printing an image, what determines how large it will appear on a page?","Using Python's Imaging Library I want to create a PNG file. I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page. Is the resolution encoded in the image? If so, how do I specify it? And even if it is, does this have any relevance when it goes to the printer?","Much is going to depend on the software you're using to print. If you're placing the image in a Word document, it will scale according to the DPI, up to the width of your page. If you're putting it on a web page, the DPI will not matter at all.",0.0,False,4,86 2009-01-23 16:16:33.017,"When printing an image, what determines how large it will appear on a page?","Using Python's Imaging Library I want to create a PNG file. I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page. Is the resolution encoded in the image? If so, how do I specify it? And even if it is, does this have any relevance when it goes to the printer?","Both image print size and resolution are relevant to printing an image of a specific scale and quality. Bear in mind that if the image is then included with a desktop publishing workspace (Word, InDesign) or even a web page, the image is then subject to any specified resolution in the parent document -- this won't necessarily alter the relative scale of the image in the case of desktop publishing programs but will alter image quality. And yes, all images have a resolution property, which answers half your question - I don't know Python...",0.0814518047658113,False,4,86 2009-01-23 16:16:33.017,"When printing an image, what determines how large it will appear on a page?","Using Python's Imaging Library I want to create a PNG file. I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page. Is the resolution encoded in the image? If so, how do I specify it? And even if it is, does this have any relevance when it goes to the printer?","I found a very simple way to get dpi information into the png: im.save('myfile.png',dpi=[600,600]) Unfortunately I did not find this documented anywhere and had to dig into the PIL source code.",0.2401167094949473,False,4,86 2009-01-26 22:42:42.320,Can a lambda function call itself recursively in Python?,"A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?","If you were truly masochistic, you might be able to do it using C extensions, but this exceeds the capability of a lambda (unnamed, anonymous) functon. No. (for most values of no).",-0.0814518047658113,False,1,87 2009-01-28 13:39:54.740,Inventory Control Across Multiple Servers .. Ideas?,"We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout. Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously. See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have. Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two. The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented. Thanks in advance for any answers, and I hope that made sense .. I can elaborate.","I don't see the problem... You have an application running on one server that manages your database locally. There's no reason a remote server can't also talk to that database. Of course, if you don't have a database and are instead using a homegrown app to act as some sort of faux-database, I recommend that you refactor to use something sort of actual DB sooner rather than later.",0.0,False,3,88 2009-01-28 13:39:54.740,Inventory Control Across Multiple Servers .. Ideas?,"We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout. Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously. See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have. Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two. The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented. Thanks in advance for any answers, and I hope that made sense .. I can elaborate.","One possibility would be to expose a web service interface on your inventory management system that allows the transactions used by the web shopfront to be accessed remotely. With a reasonably secure VPN link or ssh tunnel type arrangement, the web shopfront could get stock levels, place orders or execute searches against the inventory system. Notes: You would still have to add a reasonable security layer to the inventory service in case the web shopfront was compromised. You would have to make sure your inventory management application and server was big enough to handle the load, or could be reasonably easily scaled so it could do so. Your SLA for the inventory application would need to be good enough to support the web shopfront. This probably means some sort of hot failover arrangement.",1.2,True,3,88 2009-01-28 13:39:54.740,Inventory Control Across Multiple Servers .. Ideas?,"We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout. Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously. See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have. Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two. The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented. Thanks in advance for any answers, and I hope that made sense .. I can elaborate.","I'm not sure if there is any one really good solution for your problem. I think the way you are doing it now works fine, but if you don't agree then I don't know what to tell you.",0.0,False,3,88 2009-01-29 18:05:22.420,Reversing a regular expression in Python,"I want to reverse a regular expression. I.e. given a regular expression, I want to produce any string that will match that regex. I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :) I'm using Python, so I'd like a Python library. To reiterate, I only want one string that will match the regex. Things like ""."" or "".*"" would make an infinite amount of strings match the regex, but I don't care about all options. I'm willing for this library to only work on a certain subset of regex.","Unless your regex is extremely simple (i.e. no stars or pluses), there will be infinitely many strings which match it. If your regex only involves concatenation and alternation, then you can expand each alternation into all of its possibilities, e.g. (foo|bar)(baz|quux) can be expanded into the list ['foobaz', 'fooquux', 'barbaz', 'barquux'].",0.2497086294969975,False,1,89 2009-01-30 18:21:13.493,What's a good way to keep track of class instance variables in Python?,"I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all? I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this? Edit: It appears I created some confusion with the term ""member variable."" I really mean instance variable, and I've edited my question accordingly.","First of all: class attributes, or instance attributes? Or both? =) Usually you just add instance attributes in __init__, and class attributes in the class definition, often before method definitions... which should probably cover 90% of use cases. If code adds attributes on the fly, it probably (hopefully :-) has good reasons for doing so... leveraging dynamic features, introspection, etc. Other than that, adding attributes this way is probably less common than you think.",1.2,True,5,90 2009-01-30 18:21:13.493,What's a good way to keep track of class instance variables in Python?,"I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all? I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this? Edit: It appears I created some confusion with the term ""member variable."" I really mean instance variable, and I've edited my question accordingly.","The easiest is to use an IDE. PyDev is a plugin for eclipse. I'm not a full on expert in all ways pythonic, but in general I define my class members right under the class definition in python, so if I add members, they're all relative. My personal opinion is that class members should be declared in one section, for this specific reason. Local scoped variables, otoh, should be defined closest to when they are used (except in C--which I believe still requires variables to be declared at the beginning of a method).",0.0,False,5,90 2009-01-30 18:21:13.493,What's a good way to keep track of class instance variables in Python?,"I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all? I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this? Edit: It appears I created some confusion with the term ""member variable."" I really mean instance variable, and I've edited my question accordingly.","This is a common concern I hear from many programmers who come from a C, C++, or other statically typed language where variables are pre-declared. In fact it was one of the biggest concerns we heard when we were persuading programmers at our organization to abandon C for high-level programs and use Python instead. In theory, yes you can add instance variables to an object at any time. Yes it can happen from typos, etc. In practice, it rarely results in a bug. When it does, the bugs are generally not hard to find. As long as your classes are not bloated (1000 lines is pretty huge!) and you have ample unit tests, you should rarely run in to a real problem. In case you do, it's easy to drop to a Python console at almost any time and inspect things as much as you wish.",0.0814518047658113,False,5,90 2009-01-30 18:21:13.493,What's a good way to keep track of class instance variables in Python?,"I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all? I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this? Edit: It appears I created some confusion with the term ""member variable."" I really mean instance variable, and I've edited my question accordingly.","Instance variables should be initialized in the class's __init__() method. (In general) If that's not possible. You can use __dict__ to get a dictionary of all instance variables of an object during runtime. If you really need to track this in documentation add a list of instance variables you are using into the docstring of the class.",0.1618299653758019,False,5,90 2009-01-30 18:21:13.493,What's a good way to keep track of class instance variables in Python?,"I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all? I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this? Edit: It appears I created some confusion with the term ""member variable."" I really mean instance variable, and I've edited my question accordingly.","I would say, the standard practice to avoid this is to not write classes where you can be 1000 lines away from anything! Seriously, that's way too much for just about any useful class, especially in a language that is as expressive as Python. Using more of what the Standard Library offers and abstracting away code into separate modules should help keeping your LOC count down. The largest classes in the standard library have well below 100 lines!",0.3869120172231254,False,5,90 2009-01-31 01:22:08.137,How to make python gracefully fail?,"I was just wondering how do you make python fail in a user defined way in all possible errors. For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item. If anyone can help me with this it would be greatly appreciated! Thanks a lot! Jason","all possible errors The other answers pretty much cover how to make your program gracefully fail, but I'd like to mention one thing -- You don't want to gracefully fail all errors. If you hide all your errors, you won't be shown those which signify that the logic of the program is wrong - namely errors you want to see. So while it's important to catch your exceptions, make sure you know exactly which exceptions are actually being caught.",0.1618299653758019,False,1,91 2009-02-01 03:37:44.480,Can I log into a web application automatically using a users windows logon?,"On the intranet at my part time job (not IT related) there are various web applications that we use that do not require logging in explicitly. We are required to login to Windows obviously, and that then authenticates us some how. I'm wondering how this is done? Without worrying about security TOO much, how would I go about authenticating a user to a web application, utilizing the windows login information? I'd be using Python (and Django). Are there limitations on how this can be achieved? For instance, would a specific browser be required? Would the application and intranet backend have to be hosted at the same location or at least have to communicate? Or is it simply getting the users Windows credentials, and passing that to the authentication software of the web application?","To the best of my knowledge the only browser that automatically passes your login credentials is Internet Explorer. To enable this feature select ""Enable Integrated Windows Authentication"" in the advanced Internet options dialog under the security section. This is usually enabled by default. The web server will have to have the Anonymous user permission removed from the web application and enable windows authentication option checked. Simply add the users you want to have access to the web application to the file/folder permissions. I have only tried this with IIS so I'm not sure if it will work on other web servers.",0.0,False,1,92 2009-02-05 04:51:24.623,Random name generator strategy - help me improve it,"I have a small project I am doing in Python using web.py. It's a name generator, using 4 ""parts"" of a name (firstname, middlename, anothername, surname). Each part of the name is a collection of entites in a MySQL databse (name_part (id, part, type_id), and name_part_type (id, description)). Basic stuff, I guess. My generator picks a random entry of each ""type"", and assembles a comical name. Right now, I am using select * from name_part where type_id=[something] order by rand() limit 1 to select a random entry of each type (so I also have 4 queries that run per pageview, I figured this was better than one fat query returning potentially hundreds of rows; if you have a suggestion for how to pull this off in one query w/o a sproc I'll listen). Obviously I want to make this more random. Actually, I want to give it better coverage, not necessarily randomness. I want to make sure it's using as many possibilities as possible. That's what I am asking in this question, what sorts of strategies can I use to give coverage over a large random sample? My idea, is to implement a counter column on each name_part, and increment it each time I use it. I would need some logic to then say like: ""get a name_part that is less than the highest ""counter"" for this ""name_part_type"", unless there are none then pick a random one"". I am not very good at SQL, is this kind of logic even possible? The only way I can think to do this would require up to 3 or 4 queries for each part of the name (so up to 12 queries per pageview). Can I get some input on my logic here? Am I overthinking it? This actually sounds ideal for a stored procedure... but can you guys at least help me solve how to do it without a sproc? (I don't know if I can even use a sproc with the built-in database stuff of web.py). I hope this isn't terribly dumb but thanks ahead of time. edit: Aside from my specific problem I am still curious if there are any alternate strategies I can use that may be better.","I agree with your intuition that using a stored procedure is the right way to go, but then, I almost always try to implement database stuff in the database. In your proc, I would introduce some kind of logic like say, there's only a 30% chance that returning the result will actually increment the counter. Just to increase the variability.",0.2012947653214861,False,1,93 2009-02-05 21:19:20.087,How to clear the interpreter console?,"Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do. Note: I'm running on Windows, so Ctrl+L doesn't work.","I am using Spyder (Python 2.7) and to clean the interpreter console I use either %clear that forces the command line to go to the top and I will not see the previous old commands. or I click ""option"" on the Console environment and select ""Restart kernel"" that removes everything.",0.0136046027467035,False,7,94 2009-02-05 21:19:20.087,How to clear the interpreter console?,"Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do. Note: I'm running on Windows, so Ctrl+L doesn't work.","Quickest and easiest way without a doubt is Ctrl+L. This is the same for OS X on the terminal.",0.3275988531455109,False,7,94 2009-02-05 21:19:20.087,How to clear the interpreter console?,"Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do. Note: I'm running on Windows, so Ctrl+L doesn't work.","If it is on mac, then a simple cmd + k should do the trick.",0.0272041704036547,False,7,94 2009-02-05 21:19:20.087,How to clear the interpreter console?,"Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do. Note: I'm running on Windows, so Ctrl+L doesn't work.",I found the simplest way is just to close the window and run a module/script to reopen the shell.,0.0136046027467035,False,7,94 2009-02-05 21:19:20.087,How to clear the interpreter console?,"Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do. Note: I'm running on Windows, so Ctrl+L doesn't work.","OK, so this is a much less technical answer, but I'm using the Python plugin for Notepad++ and it turns out you can just clear the console manually by right-clicking on it and clicking ""clear"". Hope this helps someone out there!",0.0136046027467035,False,7,94 2009-02-05 21:19:20.087,How to clear the interpreter console?,"Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do. Note: I'm running on Windows, so Ctrl+L doesn't work.","Use idle. It has many handy features. Ctrl+F6, for example, resets the console. Closing and opening the console are good ways to clear it.",0.0543681047732388,False,7,94 2009-02-05 21:19:20.087,How to clear the interpreter console?,"Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do. Note: I'm running on Windows, so Ctrl+L doesn't work.","just use this.. print '\n'*1000",0.0272041704036547,False,7,94 2009-02-07 00:27:40.520,how to search for specific file type with yahoo search API?,"Does anyone know if there is some parameter available for programmatic search on yahoo allowing to restrict results so only links to files of specific type will be returned (like PDF for example)? It's possible to do that in GUI, but how to make it happen through API? I'd very much appreciate a sample code in Python, but any other solutions might be helpful as well.","Thank you. I found myself that something like this works OK (file type is the first argument, and query is the second): format = sys.argv[1] query = "" "".join(sys.argv[2:]) srch = create_search(""Web"", app_id, query=query, format=format)",1.2,True,1,95 2009-02-07 16:30:31.217,Insert Command into Bash Shell,"Is there any way to inject a command into a bash prompt in Linux? I am working on a command history app - like the Ctrl+R lookup but different. I am using python for this. I will show a list of commands from history based on the user's search term - if the user presses enter, the app will execute the command and print the results. So far, so good. If the user chooses a command and then press the right or left key, I want to insert the command into the prompt - so that the user can edit the command before executing it. If you are on Linux, just fire up a bash console, press Ctrl+r, type cd(or something), and then press the right arrow key - the selected command will be shown at the prompt. This is the functionality I am looking for - but I want to know how to do that from within python.","You can do this, but only if the shell runs as a subprocess of your Python program; you can't feed content into the stdin of your parent process. (If you could, UNIX would have a host of related security issues when folks run processes with fewer privileges than the calling shell!) If you're familiar with how Expect allows passthrough to interactive subprocesses (with specific key sequences from the user or strings received from the child process triggering matches and sending control back to your program), the same thing can be done from Python with pexpect. Alternately, as another post mentioned, the curses module provides full control over the drawing of terminal displays -- which you'll want if this history menu is happening within the window rather than in a graphical (X11/win32) pop-up.",0.296905446847765,False,1,96 2009-02-07 23:18:03.840,"Python, SQLite and threading","I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP. So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. Then in the main thread start a CherryPy application that will query that SQLite database and serve the data. My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application? If I'd do a connection per thread to the database will I also be able to create/use an in memory database?","Depending on the application the DB could be a real overhead. If we are talking about volatile data, maybe you could skip the communication via DB completely and share the data between the data gathering process and the data serving process(es) via IPC. This is not an option if the data has to be persisted, of course.",0.0,False,4,97 2009-02-07 23:18:03.840,"Python, SQLite and threading","I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP. So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. Then in the main thread start a CherryPy application that will query that SQLite database and serve the data. My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application? If I'd do a connection per thread to the database will I also be able to create/use an in memory database?","""...create several threads that will gather data at a specified interval and cache that data locally into a sqlite database. Then in the main thread start a CherryPy app that will query that sqlite db and serve the data."" Don't waste a lot of time on threads. The things you're describing are simply OS processes. Just start ordinary processes to do gathering and run Cherry Py. You have no real use for concurrent threads in a single process for this. Gathering data at a specified interval -- when done with simple OS processes -- can be scheduled by the OS very simply. Cron, for example, does a great job of this. A CherryPy App, also, is an OS process, not a single thread of some larger process. Just use processes -- threads won't help you.",0.0679224682270276,False,4,97 2009-02-07 23:18:03.840,"Python, SQLite and threading","I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP. So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. Then in the main thread start a CherryPy application that will query that SQLite database and serve the data. My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application? If I'd do a connection per thread to the database will I also be able to create/use an in memory database?","Short answer: Don't use Sqlite3 in a threaded application. Sqlite3 databases scale well for size, but rather terribly for concurrency. You will be plagued with ""Database is locked"" errors. If you do, you will need a connection per thread, and you have to ensure that these connections clean up after themselves. This is traditionally handled using thread-local sessions, and is performed rather well (for example) using SQLAlchemy's ScopedSession. I would use this if I were you, even if you aren't using the SQLAlchemy ORM features.",1.2,True,4,97 2009-02-07 23:18:03.840,"Python, SQLite and threading","I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP. So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. Then in the main thread start a CherryPy application that will query that SQLite database and serve the data. My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application? If I'd do a connection per thread to the database will I also be able to create/use an in memory database?",Depending on the data rate sqlite could be exactly the correct way to do this. The entire database is locked for each write so you aren't going to scale to 1000s of simultaneous writes per second. But if you only have a few it is the safest way of assuring you don't overwrite each other.,0.0,False,4,97 2009-02-09 07:05:27.367,How to modify existing panels in Maya using MEL or Python?,"I've been writing tools in Maya for years using MEL and Python. I'd consider myself an expert in custom window/gui design in Maya except for one area; modifying existing panels and editors. Typically, I'm building tools that need totally custom UIs, so its customary for me to build them from scratch. However, recently I've found myself wanting to add some additional functionality to the layer editor in Maya. I've seen tutorials that explain how to do this, but now that I want to do it, I can't find any. Links to tutorials or a brief code snippet to get me started would be great. I just need to know how to find the layer editor/panel and, say, add a button or text field to it.","Have you tried searching ui item names in MEL files under maya installation directory? It should be one of the MEL scripts included, and from there you can just modify it.",1.2,True,1,98 2009-02-11 09:19:22.170,Outputting data a row at a time from mysql using sqlalchemy,"I want to fetch data from a mysql database using sqlalchemy and use the data in a different class.. Basically I fetch a row at a time, use the data, fetch another row, use the data and so on.. I am running into some problem doing this.. Basically, how do I output data a row at a time from mysql data?.. I have looked into all tutorials but they are not helping much.","Exactly what problems are you running into? You can simply iterate over the ResultProxy object: for row in conn_or_sess_or_engine.execute(selectable_obj_or_SQLstring): do_something_with(row)",0.2012947653214861,False,1,99 2009-02-11 16:11:44.397,Standard python interpreter has a vi command mode?,"I was working a bit in the python interpreter (python 2.4 on RHEL 5.3), and suddenly found myself in what seems to be a 'vi command mode'. That is, I can edit previous commands with typical vi key bindings, going left with h, deleting with x... I love it - the only thing is, I don't know how I got here (perhaps it's through one of the modules I've imported: pylab/matplotlib?). Can anyone shed some light on how to enable this mode in the interpreter?","For Mac OS X 10.10.3, python2.7, vi mode can be configured by placing bind -v in ~/.editrc. The last few paragraphs of the man page hint at this.",0.5457054096481145,False,1,100 2009-02-12 20:41:14.033,Granularity of Paradigm Mixing,"When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?","Different problems require different solutions, but it helps if you solve things the same way in the same layer. And varying to wildly will just confuse you and everyone else in the project. For C++, I've found that statically typed OOP (use zope.interface in Python) work well for higher-level parts (connecting, updating, signaling, etc) and functional stuff solves many lower-level problems (parsing, nuts 'n bolts data processing, etc) more nicely. And usually, a dynamically typed scripting system is good for selecting and configuring the specific app, game level, whatnot. This may be the language itself (i.e. Python) or something else (an xml-script engine + necessary system for dynamic links in C++).",0.0,False,4,101 2009-02-12 20:41:14.033,Granularity of Paradigm Mixing,"When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?","Mixing paradigms has an advantage of letting you express solutions in most natural and esy way. Which is very good thing when it help keeping your program logic smaller. For example, filtering a list by some criteria is several times simpler to express with functional solution compared to traditional loop. On the other hand, to get benefit from mixing two or more paradigms programmer should be reasonably fluent with all of them. So this is powerful tool that should be used with care.",0.1016881243684853,False,4,101 2009-02-12 20:41:14.033,Granularity of Paradigm Mixing,"When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?","I am not sure that I ever think about it like this. Once you start ""thinking in Ruby"" the multi-paradigms just merge into ... well, Ruby. Ruby is object-oriented, but I find that other things such as the functional aspect tend to mean that some of the ""traditional"" design patters present in OO languages are just simply not relevant. The iterator is a classic example ... iteration is something that is handled elegantly in Ruby and the heavy-weight OO iteration patterns no longer really apply. This seems to be true throughout the language.",0.2012947653214861,False,4,101 2009-02-12 20:41:14.033,Granularity of Paradigm Mixing,"When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?","Different paradigms mix in different ways. For example, Using OOP doesn't eliminate the use of subroutines and procedural code from an outside library. It merely moves the procedures around into a different place. It is impossible to purely program with one paradigm. You may think you have a single one in mind when you program, but that's your illusion. Your resultant code will land along the borders and within the bounds of many paradigms.",0.2012947653214861,False,4,101 2009-02-17 13:16:25.157,Python list serialization - fastest method,"I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest. Which is the fastest method, and why? Using import on a .py file that just contains the list assigned to a variable Using cPickle's load Some other method (perhaps numpy?) Also, how can one benchmark such things reliably? Addendum: measuring this reliably is difficult, because import is cached so it can't be executed multiple times in a test. The loading with pickle also gets faster after the first time probably because page-precaching by the OS. Loading 1 million numbers with cPickle takes 1.1 sec the first time run, and 0.2 sec on subsequent executions of the script. Intuitively I feel cPickle should be faster, but I'd appreciate numbers (this is quite a challenge to measure, I think). And yes, it's important for me that this performs quickly. Thanks","cPickle will be the fastest since it is saved in binary and no real python code has to be parsed. Other advantates are that it is more secure (since it does not execute commands) and you have no problems with setting $PYTHONPATH correctly.",0.0679224682270276,False,1,102 2009-02-17 14:50:22.530,How to re-use a reusable app in Django,"I am trying to create my first site in Django and as I'm looking for example apps out there to draw inspiration from, I constantly stumble upon a term called ""reusable apps"". I understand the concept of an app that is reusable easy enough, but the means of reusing an app in Django are quite lost for me. Few questions that are bugging me in the whole business are: What is the preferred way to re-use an existing Django app? Where do I put it and how do I reference it? From what I understand, the recommendation is to put it on your ""PYTHONPATH"", but that breaks as soon as I need to deploy my app to a remote location that I have limited access to (e.g. on a hosting service). So, if I develop my site on my local computer and intend to deploy it on an ISP where I only have ftp access, how do I re-use 3rd party Django apps so that if I deploy my site, the site keeps working (e.g. the only thing I can count on is that the service provider has Python 2.5 and Django 1.x installed)? How do I organize my Django project so that I could easily deploy it along with all of the reusable apps I want to use?","An old question, but here's what I do: If you're using a version control system (VCS), I suggest putting all of the reusable apps and libraries (including django) that your software needs in the VCS. If you don't want to put them directly under your project root, you can modify settings.py to add their location to sys.path. After that deployment is as simple as cloning or checking out the VCS repository to wherever you want to use it. This has two added benefits: Version mismatches; your software always uses the version that you tested it with, and not the version that was available at the time of deployment. If multiple people work on the project, nobody else has to deal with installing the dependencies. When it's time to update a component's version, update it in your VCS and then propagate the update to your deployments via it.",0.3869120172231254,False,1,103 2009-02-18 15:25:25.633,How to convert an integer to the shortest url-safe string in Python?,"I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python. The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.","If you are looking for a way to shorten the integer representation using base64, I think you need to look elsewhere. When you encode something with base64 it doesn't get shorter, in fact it gets longer. E.g. 11234 encoded with base64 would yield MTEyMzQ= When using base64 you have overlooked the fact that you are not converting just the digits (0-9) to a 64 character encoding. You are converting 3 bytes into 4 bytes so you are guaranteed your base64 encoded string would be 33.33% longer.",0.0543681047732388,False,2,104 2009-02-18 15:25:25.633,How to convert an integer to the shortest url-safe string in Python?,"I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python. The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.","Base64 takes 4 bytes/characters to encode 3 bytes and can only encode multiples of 3 bytes (and adds padding otherwise). So representing 4 bytes (your average int) in Base64 would take 8 bytes. Encoding the same 4 bytes in hex would also take 8 bytes. So you wouldn't gain anything for a single int.",0.1084157444430997,False,2,104 2009-02-19 19:50:27.033,Python: Am I missing something?,"I'm in the process of learning Python while implementing build scripts and such. And for the moment everything is working fine in that the scripts do what they need to do. But I keep having the feeling I'm missing something, such as ""The Python Way"". I know build scripts and glue scripts are not really the most exciting development work and may hardly be a candidate for revealing the true power of Python but I'd still like the opportunity to have my mind blown. I develop mostly in C# and I find that my Python code looks awfully similar in structure and style to a lot of my C# code. In other words I feel like I'm thinking in C# but writing in Python. Am I really missing something? (Note: I realize this isn't so much a programming question and it's quite broad and there may not be a definitive answer so mod me down into oblivion if you have to.)",I would suggest finding a personal python guru. Show them some of your code and have them review/rewrite it into idiomatic python. Thus will you be enlightened.,0.0,False,5,105 2009-02-19 19:50:27.033,Python: Am I missing something?,"I'm in the process of learning Python while implementing build scripts and such. And for the moment everything is working fine in that the scripts do what they need to do. But I keep having the feeling I'm missing something, such as ""The Python Way"". I know build scripts and glue scripts are not really the most exciting development work and may hardly be a candidate for revealing the true power of Python but I'd still like the opportunity to have my mind blown. I develop mostly in C# and I find that my Python code looks awfully similar in structure and style to a lot of my C# code. In other words I feel like I'm thinking in C# but writing in Python. Am I really missing something? (Note: I realize this isn't so much a programming question and it's quite broad and there may not be a definitive answer so mod me down into oblivion if you have to.)","Think like this: If you are writing too much for little work, something is wrong, this is not pythonic. Most Python code you will write is very simple and direct. Usually you don't need much work for anything simple. If you are writing too much, stop and think if there is a better way. (and this is how I learned many things in Python!)",0.1016881243684853,False,5,105 2009-02-19 19:50:27.033,Python: Am I missing something?,"I'm in the process of learning Python while implementing build scripts and such. And for the moment everything is working fine in that the scripts do what they need to do. But I keep having the feeling I'm missing something, such as ""The Python Way"". I know build scripts and glue scripts are not really the most exciting development work and may hardly be a candidate for revealing the true power of Python but I'd still like the opportunity to have my mind blown. I develop mostly in C# and I find that my Python code looks awfully similar in structure and style to a lot of my C# code. In other words I feel like I'm thinking in C# but writing in Python. Am I really missing something? (Note: I realize this isn't so much a programming question and it's quite broad and there may not be a definitive answer so mod me down into oblivion if you have to.)",Write some Python code and post it on SO for review and feedback whether it is pythonic.,0.0509761841073563,False,5,105 2009-02-19 19:50:27.033,Python: Am I missing something?,"I'm in the process of learning Python while implementing build scripts and such. And for the moment everything is working fine in that the scripts do what they need to do. But I keep having the feeling I'm missing something, such as ""The Python Way"". I know build scripts and glue scripts are not really the most exciting development work and may hardly be a candidate for revealing the true power of Python but I'd still like the opportunity to have my mind blown. I develop mostly in C# and I find that my Python code looks awfully similar in structure and style to a lot of my C# code. In other words I feel like I'm thinking in C# but writing in Python. Am I really missing something? (Note: I realize this isn't so much a programming question and it's quite broad and there may not be a definitive answer so mod me down into oblivion if you have to.)","To echo TLHOLADAY, read the standard library. That's where the ""pythonic"" stuff is. If you're not getting a good feel there, then read the source for sqlachemy or django or your project of choice.",0.0,False,5,105 2009-02-19 19:50:27.033,Python: Am I missing something?,"I'm in the process of learning Python while implementing build scripts and such. And for the moment everything is working fine in that the scripts do what they need to do. But I keep having the feeling I'm missing something, such as ""The Python Way"". I know build scripts and glue scripts are not really the most exciting development work and may hardly be a candidate for revealing the true power of Python but I'd still like the opportunity to have my mind blown. I develop mostly in C# and I find that my Python code looks awfully similar in structure and style to a lot of my C# code. In other words I feel like I'm thinking in C# but writing in Python. Am I really missing something? (Note: I realize this isn't so much a programming question and it's quite broad and there may not be a definitive answer so mod me down into oblivion if you have to.)","To add to the answers of Andrew Hare and Baishampayan Ghose... To learn the idiom of any language must involve reading code written in that idiom. I'm still learning the Python idiom, but I've been through this with other languages. I can read about list comprehensions, but the lightbulb only really comes on when you see such things in use and say, ""Wow! That's awesome! Two lines of code and it's crystal clear!"" So go find some pythonic code that you find interesting and start reading it and understanding it. The knowledge will stay in your head better if you see everything in the context of a working program.",0.0763815498574146,False,5,105 2009-02-20 16:04:25.480,Statistics with numpy,"I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice. Is there a simple way to do that using numpy?","In addition to df's answer, if you want to know the specific prices that are above the base prices, you can do: prices[prices > (1.10 * base_prices)]",0.1016881243684853,False,1,106 2009-02-21 19:39:59.540,Set up a scheduled job?,"I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to set this up? To clarify: I know I can set up a cron job to do this, but I'm curious if there is some feature in Django that provides this functionality. I'd like people to be able to deploy this app themselves without having to do much config (preferably zero). I've considered triggering these actions ""retroactively"" by simply checking if a job should have been run since the last time a request was sent to the site, but I'm hoping for something a bit cleaner.","I had something similar with your problem today. I didn't wanted to have it handled by the server trhough cron (and most of the libs were just cron helpers in the end). So i've created a scheduling module and attached it to the init . It's not the best approach, but it helps me to have all the code in a single place and with its execution related to the main app.",0.0340004944420038,False,1,107 2009-02-22 00:58:37.450,How do YOU deploy your WSGI application? (and why it is the best way),"Deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) Pure Python web server eg paste, cherrypy, Spawning, Twisted.web as 2 but with reverse proxy from nginx, apache2 etc, with good static file handling Conversion to other protocol such as FCGI with a bridge (eg Flup) and running in a conventional web server. More? I want to know how you do it, and why it is the best way to do it. I would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc. I will upvote any non-insane answer.","Apache+mod_wsgi, Simple, clean. (only four lines of webserver config), easy for other sysadimns to get their head around.",0.0453204071731508,False,4,108 2009-02-22 00:58:37.450,How do YOU deploy your WSGI application? (and why it is the best way),"Deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) Pure Python web server eg paste, cherrypy, Spawning, Twisted.web as 2 but with reverse proxy from nginx, apache2 etc, with good static file handling Conversion to other protocol such as FCGI with a bridge (eg Flup) and running in a conventional web server. More? I want to know how you do it, and why it is the best way to do it. I would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc. I will upvote any non-insane answer.","Apache httpd + mod_fcgid using web.py (which is a wsgi application). Works like a charm.",0.1352210990936997,False,4,108 2009-02-22 00:58:37.450,How do YOU deploy your WSGI application? (and why it is the best way),"Deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) Pure Python web server eg paste, cherrypy, Spawning, Twisted.web as 2 but with reverse proxy from nginx, apache2 etc, with good static file handling Conversion to other protocol such as FCGI with a bridge (eg Flup) and running in a conventional web server. More? I want to know how you do it, and why it is the best way to do it. I would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc. I will upvote any non-insane answer.","We are using pure Paste for some of our web services. It is easy to deploy (with our internal deployment mechanism; we're not using Paste Deploy or anything like that) and it is nice to minimize the difference between production systems and what's running on developers' workstations. Caveat: we don't expect low latency out of Paste itself because of the heavyweight nature of our requests. In some crude benchmarking we did we weren't getting fantastic results; it just ended up being moot due to the expense of our typical request handler. So far it has worked fine. Static data has been handled by completely separate (and somewhat ""organically"" grown) stacks, including the use of S3, Akamai, Apache and IIS, in various ways.",0.0453204071731508,False,4,108 2009-02-22 00:58:37.450,How do YOU deploy your WSGI application? (and why it is the best way),"Deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) Pure Python web server eg paste, cherrypy, Spawning, Twisted.web as 2 but with reverse proxy from nginx, apache2 etc, with good static file handling Conversion to other protocol such as FCGI with a bridge (eg Flup) and running in a conventional web server. More? I want to know how you do it, and why it is the best way to do it. I would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc. I will upvote any non-insane answer.","Nginx reverse proxy and static file sharing + XSendfile + uploadprogress_module. Nothing beats it for the purpose. On the WSGI side either Apache + mod_wsgi or cherrypy server. I like to use cherrypy wsgi server for applications on servers with less memory and less requests. Reasoning: I've done benchmarks with different tools for different popular solutions. I have more experience with lower level TCP/IP than web development, especially http implementations. I'm more confident that I can recognize a good http server than I can recognize a good web framework. I know Twisted much more than Django or Pylons. The http stack in Twisted is still not up to this but it will be there.",0.2655860252697744,False,4,108 2009-02-24 09:15:24.853,Python web programming,"Good morning. As the title indicates, I've got some questions about using python for web development. What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, *nix and win environment. My major concern when I last tried apache + mod_python + CherryPy was having to reload webserver to see the changes. Is it considered normal? For some reason cherrypy's autoreload didn't work at all. What is the best setup to deploy a working Python app to production and why? I'm now using lighttpd for my PHP web apps, but how would it do for python compared to nginx for example? Is it worth diving straight with a framework or to roll something simple of my own? I see that Django has got quite a lot of fans, but I'm thinking it would be overkill for my needs, so I've started looking into CherryPy. How exactly are Python apps served if I have to reload httpd to see the changes? Something like a permanent process spawning child processes, with all the major file includes happening on server start and then just lazy loading needed resources? Python supports multithreading, do I need to look into using that for a benefit when developing web apps? What would be that benefit and in what situations? Big thanks!","What is the best setup for a development environment? Doesn't much matter. We use Django, which runs in Windows and Unix nicely. For production, we use Apache in Red Hat. Is having to reload webserver to see the changes considered normal? Yes. Not clear why you'd want anything different. Web application software shouldn't be dynamic. Content yes. Software no. In Django, we develop without using a web server of any kind on our desktop. The Django ""runserver"" command reloads the application under most circumstances. For development, this works great. The times when it won't reload are when we've damaged things so badly that the app doesn't properly. What is the best setup to deploy a working Python app to production and why? ""Best"" is undefined in this context. Therefore, please provide some qualification for ""nest"" (e.g., ""fastest"", ""cheapest"", ""bluest"") Is it worth diving straight with a framework or to roll something simple of my own? Don't waste time rolling your own. We use Django because of the built-in admin page that we don't have to write or maintain. Saves mountains of work. How exactly are Python apps served if I have to reload httpd to see the changes? Two methods: Daemon - mod_wsgi or mod_fastcgi have a Python daemon process to which they connect. Change your software. Restart the daemon. Embedded - mod_wsgi or mod_python have an embedded mode in which the Python interpreter is inside the mod, inside Apache. You have to restart httpd to restart that embedded interpreter. Do I need to look into using multi-threaded? Yes and no. Yes you do need to be aware of this. No, you don't need to do very much. Apache and mod_wsgi and Django should handle this for you.",0.573727155831378,False,2,109 2009-02-24 09:15:24.853,Python web programming,"Good morning. As the title indicates, I've got some questions about using python for web development. What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, *nix and win environment. My major concern when I last tried apache + mod_python + CherryPy was having to reload webserver to see the changes. Is it considered normal? For some reason cherrypy's autoreload didn't work at all. What is the best setup to deploy a working Python app to production and why? I'm now using lighttpd for my PHP web apps, but how would it do for python compared to nginx for example? Is it worth diving straight with a framework or to roll something simple of my own? I see that Django has got quite a lot of fans, but I'm thinking it would be overkill for my needs, so I've started looking into CherryPy. How exactly are Python apps served if I have to reload httpd to see the changes? Something like a permanent process spawning child processes, with all the major file includes happening on server start and then just lazy loading needed resources? Python supports multithreading, do I need to look into using that for a benefit when developing web apps? What would be that benefit and in what situations? Big thanks!","When you use mod_python on a threaded Apache server (the default on Windows), CherryPy runs in the same process as Apache. In that case, you almost certainly don't want CP to restart the process. Solution: use mod_rewrite or mod_proxy so that CherryPy runs in its own process. Then you can autoreload to your heart's content. :)",0.0814518047658113,False,2,109 2009-02-25 15:39:46.823,What are good ways to upload bulk .csv data into a webapp using Django/Python?,"I have a very basic CSV file upload module working to bulk upload my user's data into my site. I process the CSV file in the backend with a python script that runs on crontab and then email the user the results of the bulk upload. This process works ok operationally, but my issue is with the format of the csv file. Are there good tools or even basic rules on how to accept different formats of the csv file? The user may have a different order of data columns, slightly different names for the column headers (I want the email column to be entitled ""Email"", but it may say ""Primary Email"", ""Email Address""), or missing additional data columns. Any good examples of CSV upload functionality that is very permissive and user friendly? Also, how do I tell the user to export as CSV data? I'm importing address book information, so this data often comes from Outlook, Thunderbird, other software packages that have address books. Are there other popular data formats that I should accept?","Look at csv module from stdlib. It contains presets for popualr CSV dialects like one produced by Excel. Reader class support field mapping and if file contains column header it coes not depend on column order. For more complex logic, like looking up several alternative names for a field, you'll need to write your own implementation.",0.0679224682270276,False,2,110 2009-02-25 15:39:46.823,What are good ways to upload bulk .csv data into a webapp using Django/Python?,"I have a very basic CSV file upload module working to bulk upload my user's data into my site. I process the CSV file in the backend with a python script that runs on crontab and then email the user the results of the bulk upload. This process works ok operationally, but my issue is with the format of the csv file. Are there good tools or even basic rules on how to accept different formats of the csv file? The user may have a different order of data columns, slightly different names for the column headers (I want the email column to be entitled ""Email"", but it may say ""Primary Email"", ""Email Address""), or missing additional data columns. Any good examples of CSV upload functionality that is very permissive and user friendly? Also, how do I tell the user to export as CSV data? I'm importing address book information, so this data often comes from Outlook, Thunderbird, other software packages that have address books. Are there other popular data formats that I should accept?","If you'll copy excel table into clipboard and then paste results into notepad, you'll notice that it's tab separated. I once used it to make bulk import from most of table editors by copy-pasting data from the editor into textarea on html page. You can use a background for textarea as a hint for number of columns and place your headers at the top suggesting the order for a user. Javascript will process pasted data and display them to the user immediately with simple prevalidation making it easy to fix an error and repaste. Then import button is clicked, data is validated again and import results are displayed. Unfortunately, I've never heard any feedback about whenever this was easy to use or not. Anyway, I still see it as an option when implementing bulk import.",0.0679224682270276,False,2,110 2009-02-26 06:44:48.240,Python - How to check if a file is used by another application?,"I want to open a file which is periodically written to by another application. This application cannot be modified. I'd therefore like to only open the file when I know it is not been written to by an other application. Is there a pythonic way to do this? Otherwise, how do I achieve this in Unix and Windows? edit: I'll try and clarify. Is there a way to check if the current file has been opened by another application? I'd like to start with this question. Whether those other application read/write is irrelevant for now. I realize it is probably OS dependent, so this may not really be python related right now.","One thing I've done is have python very temporarily rename the file. If we're able to rename it, then no other process is using it. I only tested this on Windows.",0.0,False,1,111 2009-02-28 19:55:21.193,Calling function defined in exe,"I need to know a way to call a function defined in the exe from a python script. I know how to call entire exe from py file.",Not sure if it is for windows. But you can treat an exe like a dll (if functions are exported). And they can be used by other programs.,0.1352210990936997,False,2,112 2009-02-28 19:55:21.193,Calling function defined in exe,"I need to know a way to call a function defined in the exe from a python script. I know how to call entire exe from py file.","Unless the said executable takes command line arguments which will specify which function to use, I don't think this is possible. With that being said, if you created the EXE, command line arguments are a good way to implement the functionality you're looking for.",0.0,False,2,112 2009-02-28 20:54:02.567,External classes in Python,"I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it? I'd like to eventually be able to share python programs.","If you want to store your RSS file in a different place use sys.append("""") and pout the module in that directory and use import or from import *",0.0,False,1,113 2009-03-01 03:40:26.020,How can I manually register distributions with pkg_resources?,"I'm trying to get a package installed on Google App Engine. The package relies rather extensively on pkg_resources, but there's no way to run setup.py on App Engine. There's no platform-specific code in the source, however, so it's no problem to just zip up the source and include those in the system path. And I've gotten a version of pkg_resources installed and working as well. The only problem is getting the package actually registered with pkg_resources so when it calls iter_entry_points it can find the appropriate plugins. What methods do I need to call to register modules on sys.path with all the appropriate metadata, and how do I figure out what that metadata needs to be?","On your local development system, run python setup.py bdist_egg, which will create a Zip archive with the necessary metadata included. Add it to your sys.path, and it should work properly.",0.0,False,2,114 2009-03-01 03:40:26.020,How can I manually register distributions with pkg_resources?,"I'm trying to get a package installed on Google App Engine. The package relies rather extensively on pkg_resources, but there's no way to run setup.py on App Engine. There's no platform-specific code in the source, however, so it's no problem to just zip up the source and include those in the system path. And I've gotten a version of pkg_resources installed and working as well. The only problem is getting the package actually registered with pkg_resources so when it calls iter_entry_points it can find the appropriate plugins. What methods do I need to call to register modules on sys.path with all the appropriate metadata, and how do I figure out what that metadata needs to be?","Create a setup.py for the package just as you would normally, and then use ""setup.py sdist --formats=zip"" to build your source zip. The built source zip will include an .egg-info metadata directory, which will then be findable by pkg_resources. Alternately, you can use bdist_egg for all your packages.",1.2,True,2,114 2009-03-02 20:24:41.853,How do you get default headers in a urllib2 Request?,"I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer. However, other ""standard"" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the full set of HTTP headers), and can't figure out how. any pointers? in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?","see urllib2.py:do_request (line 1044 (1067)) and urllib2.py:do_open (line 1073) (line 293) self.addheaders = [('User-agent', client_version)] (only 'User-agent' added)",0.0,False,1,115 2009-03-05 03:18:42.560,Discovering public IP programmatically,"I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results) Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it? P.S. I'm planning on writing a short python script to do it","Here are a few public services that support IPv4 and IPv6: curl http://icanhazip.com curl http://www.trackip.net/ip curl https://ipapi.co/ip curl http://api6.ipify.org curl http://www.cloudflare.com/cdn-cgi/trace curl http://checkip.dns.he.net The following seem to support only IPv4 at this time: curl http://bot.whatismyipaddress.com curl http://checkip.dyndns.org curl http://ifconfig.me curl http://ip-api.com curl http://api.infoip.io/ip It's easy to make an HTTP call programmatically. So all should be relatively easy to use, and you can try multiple different URLs in case one fails.",0.0255046717588776,False,3,116 2009-03-05 03:18:42.560,Discovering public IP programmatically,"I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results) Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it? P.S. I'm planning on writing a short python script to do it","Your simplest way may be to ask some server on the outside of your network. One thing to keep in mind is that different destinations may see a different address for you. The router may be multihomed. And really that's just where problems begin.",0.0763815498574146,False,3,116 2009-03-05 03:18:42.560,Discovering public IP programmatically,"I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results) Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it? P.S. I'm planning on writing a short python script to do it",If the network has an UpNp server running on the gateway you are able to talk to the gateway and ask it for your outside IP address.,0.0763815498574146,False,3,116 2009-03-06 16:11:46.483,Tools to ease executing raw SQL with Django ORM,"I often need to execute custom sql queries in django, and manually converting query results into objects every time is kinda painful. I wonder how fellow Slackers deal with this. Maybe someone had written some kind of a library to help dealing with custom SQL in Django?","Since the issue is ""manually converting query results into objects,"" the simplest solution is often to see if your custom SQL can fit into an ORM .extra() call rather than being a pure-SQL query. Often it can, and then you let the ORM do all the work of building up objects as usual.",1.2,True,1,117 2009-03-08 04:44:41.143,"For my app, how many threads would be optimal?","I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.","It's usually simpler to make multiple concurrent processes. Simply use subprocess to create as many Popens as you feel it necessary to run concurrently. There's no ""optimal"" number. Generally, when you run just one crawler, your PC spends a lot of time waiting. How much? Hard to say. When you're running some small number of concurrent crawlers, you'll see that they take about the same amount of time as one. Your CPU switches among the various processes, filling up the wait time on one with work on the others. You you run some larger number, you see that the overall elapsed time is longer because there's now more to do than your CPU can manage. So the overall process takes longer. You can create a graph that shows how the process scales. Based on this you can balance the number of processes and your desirable elapsed time. Think of it this way. 1 crawler does it's job in 1 minute. 100 pages done serially could take a 100 minutes. 100 crawlers concurrently might take on hour. Let's say that 25 crawlers finishes the job in 50 minutes. You don't know what's optimal until you run various combinations and compare the results.",0.1731644579931097,False,3,118 2009-03-08 04:44:41.143,"For my app, how many threads would be optimal?","I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.","One thing you should keep in mind is that some servers may interpret too many concurrent requests from the same IP address as a DoS attack and abort connections or return error pages for requests that would otherwise succeed. So it might be a good idea to limit the number of concurrent requests to the same server to a relatively low number (5 should be on the safe side).",0.0582430451621389,False,3,118 2009-03-08 04:44:41.143,"For my app, how many threads would be optimal?","I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.","You will probably find your application is bandwidth limited not CPU or I/O limited. As such, add as many as you like until performance begins to degrade. You may come up against other limits depending on your network setup. Like if you're behind an ADSL router, there will be a limit on the number of concurrent NAT sessions, which may impact making too many HTTP requests at once. Make too many and your provider may treat you as being infected by a virus or the like. There's also the issue of how many requests the server you're crawling can handle and how much of a load you want to put on it. I wrote a crawler once that used just one thread. It took about a day to process all the information I wanted at about one page every two seconds. I could've done it faster but I figured this was less of a burden for the server. So really theres no hard and fast answer. Assuming a 1-5 megabit connection I'd say you could easily have up to 20-30 threads without any problems.",1.2,True,3,118 2009-03-09 09:57:36.500,"Is there a way to configure the Application Pool's ""Idle timeout"" in web.config?","I know one can set the session timeout. But, if the application itself has received no requests for a given period of time, IIS shuts down the application. This behavior is configurable in the IIS management console, and I know how to do this. Still, I wonder if it is possible to configure this in web.config.","Not in IIS 6. In IIS 6, Application Pools are controlled by Worker Processes, which map to a Request Queue handled by HTTP.sys. HTTP.sys handles the communication with the WWW Server to determine when to start and stop Worker Processes. Since IIS 6 was created before .Net, there's no communication hooks between .Net and the low-level http handlers. ASP.net is implimented as an ISAPI filter, which is loaded by the Worker Process itself. You have a chicken-before-the-egg issue if you are looking at the web.config controlling a worker process. This is primarily why MS did the major re-write of IIS 7 which integrates .Net through the entire request life-cycle, not just the ISAPI filter portion.",1.2,True,1,119 2009-03-09 15:48:55.827,How do I find the Windows common application data folder using Python?,"I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?","You can access all of your OS environment variables using the os.environ dictionary in the os module. Choosing which key to use from that dictionary could be tricky, though. In particular, you should remain aware of internationalized (i.e., non-English) versions of Windows when using these paths. os.environ['ALLUSERSPROFILE'] should give you the root directory for all users on the computer, but after that be careful not to hard code subdirectory names like ""Application Data,"" because these directories don't exist on non-English versions of Windows. For that matter, you may want to do some research on what versions of Windows you can expect to have the ALLUSERSPROFILE environment variable set (I don't know myself -- it may be universal). My XP machine here has a COMMONAPPDATA environment variable which points to the All Users\Application Data folder, but my Win2K3 system does not have this environment variable.",0.2012947653214861,False,1,120 2009-03-09 21:58:14.723,Python equivalent to java.util.SortedSet?,"Does anybody know if Python has an equivalent to Java's SortedSet interface? Heres what I'm looking for: lets say I have an object of type foo, and I know how to compare two objects of type foo to see whether foo1 is ""greater than"" or ""less than"" foo2. I want a way of storing many objects of type foo in a list L, so that whenever I traverse the list L, I get the objects in order, according to the comparison method I define. Edit: I guess I can use a dictionary or a list and sort() it every time I modify it, but is this the best way?","Do you have the possibility of using Jython? I just mention it because using TreeMap, TreeSet, etc. is trivial. Also if you're coming from a Java background and you want to head in a Pythonic direction Jython is wonderful for making the transition easier. Though I recognise that use of TreeSet in this case would not be part of such a ""transition"". For Jython superusers I have a question myself: the blist package can't be imported because it uses a C file which must be imported. But would there be any advantage of using blist instead of TreeSet? Can we generally assume the JVM uses algorithms which are essentially as good as those of CPython stuff?",0.0,False,1,121 2009-03-11 02:32:55.053,Viewing all defined variables,"I'm currently working on a computation in python shell. What I want to have is Matlab style listout where you can see all the variables that have been defined up to a point (so I know which names I've used, their values and such). Is there a way, and how can I do that?","globals(), locals(), vars(), and dir() may all help you in what you want.",0.573727155831378,False,3,122 2009-03-11 02:32:55.053,Viewing all defined variables,"I'm currently working on a computation in python shell. What I want to have is Matlab style listout where you can see all the variables that have been defined up to a point (so I know which names I've used, their values and such). Is there a way, and how can I do that?","In my Python 2.7 interpreter, the same whos command that exists in MATLAB exists in Python. It shows the same details as the MATLAB analog (variable name, type, and value/data). Note that in the Python interpreter, whos lists all variables in the ""interactive namespace"".",0.2012947653214861,False,3,122 2009-03-11 02:32:55.053,Viewing all defined variables,"I'm currently working on a computation in python shell. What I want to have is Matlab style listout where you can see all the variables that have been defined up to a point (so I know which names I've used, their values and such). Is there a way, and how can I do that?","A few things you could use: dir() will give you the list of in scope variables: globals() will give you a dictionary of global variables locals() will give you a dictionary of local variables",1.0,False,3,122 2009-03-13 00:09:14.370,Email integration,"I was wondering if someone could help me out. In some web application, the app will send out emails, say when a new message has been posted. Then instead of signing into the application to post a reply you can just simply reply to the email and it will automatically update the web app with your response. My question is, how is this done and what is it called? Thanks","Generally: 1) Set up a dedicated email account for the purpose. 2) Have a programm monitor the mailbox (let's say fetchmail, since that's what I do). 3) When an email arrives at the account, fetchmail downloads the email, writes it to disk, and calls script or program you have written with the email file as an argument. 4) Your script or program parses the email and takes an appropriate action. The part that's usually mysterious to people is the fetchmail part (#2). Specifically on Mail Servers (iff you control the mailserver enough to redirect emails to scripts): 1-3) Configure an address to be piped to a script you have written. 4) Same as above.",0.4431875092007125,False,1,123 2009-03-16 08:22:52.843,Directory checksum with python?,"So I'm in the middle of web-based filesystem abstraction layer development. Just like file browser, except it has some extra features like freaky permissions etc. I would like users to be notified somehow about directory changes. So, i.e. when someone uploads a new file via FTP, certain users should get a proper message. It is not required for the message to be extra detailed, I don't really need to show the exact resource changed. The parent directory name should be enough. What approach would you recommend?","A simple approach would be to monitor/check the last modification date of the working directory (using os.stat() for example). Whenever a file in a directory is modified, the working directory's (the directory the file is in) last modification date changes as well. At least this works on the filesystems I am working on (ufs, ext3). I'm not sure if all filesystems do it this way.",0.0,False,1,124 2009-03-17 01:33:18.047,How to unlock an sqlite3 db?,"OMG! What an apparent problem... my django based scripts have locked my sqlite db... Does anyone know how to fix?","Your database is locked because you have a transaction running somewhere. Stop all your Django apps. If necessary, reboot. It's also remotely possible that you crashed a SQLite client in the middle of a transaction and the file lock was left in place.",1.2,True,1,125 2009-03-23 18:57:43.417,Examples for string find in Python,"I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.","if x is a string and you search for y which also a string their is two cases : case 1: y is exist in x so x.find(y) = the index (the position) of the y in x . case 2: y is not exist so x.find (y) = -1 this mean y is not found in x.",0.0,False,1,126 2009-03-24 11:34:34.207,How do I notify a process of an SQLite database change done in a different process?,"Let's say I have two or more processes dealing with an SQLite database - a ""player"" process and many ""editor"" processes. The ""player"" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database. An ""editor"" process is any editor for that database: it changes the database constantly. Now I want the player to reflect the editing changes quickly. I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes. I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size. I am thinking about using a log table and triggers, but I wonder if there is a simpler method.","I think in that case, I would make a process to manage the database read/writes. Each editor that want to make some modifications to the database makes a call to this proccess, be it through IPC or network, or whatever method. This process can then notify the player of a change in the database. The player, when he wants to retrieve some data should make a request of the data it wants to the process managing the database. (Or the db process tells it what it needs, when it notifies of a change, so no request from the player needed) Doing this will have the advantage of having only one process accessing the SQLite DB, so no locking or concurrency issues on the database.",0.1016881243684853,False,5,127 2009-03-24 11:34:34.207,How do I notify a process of an SQLite database change done in a different process?,"Let's say I have two or more processes dealing with an SQLite database - a ""player"" process and many ""editor"" processes. The ""player"" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database. An ""editor"" process is any editor for that database: it changes the database constantly. Now I want the player to reflect the editing changes quickly. I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes. I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size. I am thinking about using a log table and triggers, but I wonder if there is a simpler method.","A relational database is not your best first choice for this. Why? You want all of your editors to pass changes to your player. Your player is -- effectively -- a server for all those editors. Your player needs multiple open connections. It must listen to all those connections for changes. It must display those changes. If the changes are really large, you can move to a hybrid solution where the editors persist the changes and notify the player. Either way, the editors must notify they player that they have a change. It's much, much simpler than the player trying to discover changes in a database. A better design is a server which accepts messages from the editors, persists them, and notifies the player. This server is neither editor nor player, but merely a broker that assures that all the messages are handled. It accepts connections from editors and players. It manages the database. There are two implementations. Server IS the player. Server is separate from the player. The design of server doesn't change -- only the protocol. When server is the player, then server calls the player objects directly. When server is separate from the player, then the server writes to the player's socket. When the player is part of the server, player objects are invoked directly when a message is received from an editor. When the player is separate, a small reader collects the messages from a socket and calls the player objects. The player connects to the server and then waits for a stream of information. This can either be input from the editors or references to data that the server persisted in the database. If your message traffic is small enough so that network latency is not a problem, editor sends all the data to the server/player. If message traffic is too large, then the editor writes to a database and sends a message with just a database FK to the server/player. Please clarify ""If the editor crashes while notifying, the player is permanently messed up"" in your question. This sounds like a poor design for the player service. It can't be ""permanently messed up"" unless it's not getting state from the various editors. If it's getting state from the editors (but attempting to mirror that state, for example) then you should consider a design where the player simply gets state from the editor and cannot get ""permanently messed up"".",1.2,True,5,127 2009-03-24 11:34:34.207,How do I notify a process of an SQLite database change done in a different process?,"Let's say I have two or more processes dealing with an SQLite database - a ""player"" process and many ""editor"" processes. The ""player"" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database. An ""editor"" process is any editor for that database: it changes the database constantly. Now I want the player to reflect the editing changes quickly. I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes. I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size. I am thinking about using a log table and triggers, but I wonder if there is a simpler method.",Just open a socket between the two processes and have the editor tell all the players about the update.,0.1016881243684853,False,5,127 2009-03-24 11:34:34.207,How do I notify a process of an SQLite database change done in a different process?,"Let's say I have two or more processes dealing with an SQLite database - a ""player"" process and many ""editor"" processes. The ""player"" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database. An ""editor"" process is any editor for that database: it changes the database constantly. Now I want the player to reflect the editing changes quickly. I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes. I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size. I am thinking about using a log table and triggers, but I wonder if there is a simpler method.","How many editor processes (why processes?), and how often do you expect updates? This doesn't sound like a good design, especially not considering sqlite really isn't too happy about multiple concurrent accesses to the database. If multiple processes makes sense and you want persistence, it would probably be smarter to have the editors notify your player via sockets, pipes, shared memory or the like and then have the player (aka server process) do the persisting.",0.0509761841073563,False,5,127 2009-03-24 11:34:34.207,How do I notify a process of an SQLite database change done in a different process?,"Let's say I have two or more processes dealing with an SQLite database - a ""player"" process and many ""editor"" processes. The ""player"" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database. An ""editor"" process is any editor for that database: it changes the database constantly. Now I want the player to reflect the editing changes quickly. I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes. I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size. I am thinking about using a log table and triggers, but I wonder if there is a simpler method.","If it's on the same machine, the simplest way would be to have named pipe, ""player"" with blocking read() and ""editors"" putting a token in pipe whenever they modify DB.",0.1016881243684853,False,5,127 2009-03-25 04:23:52.267,How do I tell which Python interpreter I'm using?,"I am using Python 2.5.2. How can I tell whether it is CPython or IronPython or Jython? Another question: how can I use a DLL developed in VB.NET in my project?","If you are typing ""python"" to launch it, it is probably CPython. IronPython's executable name is ""ipy"".",0.3153999413393242,False,1,128 2009-03-26 01:19:41.687,How to re import an updated package while in Python Interpreter?,"I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.","So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me. Yes, just saying import again gives you the existing copy of the module from sys.modules. You can say reload(module) to update sys.modules and get a new copy of that single module, but if any other modules have a reference to the original module or any object from the original module, they will keep their old references and Very Confusing Things will happen. So if you've got a module a, which depends on module b, and b changes, you have to ‘reload b’ followed by ‘reload a’. If you've got two modules which depend on each other, which is extremely common when those modules are part of the same package, you can't reload them both: if you reload p.a it'll get a reference to the old p.b, and vice versa. The only way to do it is to unload them both at once by deleting their items from sys.modules, before importing them again. This is icky and has some practical pitfalls to do with modules entries being None as a failed-relative-import marker. And if you've got a module which passes references to its objects to system modules — for example it registers a codec, or adds a warnings handler — you're stuck; you can't reload the system module without confusing the rest of the Python environment. In summary: for all but the simplest case of one self-contained module being loaded by one standalone script, reload() is very tricky to get right; if, as you imply, you are using a ‘package’, you will probably be better off continuing to cycle the interpreter.",0.9980046621516976,False,1,129 2009-03-26 13:01:52.357,"In Python, how do I take a list and reduce it to a list of duplicates?","I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates. Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions? EDIT: Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.","the solutions based on 'set' have a small drawback, namely they only work for hashable objects. the solution based on itertools.groupby on the other hand works for all comparable objects (e.g.: dictionaries and lists).",0.0,False,1,130 2009-04-01 05:44:36.447,How do I schedule a process' termination?,"I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?","One idea: Save the process's PID (returned by fork() in your child process) to a file, then either schedule a cron job to kill it or kill it manually, reading the PID from the file. Another option: Create a shell script wrapper that automatically kills and restarts the process. Same as above, but you can keep the PID in memory, sleep for as long as you need, kill the process, then loop.",0.0,False,1,131 2009-04-02 06:35:38.017,Python SAX parser says XML file is not well-formed,"I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do I fix it? Edit: I think I've found the problem. My character data contains ""<"" and "">"" characters, presumably from html tags. After being parsed, these are converted to ""<"" and "">"" characters, which seems to bother the SAX parser. Is there any way to prevent this from happening?","I would suggest putting those tags back in and making sure it still works. Then, if you want to take them out, do it one at a time until it breaks. However, I question the wisdom of taking them out. If it's your XML file, you should understand it better. If it's a third-party XML file, you really shouldn't be fiddling with it (until you understand it better :-).",0.2012947653214861,False,3,132 2009-04-02 06:35:38.017,Python SAX parser says XML file is not well-formed,"I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do I fix it? Edit: I think I've found the problem. My character data contains ""<"" and "">"" characters, presumably from html tags. After being parsed, these are converted to ""<"" and "">"" characters, which seems to bother the SAX parser. Is there any way to prevent this from happening?","I would second recommendation to try to parse it using another XML parser. That should give an indication as to whether it's the document that's wrong, or parser. Also, the actual error message might be useful. One fairly common problem for example is that the xml declaration (if one is used, it's optional) must be the very first thing -- not even whitespace is allowed before it.",0.0,False,3,132 2009-04-02 06:35:38.017,Python SAX parser says XML file is not well-formed,"I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do I fix it? Edit: I think I've found the problem. My character data contains ""<"" and "">"" characters, presumably from html tags. After being parsed, these are converted to ""<"" and "">"" characters, which seems to bother the SAX parser. Is there any way to prevent this from happening?","You could load it into Firefox, if you don't have an XML editor. Firefox shows you the error.",0.0,False,3,132 2009-04-02 11:54:59.983,Import an existing python project to XCode,"I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository. Other developers are working on the project not using XCode - They won't mind if I add a project file or something, but they will mind if I have to reorganise the whole thing.","There are no special facilities for working with non-Cocoa Python projects with Xcode. Therefore, you probably just want to create a project with the ""Empty Project"" template (under ""Other"") and just drag in your source code. For convenience, you may want to set up an executable in the project. You can do this by ctrl/right-clicking in the project source list and choosing ""Add"" > ""New Custom Executable..."". You can also add a target, although I'm not sure what this would buy you.",0.1016881243684853,False,1,133 2009-04-05 16:07:30.077,How can you make a vote-up-down button like in Stackoverflow?,"Problems how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease how to save the action af an user to an variable NumberOfVotesOfQuestionID I am not sure whether I should use database or not for the variable. However, I know that there is an easier way too to save the number of votes. How can you solve those problems? [edit] The server-side programming language is Python.","You create the buttons, which can be links or images or whatever. Now hook a JavaScript function up to each button's click event. On clicking, the function fires and Sends a request to the server code that says, more or less, +1 or -1. Server code takes over. This will vary wildly depending on what framework you use (or don't) and a bunch of other things. Code connects to the database and runs a query to +1 or -1 the score. How this happens will vary wildly depending on your database design, but it'll be something like UPDATE posts SET score=score+1 WHERE score_id={{insert id here}};. Depending on what the database says, the server returns a success code or a failure code as the AJAX request response. Response gets sent to AJAX, asynchronously. The JS response function updates the score if it's a success code, displays an error if it's a failure. You can store the code in a variable, but this is complicated and depends on how well you know the semantics of your code's runtime environment. It eventually needs to be pushed to persistent storage anyway, so using the database 100% is a good initial solution. When the time for optimizing performance comes, there are enough software in the world to cache database queries to make you feel woozy so it's not that big a deal.",0.296905446847765,False,1,134 2009-04-05 23:34:32.857,Help Me Figure Out A Random Scheduling Algorithm using Python and PostgreSQL,"I am trying to do the schedule for the upcoming season for my simulation baseball team. I have an existing Postgresql database that contains the old schedule. There are 648 rows in the database: 27 weeks of series for 24 teams. The problem is that the schedule has gotten predictable and allows teams to know in advance about weak parts of their schedule. What I want to do is take the existing schedule and randomize it. That way teams are still playing each other the proper number of times but not in the same order as before. There is one rule that has been tripping me up: each team can only play one home and one road series PER week. I had been fooling around with SELECT statements based on ORDER BY RANDOM() but I haven't figured out how to make sure a team only has one home and one road series per week. Now, I could do this in PHP (which is the language I am most comfortable with) but I am trying to make the shift to Python so I'm not sure how to get this done in Python. I know that Python doesn't seem to handle two dimensional arrays very well. Any help would be greatly appreciated.","Have you considered keeping your same ""schedule"", and just shuffling the teams? Generating a schedule where everyone plays each other the proper number of times is possible, but if you already have such a schedule then it's much easier to just shuffle the teams. You could keep your current table, but replace each team in it with an id (0-23, or A-X, or whatever), then randomly generate into another table where you assign each team to each id (0 = TeamJoe, 1 = TeamBob, etc). Then when it's time to shuffle again next year, just regenerate that mapping table. Not sure if this answers the question the way you want, but is probably what I would go with (and is actually how I do it on my fantasy football website).",0.2655860252697744,False,2,135 2009-04-05 23:34:32.857,Help Me Figure Out A Random Scheduling Algorithm using Python and PostgreSQL,"I am trying to do the schedule for the upcoming season for my simulation baseball team. I have an existing Postgresql database that contains the old schedule. There are 648 rows in the database: 27 weeks of series for 24 teams. The problem is that the schedule has gotten predictable and allows teams to know in advance about weak parts of their schedule. What I want to do is take the existing schedule and randomize it. That way teams are still playing each other the proper number of times but not in the same order as before. There is one rule that has been tripping me up: each team can only play one home and one road series PER week. I had been fooling around with SELECT statements based on ORDER BY RANDOM() but I haven't figured out how to make sure a team only has one home and one road series per week. Now, I could do this in PHP (which is the language I am most comfortable with) but I am trying to make the shift to Python so I'm not sure how to get this done in Python. I know that Python doesn't seem to handle two dimensional arrays very well. Any help would be greatly appreciated.","I'm not sure I fully understand the problem, but here is how I would do it: 1. create a complete list of matches that need to happen 2. iterate over the weeks, selecting which match needs to happen in this week. You can use Python lists to represent the matches that still need to happen, and, for each week, the matches that are happening in this week. In step 2, selecting a match to happen would work this way: a. use random.choice to select a random match to happen. b. determine which team has a home round for this match, using random.choice([1,2]) (if it could have been a home round for either team) c. temporarily remove all matches that get blocked by this selection. a match is blocked if one of its teams has already two matches in the week, or if both teams already have a home match in this week, or if both teams already have a road match in this week. d. when there are no available matches anymore for a week, proceed to the next week, readding all the matches that got blocked for the previous week.",0.1352210990936997,False,2,135 2009-04-07 00:39:25.627,Import XML into SQL database,"I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way to do this? I know this ability is built into MySQL 6.0, but that is not an option right now because it is an alpha development release. Also, if I have to do any scripting I would prefer to use Python because that's what I am most familiar with. Thanks.","It may be a common task, but maybe 20GB isn't as common with MySQL as it is with SQL Server. I've done this using SQL Server Integration Services and a bit of custom code. Whether you need either of those depends on what you need to do with 20GB of XML in a database. Is it going to be a single column of a single row of a table? One row per child element? SQL Server has an XML datatype if you simply want to store the XML as XML. This type allows you to do queries using XQuery, allows you to create XML indexes over the XML, and allows the XML column to be ""strongly-typed"" by referring it to a set of XML schemas, which you store in the database.",0.0,False,1,136 2009-04-07 08:36:07.227,"Python distutils, how to get a compiler that is going to be used?","For example, I may use python setup.py build --compiler=msvc or python setup.py build --compiler=mingw32 or just python setup.py build, in which case the default compiler (say, bcpp) will be used. How can I get the compiler name inside my setup.py (e. g. msvc, mingw32 and bcpp, respectively)? UPD.: I don't need the default compiler, I need the one that is actually going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse sys.argv to see if there's a --compiler... string there.","You can subclass the distutils.command.build_ext.build_ext command. Once build_ext.finalize_options() method has been called, the compiler type is stored in self.compiler.compiler_type as a string (the same as the one passed to the build_ext's --compiler option, e.g. 'mingw32', 'gcc', etc...).",0.4961739557460144,False,2,137 2009-04-07 08:36:07.227,"Python distutils, how to get a compiler that is going to be used?","For example, I may use python setup.py build --compiler=msvc or python setup.py build --compiler=mingw32 or just python setup.py build, in which case the default compiler (say, bcpp) will be used. How can I get the compiler name inside my setup.py (e. g. msvc, mingw32 and bcpp, respectively)? UPD.: I don't need the default compiler, I need the one that is actually going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse sys.argv to see if there's a --compiler... string there.","import distutils.ccompiler compiler_name = distutils.ccompiler.get_default_compiler()",-0.0679224682270276,False,2,137 2009-04-13 16:20:47.457,Django models - how to filter out duplicate values by PK after the fact?,"I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.","If the order doesn't matter, use a dict.",0.0,False,1,138 2009-04-15 01:05:26.610,How to visualize IP addresses as they change in python?,"I've written a little script that collects my external IP address every time I open a new terminal window and appends it, at well as the current time, to a text file. I'm looking for ideas on a way to visualize when/how often my IP address changes. I bounce between home and campus and could separate them using the script, but it would be nice to visualize them separately. I frequently use matplotlib. Any ideas?",There's a section in the matplotlib user guide about drawing bars on a chart to represent ranges. I've never done that myself but it seems appropriate for what you're looking for.,0.0,False,1,139 2009-04-15 21:13:47.127,Need to build (or otherwise obtain) python-devel 2.3 and add to LD_LIBRARY_PATH,"I am supporting an application with a hard dependency on python-devel 2.3.7. The application runs the python interpreter embedded, attempting to load libpython2.3.so - but since the local machine has libpython2.4.so under /usr/lib64, the application is failing. I see that there are RPMs for python-devel (but not version 2.3.x). Another wrinkle is that I don't want to overwrite the existing python under /usr/lib (I don't have su anyway). What I want to do is place the somewhere in my home directory (i.e. /home/noahz/lib) and use PATH and LD_LIBRARY_PATH to point to the older version for this application. What I'm trying to find out (but can't seem to craft the right google search for) is: 1) Where do I download python-devel-2.3 or libpython2.3.so.1.0 (if either available) 2a) If I can't download python-devel-2.3, how do I build libpython2.3.so from source (already downloaded Python-2.3.tgz and 2b) Is building libpython2.3.so.1.0 from source and pointing to it with LD_LIBRARY_PATH good enough, or am I going to run into other problems (other dependencies) 3) In general, am I approaching this problem the right way? ADDITIONAL INFO: I attempted to symlink (ln -s) to the later version. This caused the app to fail silently. Distro is Red Hat Enterprise Linux 5 (RHEL5) - for x86_64","You can use the python RPM's linked to from the python home page ChristopheD mentioned. You can extract the RPM's using cpio, as they are just specialized cpio archives. Your method of extracting them to your home directory and setting LD_LIBRARY_PATH and PATH should work; I use this all the time for hand-built newer versions of projects I also have installed. Don't focus on the -devel package though; you need the main package. You can unpack the -devel one as well, but the only thing you'll actually use from it is the libpython2.3.so symlink that points to the actual library, and you can just as well create this by hand. Whether this is the right approach depends on what you are trying to do. If all you're trying to do is to get this one application to run for you personally, then this hack sounds fine. If you wanted to actually distribute something to other people for running this application, and you have no way of fixing the actual application, you should consider building an rpm of the older python version that doesn't conflict with the system-installed one.",1.2,True,1,140 2009-04-18 22:02:45.750,How do I modify sys.path from .htaccess to allow mod_python to see Django?,"The host I'm considering for hosting a Django site has mod_python installed, but does not have Django. Django's INSTALL file indicates that I can simply copy the django directory to Python's site-packages directory to install Django, so I suspect that it might be possible to configure Python / mod_python to look for it elsewhere (namely my user space) by modifying sys.path, but I don't know how to change it from .htaccess or mod_python. How do I modify sys.path from .htaccess to allow mod_python to see Django? P.S. I can only access the site via FTP (i.e. no shell access). I realize that it sounds like I should just switch hosts, but there are compelling reasons for me to make this work so I'm at least going to try.",You're using mod_python wrong. It was never intended to serve python web applications. You should be using WSGI for this... or at least FastCGI.,0.1352210990936997,False,1,141 2009-04-19 18:00:40.033,Convert timedelta to years?,I need to check if some number of years have been since some date. Currently I've got timedelta from datetime module and I don't know how to convert it to years.,"How exact do you need it to be? td.days / 365.25 will get you pretty close, if you're worried about leap years.",0.0968769437433111,False,4,142 2009-04-19 18:00:40.033,Convert timedelta to years?,I need to check if some number of years have been since some date. Currently I've got timedelta from datetime module and I don't know how to convert it to years.,"Get the number of days, then divide by 365.2425 (the mean Gregorian year) for years. Divide by 30.436875 (the mean Gregorian month) for months.",0.1352210990936997,False,4,142 2009-04-19 18:00:40.033,Convert timedelta to years?,I need to check if some number of years have been since some date. Currently I've got timedelta from datetime module and I don't know how to convert it to years.,"In the end what you have is a maths issue. If every 4 years we have an extra day lets then dived the timedelta in days, not by 365 but 365*4 + 1, that would give you the amount of 4 years. Then divide it again by 4. timedelta / ((365*4) +1) / 4 = timedelta * 4 / (365*4 +1)",0.0194338988372611,False,4,142 2009-04-19 18:00:40.033,Convert timedelta to years?,I need to check if some number of years have been since some date. Currently I've got timedelta from datetime module and I don't know how to convert it to years.,"If you're trying to check if someone is 18 years of age, using timedelta will not work correctly on some edge cases because of leap years. For example, someone born on January 1, 2000, will turn 18 exactly 6575 days later on January 1, 2018 (5 leap years included), but someone born on January 1, 2001, will turn 18 exactly 6574 days later on January 1, 2019 (4 leap years included). Thus, you if someone is exactly 6574 days old, you can't determine if they are 17 or 18 without knowing a little more information about their birthdate. The correct way to do this is to calculate the age directly from the dates, by subtracting the two years, and then subtracting one if the current month/day precedes the birth month/day.",0.9912596409131113,False,4,142 2009-04-19 19:51:07.787,Amazon S3 permissions,"Trying to understand S3...How do you limit access to a file you upload to S3? For example, from a web application, each user has files they can upload, but how do you limit access so only that user has access to that file? It seems like the query string authentication requires an expiration date and that won't work for me, is there another way to do this?",You will have to build the whole access logic to S3 in your applications,0.1016881243684853,False,3,143 2009-04-19 19:51:07.787,Amazon S3 permissions,"Trying to understand S3...How do you limit access to a file you upload to S3? For example, from a web application, each user has files they can upload, but how do you limit access so only that user has access to that file? It seems like the query string authentication requires an expiration date and that won't work for me, is there another way to do this?","There are various ways to control access to the S3 objects: Use the query string auth - but as you noted this does require an expiration date. You could make it far in the future, which has been good enough for most things I have done. Use the S3 ACLS - but this requires the user to have an AWS account and authenticate with AWS to access the S3 object. This is probably not what you are looking for. You proxy the access to the S3 object through your application, which implements your access control logic. This will bring all the bandwidth through your box. You can set up an EC2 instance with your proxy logic - this keeps the bandwidth closer to S3 and can reduce latency in certain situations. The difference between this and #3 could be minimal, but depends your particular situation.",0.9981778976111988,False,3,143 2009-04-19 19:51:07.787,Amazon S3 permissions,"Trying to understand S3...How do you limit access to a file you upload to S3? For example, from a web application, each user has files they can upload, but how do you limit access so only that user has access to that file? It seems like the query string authentication requires an expiration date and that won't work for me, is there another way to do this?","Have the user hit your server Have the server set up a query-string authentication with a short expiration (minutes, hours?) Have your server redirect to #2",0.6730655149877884,False,3,143 2009-04-20 19:27:37.197,How do I load entry-points for a defined set of eggs with Python setuptools?,"I would like to use the entry point functionality in setuptools. There are a number of occasions where I would like to tightly control the list of eggs that are run, and thence the extensions that contribute to a set of entry points: egg integration testing, where I want to run multiple test suites on different combinations of eggs. scanning a single directory of eggs/plugins so as to run two different instances of the same program, but with different eggs. development time, where I am developing one or more egg, and would like to run the program as part of the normal edit-run cycle. I have looked through the setuptools documentation, and while it doesn't say that this is not possible, I must have missed something saying how to do it. What is the best way to approach deploying plugins differently to the default system-wide discovery?","We're solving something similar, ability to use setup.py develop if You're mere user without access to global site-packages. So far, we solved it with virtualenv. I'd say it will help for your case too: have minimal system-wide install (or explicitly exclude it), create virtual environment with eggs you want and test there. (Or, for integration tests, create clean environment, install egg and test all dependencies are installed). For 2, I'm not sure, but it should work too, with multiple virtualenvs. For 3, setup.py develop is the way to go.",0.0,False,1,144 2009-04-21 14:43:48.383,Free word list for use programmatically?,"A friend of mine was talking about a word game she liked to play where you try to convert one word to another (they have the same number of letters) by switching one letter at a time, where each iteration produces a real word. Example: MOON --> WOLF GOON GOOF GOLF WOLF I figured it'd be a fun little project to write a program to generate solutions, and taking it further, given 2 words, determine if a solution exists and the number of iterations in optimal solution. Problem is I'm having trouble finding free word lists that I can easily access programmatically. I'm also thinking about using this as an excuse to learn Python, so it'd be great if anyone knows of free word lists and pointers on how to parse and access it from Python. The algorithm for figuring out how to find an optimal path I'll work on my own.",Most unix (which includes osx) have a file /usr/share/dict/words.,0.999839224992412,False,1,145 2009-04-23 12:20:12.113,Python3 Http Web Server: virtual hosts,"I am writing an rather simple http web server in python3. The web server needs to be simple - only basic reading from config files, etc. I am using only standard libraries and for now it works rather ok. There is only one requirement for this project, which I can't implement on my own - virtual hosts. I need to have at least two virtual hosts, defined in config files. The problem is, that I can't find a way how can I implement them in python. Does anyone have any guides, articles, maybe some simple implementation how can this be done? I would be grateful for any help.","Virtual hosts work by obeying the Host: header in the HTTP request. Just read the headers of the request, and take action based on the value of the Host: header",0.9999092042625952,False,1,146 2009-04-23 19:08:27.440,How to connect to a WCF Service with IronPython,"Has anyone done this? I've tried generating a c# proxy class and connecting through it, but I cannot figure out how to get IronPython to use the generated app.config file that defines the endpoint. It tries to connect, but I just get an error about no default endpoint. I would ideally like to make the connection using only IronPython code and not use the proxy class, if possible. The binding for the service I am trying to connect to is a NetTcpBinding if that makes any difference.","Is your WCF service interface available in a shared assembly? If so, you could look at using the ChannelFactory to create your client proxy dynamically (instead of using the generated C# proxy). With that method you can supply all the details of the endpoint when you create the ChannelFactory and you won't require any configuration in your .config file.",0.0,False,1,147 2009-04-24 14:45:27.703,How to design an email system?,"I am working for a company that provides customer support to its clients. I am trying to design a system that would send emails automatically to clients when some event occurs. The system would consist of a backend part and a web interface part. The backend will handle the communication with a web interface (which will be only for internal use to change the email templates) and most important it will check some database tables and based on those results will send emails ... lots of them. Now, I am wondering how can this be designed so it can be made scalable and provide the necessary performance as it will probably have to handle a few thousands emails per hours (this should be the peek). I am mostly interested about how would this kind of architecture should be thought in order to be easily scaled in the future if needed. Python will be used on the backend with Postgres and probably whatever comes first between a Python web framework and GWT on the frontend (which seems the simplest task).","A few thousand emails per hour isn't really that much, as long as your outgoing mail server is willing to accept them in a timely manner. I would send them using a local mta, like postfix, or exim (which would then send them through your outgoing relay if required). That service is then responsible for the mail queues, retries, bounces, etc. If your looking for more ""mailing list"" features, try adding mailman into the mix. It's written in python, and you've probably seen it, as it runs tons of internet mailing lists.",0.296905446847765,False,2,148 2009-04-24 14:45:27.703,How to design an email system?,"I am working for a company that provides customer support to its clients. I am trying to design a system that would send emails automatically to clients when some event occurs. The system would consist of a backend part and a web interface part. The backend will handle the communication with a web interface (which will be only for internal use to change the email templates) and most important it will check some database tables and based on those results will send emails ... lots of them. Now, I am wondering how can this be designed so it can be made scalable and provide the necessary performance as it will probably have to handle a few thousands emails per hours (this should be the peek). I am mostly interested about how would this kind of architecture should be thought in order to be easily scaled in the future if needed. Python will be used on the backend with Postgres and probably whatever comes first between a Python web framework and GWT on the frontend (which seems the simplest task).",You might want to try Twisted Mail for implementing your own backend in pure Python.,0.0,False,2,148 2009-04-24 14:46:45.890,Basic MVT issue in Django,"I have a Django website as follows: site has several views each view has its own template to show its data each template extends a base template base template is the base of the site, has all the JS/CSS and the basic layout So up until now it's all good. So now we have the master head of the site (which exists in the base template), and it is common to all the views. But now I want to make it dynamic, and add some dynamic data to it. On which view do I do this? All my views are basically render_to_response('viewtemplate.html', someContext). So how do add a common view to a base template? Obviously I will not duplicate the common code to each separate view... I think I'm missing something fundamental in the MVT basis of Django.","Context processors and RequestContext (see Tyler's answer) are the way to go for data that is used on every page load. For data that you may need on various views, but not all (especially data that isn't really related to the primary purpose of the view, but appears in something like a navigation sidebar), it often makes most sense to define a custom template tag for retrieving the data.",0.2655860252697744,False,1,149 2009-04-25 20:35:44.357,What is the best way to redirect email to a Python script?,"I'd like to provide a functionality for users of my website to get assigned an email address upon registration (such as firstname.lastname@mydomain.com) but I don't really think it is feasible to actually support all these emails account normally through a webmail program. I am also not sure if my webhost would be cool with it. What I'd really want is to be able to have a seamless integration of this email into the bigger system that the website is, as it is mostly going to be for intra-site messaging but we want to allow users to put actual email addresses. So what I would like to do instead is have a catch-all account under mydomain and have this email look at incoming mail, see who it was meant to be sent to, and add a message for the user in the system. So, the questions are: 1) Is this the right approach? How expensive would it be to get a host that would allow me to just assign emails to at will to my domain? I am currently using WebFaction's shared hosting. 2) If it is an okay approach, what is the best way to route this catch all account to my python script? I have read about .forward but I am not very good at UNIX stuff. Once I figure that out, how would I get the script to be in the ""Django environment"" so I can use Django's model functionality to add the new messages to the user? 3) Is there anything Django can do to make this any easier? 4) Are there any tools in Python to help me parse the email address? How do they work?","but I don't really think it is feasible to actually support all these emails account normally through a webmail program I think that your base assumption here is incorrect. You see, most 'webmail' programs are just frontends (or clients) to the backend mail system (postfix etc). You will need to see how your webhost is set up. There is no reason why you can not create these accounts programmatically and then let them use a normal webmail interface like SquirrelMail or RoundCube. For instance, my webhost (bluehost) allows me 2500 email accounts - I am not sure how many yours allows - but I can upgrade to unlimited for a few extra dollars a month. I think that using the builtin email handling facility is a more robust way to go.",0.0,False,1,150 2009-04-27 21:42:12.717,Is there an easy way to tell how much time is spent waiting for the Python GIL?,"I have a long-running Python service and I'd like to know how much cumulative wall clock time has been spent by any runnable threads (i.e., threads that weren't blocked for some other reason) waiting for the GIL. Is there an easy way to do this? E.g., perhaps I could periodically dump some counter to its log file. My underlying motivation is to rule out the GIL as a source of mystery response latency from these long-running processes. There is no particular reason to suspect the GIL (other than that it would fit the symptoms), but other forms of logging haven't turned up anything yet, so, if it is easy, it would be nice to have this information.","I don't think there's an easy way. There's probably an awkward way, involving rebuilding Python to traverse the PyThreadState list and count the threads each time the lock is acquired, but I doubt it's worth the effort! I know this is a speculative question but if you are even moderately concerned about there being delays caused by threading it may be prudent to move to a multiprocessing model instead of a multithreading model. Since processes are both safer and more scalable in Python they are almost always the best choice if practical.",0.5457054096481145,False,1,151 2009-04-28 12:56:05.873,Django caching - can it be done pre-emptively?,"I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup. This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a significant delay of a few seconds while I go to the external site to parse the new data. Is there any way to load the new data lazily so that no user will ever get that kind of delay? Or is this unavoidable? Please note that I am on a shared hosting server, so keep that in mind with your answers. EDIT: thanks for the help so far. However, I'm still unsure as to how I accomplish this with the python script I will be calling. A basic test I did shows that the django cache is not global. Meaning if I call it from an external script, it does not see the cache data going on in the framework. Suggestions? Another EDIT: coming to think of it, this is probably because I am still using local memory cache. I suspect that if I move the cache to memcached, DB, whatever, this will be solved.","""I'm still unsure as to how I accomplish this with the python script I will be calling. "" The issue is that your ""significant delay of a few seconds while I go to the external site to parse the new data"" has nothing to do with Django cache at all. You can cache it everywhere, and when you go to reparse the external site, there's a delay. The trick is to NOT parse the external site while a user is waiting for their page. The trick is to parse the external site before a user asks for a page. Since you can't go back in time, you have to periodically parse the external site and leave the parsed results in a local file or a database or something. When a user makes a request you already have the results fetched and parsed, and all you're doing is presenting.",0.3869120172231254,False,2,152 2009-04-28 12:56:05.873,Django caching - can it be done pre-emptively?,"I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup. This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a significant delay of a few seconds while I go to the external site to parse the new data. Is there any way to load the new data lazily so that no user will ever get that kind of delay? Or is this unavoidable? Please note that I am on a shared hosting server, so keep that in mind with your answers. EDIT: thanks for the help so far. However, I'm still unsure as to how I accomplish this with the python script I will be calling. A basic test I did shows that the django cache is not global. Meaning if I call it from an external script, it does not see the cache data going on in the framework. Suggestions? Another EDIT: coming to think of it, this is probably because I am still using local memory cache. I suspect that if I move the cache to memcached, DB, whatever, this will be solved.","I have no proof, but I've read BeautifulSoup is slow and consumes a lot of memory. You may want to look at using the lxml module instead. lxml is supposed to be much faster and efficient, and can do much more than BeautifulSoup. Of course, the parsing probably isn't your bottleneck here; the external I/O is. First off, use memcached! Then, one strategy that can be used is as follows: Your cached object, called A, is stored in the cache with a dynamic key (A_, for example). Another cached object holds the current key for A, called A_key. Your app would then get the key for A by first getting the value at A_key A periodic process would populate the cache with the A_ keys and upon completion, change the value at A_key to the new key Using this method, all users every 5 minutes won't have to wait for the cache to be updated, they'll just get older versions until the update happens.",0.3869120172231254,False,2,152 2009-04-29 08:28:24.667,How to create IDLE -like functionality to WinForms application,"I'd like to add ""IDLE-like functionality"" to C# WinForms application, but I don't quite have an idea how to do that and couldn't find anything useful with Google. So basically I want interactive command line interface, where user could enter some Python code and execute it (not just expressions, should be possible to define new functions). So, where to start? Are there any good tutorials or samples available?","IronRuby comes with a command line interpreter. Doesn't IronPython also have one? If so, the source code would be a good start :) Oh, and if it doesn't, be sure to look at the IronRuby interpreter, because both languages are based on the DLR and are therefore similar enough to learn from both.",0.0,False,1,153 2009-04-29 11:31:06.270,Notifying container object: best practices,"I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well. I think of three alternatives on how to achieve this: 1) Hold a reference within Operator to the container [Account] object and call methods directly. Not absolutely good because of circular references. 2) Use events. As far as I know there is no built-in event handling mechanism in Python. So, this one is a bit tricky to implement. 3) Don't send messages to Operators directly. Instead, operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators. I wonder which approach is the most advantageous from the architectural point of view. How do you usually handle this task? It would be great if you could point out snippets in Python.","You're over-thinking this. Seriously. Python isn't C++; your concerns are non-issues in Python. Just write what makes sense in your problem domain. "" Not absolutely good because of circular references."" Why not? Circularity is of no relevance here at all. Bidirectional relationships are great things. Use them. Python garbage collects them just fine without any thinking on your part. What possible problem do you have with mutual (birectional) relationships? ""...operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators. "" What? Your Operators are Python objects, pass all you want. All Python objects are (in effect) references, don't sweat it. What possible problem do you have with manipulating Operator objects?",1.2,True,2,154 2009-04-29 11:31:06.270,Notifying container object: best practices,"I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well. I think of three alternatives on how to achieve this: 1) Hold a reference within Operator to the container [Account] object and call methods directly. Not absolutely good because of circular references. 2) Use events. As far as I know there is no built-in event handling mechanism in Python. So, this one is a bit tricky to implement. 3) Don't send messages to Operators directly. Instead, operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators. I wonder which approach is the most advantageous from the architectural point of view. How do you usually handle this task? It would be great if you could point out snippets in Python.","There is no ""one-size-fits-all"" solution for the Observer pattern. But usually, it's better to define an EventManager object where interested parties can register themselves for certain events and post these events whenever they happen. It simply creates less dependencies. Note that you need to use a global EventManager instance, which can be problematic during testing or from a general OO point of view (it's a global variable). I strongly advise against passing the EventManager around all the time because that will clutter your code. In my own code, the ""key"" for registering events is the class of the event. The EventManager uses a dictionary (event class -> list of observers) to know which event goes where. In the notification code, you can then use dict.get(event.__class__, ()) to find your listeners.",0.2401167094949473,False,2,154 2009-04-30 05:03:05.993,What is the best way to access stored procedures in Django's ORM,"I am designing a fairly complex database, and know that some of my queries will be far outside the scope of Django's ORM. Has anyone integrated SP's with Django's ORM successfully? If so, what RDBMS and how did you do it?",I guess the improved raw sql queryset support in Django 1.2 can make this easier as you wouldn't have to roll your own make_instance type code.,0.0,False,2,155 2009-04-30 05:03:05.993,What is the best way to access stored procedures in Django's ORM,"I am designing a fairly complex database, and know that some of my queries will be far outside the scope of Django's ORM. Has anyone integrated SP's with Django's ORM successfully? If so, what RDBMS and how did you do it?","Don't. Seriously. Move the stored procedure logic into your model where it belongs. Putting some code in Django and some code in the database is a maintenance nightmare. I've spent too many of my 30+ years in IT trying to clean up this kind of mess.",0.336246259354525,False,2,155 2009-05-01 03:24:53.257,Biggest python projects,"What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams. It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller. Are there some huge companies that develop primarily in Python?","Python is very powerful language, Many big and the very high ranked websites are built on python.. Some big products of python are:- Google (extensively used) Youtube (extensively used) Disqus Eventbrite Pinterest Reddit Quora Mozilla Asana (extensively used) Dropbox (started with python, stayed with python) Even Many companies are shifting their websites from PHP to Python, Because of its efficiency, fast ability, and reliability, and availability of huge support and many good frameworks such as Django.. Moreover, I am not saying that PHP is not a good server side scripting language, But truth is that, most users are adapting python instead of PHP.",0.296905446847765,False,3,156 2009-05-01 03:24:53.257,Biggest python projects,"What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams. It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller. Are there some huge companies that develop primarily in Python?","Our project is over 30,000 lines of Python. That's probably small by some standards. But it's plenty big enough to fill my little brain. The application is mentioned in our annual report, so it's ""strategic"" in that sense. We're not a ""huge"" company, so we don't really qualify. A ""huge company"" (Fortune 1000?) doesn't develop primarily in any single language. Large companies will have lots of development teams, each using a different technology, depending on -- well -- on nothing in particular. When you get to ""epic companies"" (Fortune 10) you're looking at an organization that's very much like a conglomerate of several huge companies rolled together. Each huge company within an epic company is still a huge company with multiple uncoordinated IT shops doing unrelated things -- there's no ""develop primarily in"" any particular language or toolset. Even for ""large companies"" and ""small companies"" (like ours) you still have fragmentation. Our in-house IT is mostly Microsoft. Our other product development is mostly Java. My team, however, doesn't have much useful specification, so we use Python. We use python because of the duck typing and dynamic programming features. (I don't know what a dynamic type system is -- Python types are static -- when you create an object, its type can never change.) Since no huge company develops primarily in any particular language or toolset, the trivial answer to your question is ""No"" for any language or tool. And No for Python in particular.",0.6730655149877884,False,3,156 2009-05-01 03:24:53.257,Biggest python projects,"What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams. It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller. Are there some huge companies that develop primarily in Python?","Among many other Python-centered companies, beyond the ones already mentioned by Unknown, I'd mention big pharma firms such as Astra-Zeneca, film studios such as Lucasfilm, and research places such as NASA, Caltech, Lawrence Livermore NRL. Among the sponsors of Pycon Italia Tre (next week in Firenze, IT -- see www.pycon.it) are Qt/Trolltech (a wholly owned subsidiary of Nokia), Google of course, Statpro, ActiveState, Wingware -- besides, of course, several Italian companies. Among the sponsors of Pycon US in Chicago in March were (of course) Google, as well as Sun Microsystems, Microsoft, Slide.com, Walt Disney Animation Studios, Oracle, Canonical, VMWare -- these are all companies who thought it worthwhile to spend money in order to have visibility to experienced Pythonistas, so presumably ones making significant large-scale use of Python (and in most cases trying to hire experienced Python developers in particular).",0.9950547536867304,False,3,156 2009-05-04 08:59:20.273,How can I check if an ip is in a network in Python?,"Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python? Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.","#This works properly without the weird byte by byte handling def addressInNetwork(ip,net): '''Is an address in a network''' # Convert addresses to host order, so shifts actually make sense ip = struct.unpack('>L',socket.inet_aton(ip))[0] netaddr,bits = net.split('/') netaddr = struct.unpack('>L',socket.inet_aton(netaddr))[0] # Must shift left an all ones value, /32 = zero shift, /0 = 32 shift left netmask = (0xffffffff << (32-int(bits))) & 0xffffffff # There's no need to mask the network address, as long as its a proper network address return (ip & netmask) == netaddr",0.0291462614471899,False,1,157 2009-05-05 02:52:08.900,What's the best way to record the type of every variable assignment in a Python program?,"Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file. One way to compensate might be to write a special profiler that, instead of timing the program, would record the runtime types and paths of objects of the program and expose this data to the editor. This might be implemented with sys.settrace() which sets a callback for each line of code and is how pdb is implemented, or by using the ast module and an import hook to instrument the code, or is there a better strategy? How would you write something like this without making it impossibly slow, and without runnning afoul of extreme dynamism e.g side affects on property access?","What if you monkey-patched object's class or another prototypical object? This might not be the easiest if you're not using new-style classes.",0.1016881243684853,False,1,158 2009-05-05 16:22:53.010,Network-aware wx.FileDialog,"I'm using wx.FileDialog in a wxPython 2.8.8.0 application, under Xubuntu 8.10.. My problem is that this dialog isn't network-aware, so I can't browse Samba shares. I see that this problem plagues other applications too (Firefox, Audacious...) so I'd like to ask where I could find informations on how to make it work. Is that dialog supposed to be already network-aware? Am I missing something? Some library maybe? Or should I write my own implementation? Many thanks!","Robin Dunn himself told me that It's using the ""native"" GTK file dialog, just like the other apps, so there isn't anything that wx can do about it. So as a workaround I ended up installing gvfs-fuse and browsing the network through $HOME/.gvfs.. A bit klunky but it works.",1.2,True,1,159 2009-05-05 17:01:44.240,Catch only some runtime errors in Python,"I'm importing a module which raises the following error in some conditions: RuntimeError: pyparted requires root access I know that I can just check for root access before the import, but I'd like to know how to catch this spesific kind of error via a try/except statement for future reference. Is there any way to differentiate between this RuntimeError and others that might be raised?","I know that I can just check for root access before the import, but I'd like to know how to catch this spesific kind of error via a try/except statement for future reference. Is there any way to differentiate between this RuntimeError and others that might be raised? If the error is caused by a specific condition, then I think the easiest way to catch the error is to test for the condition, and you can raise a more specific error yourself. After all the 'error' exists before the error is thrown, since in this case its a problem with the environment. I agree with those above - text matching on an error is kind of a terrifying prospect.",1.2,True,1,160 2009-05-05 20:14:11.267,how to get the n-th record of a datastore query,"Suppose that I have the model Foo in GAE and this query: query = Foo.all().order('-key') I want to get the n-th record. What is the most efficient way to achieve that? Will the solution break if the ordering property is not unique, such as the one below: query = Foo.all().order('-color') edit: n > 1000 edit 2: I want to develop a friendly paging mechanism that shows pages available (such as Page 1, Page 2, ... Page 185) and requires a ""?page=x"" in the query string, instead of a ""?bookmark=XXX"". When page = x, the query is to fetch the records beginning from the first record of that page.","There is no efficient way to do this - in any DBMS. In every case, you have to at least read sequentially through the index records until you find the nth one, then look up the corresponding data record. This is more or less what fetch(count, offset) does in GAE, with the additional limitation of 1000 records. A better approach to this is to keep a 'bookmark', consisting of the value of the field you're ordering on for the last entity you retrieved, and the entity's key. Then, when you want to continue from where you left off, you can add the field's value as the lower bound of an inequality query, and skip records until you match or exceed the last one you saw. If you want to provide 'friendly' page offsets to users, what you can do is to use memcache to store an association between a start offset and a bookmark (order_property, key) tuple. When you generate a page, insert or update the bookmark for the entity following the last one. When you fetch a page, use the bookmark if it exists, or generate it the hard way, by doing queries with offsets - potentially multiple queries if the offset is high enough.",1.2,True,1,161 2009-05-05 22:56:01.067,Unit testing for D-Bus and HAL?,"How does one test a method that does some interactions with the local D-Bus (accessing a HAL object)? Results of tests will differ depending on the system that the test is run on, so I don't know how to provide the method reliable input. I'm working in Python, by the way.","If you can not mock the environment then it's probably impossible for you to write the test. If your access to HAL/D-Bus is via an object and you provide a mock instance to your test then it should be possible to emulate the necessary inputs to your test from the mock implementation.",1.2,True,1,162 2009-05-07 07:45:26.073,How to run a script without being in the tasktray?,"I have a scheduled task which runs a python script every 10 min so it turns out that a script pops up on my desktop every 10 min how can i make it invincible so my script will work in the background ? I've been told that pythonw will do the work, but I cant figure out how to use it any help ? thanks",Set the scheduled task to start the script as minimized.,0.0,False,2,163 2009-05-07 07:45:26.073,How to run a script without being in the tasktray?,"I have a scheduled task which runs a python script every 10 min so it turns out that a script pops up on my desktop every 10 min how can i make it invincible so my script will work in the background ? I've been told that pythonw will do the work, but I cant figure out how to use it any help ? thanks","I've been told that pythonw will do the work, but I cant figure out how to use it Normally you just have to rename the file extension to .pyw. Then it will be executed by pythonw.",0.5457054096481145,False,2,163 2009-05-07 20:55:48.750,datastore transaction restrictions,"in my google app application, whenever a user purchases a number of contracts, these events are executed (simplified for clarity): user.cash is decreased user.contracts is increased by the number contracts.current_price is updated. market.no_of_transactions is increased by 1. in a rdms, these would be placed within the same transaction. I conceive that google datastore does not allow entities of more than one model to be in the same transaction. what is the correct approach to this issue? how can I ensure that if a write fails, all preceding writes are rolled back? edit: I have obviously missed entity groups. Now I'd appreciate some further information regarding how they are used. Another point to clarify is google says ""Only use entity groups when they are needed for transactions. For other relationships between entities, use ReferenceProperty properties and Key values, which can be used in queries"". does it mean I have to define both a reference property (since I need queriying them) and a parent-child relationship (for transactions)? edit 2: and finally, how do I define two parents for an entity if the entity is being created to establish an n-to-n relationship between 2 parents?","After a through research, I have found that a distributed transaction layer that provides a solution to the single entity group restriction has been developed in userland with the help of some google people. But so far, it is not released and is only available in java.",1.2,True,1,164 2009-05-08 18:23:39.907,Tokenizing left over data with lex/yacc,"Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless: I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates perfectly to an equation, which it parses fine and calculates, or something that is nothing like an equation, which fails parsing and is also fine. The gray area is an input that has equation-like parts, of which the parser will grab and work out. This isn't what I want - I need to be able to tell if parts of the string didn't get picked up and tokenized so I can throw back an error, but I have no idea how to do this. Does anyone know how I can define, basically, a 'catch anything that's left' token? Or is there a better way I can handle this?","I typically use a separate 'command reader' to obtain a complete command - probably a line in your case - into a host variable string, and then arrange for the lexical analyzer to analyze the string, including telling me when it didn't reach the end. This is hard to set up, but make some classes of error reporting easier. One of the places I've used this technique routinely has multi-line commands with 3 comment conventions, two sets of quoted strings, and some other nasties to set my teeth on edge (context sensitive tokenization - yuck!). Otherwise, Don's advice with the Yacc 'error' token is good.",0.0,False,2,165 2009-05-08 18:23:39.907,Tokenizing left over data with lex/yacc,"Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless: I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates perfectly to an equation, which it parses fine and calculates, or something that is nothing like an equation, which fails parsing and is also fine. The gray area is an input that has equation-like parts, of which the parser will grab and work out. This isn't what I want - I need to be able to tell if parts of the string didn't get picked up and tokenized so I can throw back an error, but I have no idea how to do this. Does anyone know how I can define, basically, a 'catch anything that's left' token? Or is there a better way I can handle this?","There is a built-in error token in yacc. You would normally do something like: line: goodline | badline ; badline : error '\n' /* Error-handling action, if needed */ goodline : equation '\n' ; Any line that doesn't match equation will be handled by badline. You might want to use yyerrok in the error handling action to ensure error processing is reset for the next line.",1.2,True,2,165 2009-05-08 22:41:21.693,Piping Batch File output to a Python script,I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like to take those messages from the batch file and use them in the python script. Anyone have any ideas on how to do this ?,Try subprocess.Popen(). It allows you to redirect stdout and stderr to files.,0.1352210990936997,False,1,166 2009-05-11 12:24:35.110,How to write a vb.net code to compile C/C++ programs?,"I'm trying to make a vb.net application that has got 2 textboxes, 7 radio buttons and 2 buttons(one named compile and the other 'run'). How can I load the content of a C/C++(or any programming language) file into the 1st textbox and on clicking the compile button, i should be able to show the errors or the C/C++ program in the 2nd textbox. On clicking Run, I should be able to show the output in the 2nd textbox. In short, I want to use the 2nd textbox as a terminal/console. The radio buttons are 4 selecting the language C or C++ or python or C# or java or perl or vb. Are the compilers of all these languages present in .net? If so how can I call them?",Compiling can be done by calling cl.exe which comes with Visual Studio. Of course you could also use GCC instead.,0.2012947653214861,False,1,167 2009-05-11 14:55:46.930,Python M2Crypto EC Support,"M2Crypto provides EC support for ECDSA/ECDH. I have installed OpenSSL 0.9.8i which contains support for EC. However when I run ""from M2Crypto import EC,BIO"" I get error saying EC_init() failed. So I added debug to print m2.OPENSSL_VERSION_TEXT value. It gets printed as ""OpenSSL 0.9.7 19 Feb 2003"". This version of OpenSSL doesnot support EC. I tried ""python setup.py build build_ext --openssl=""new_path where OpenSSL 0.9.8i is installed"". Though M2Crypto is built again ""Python setup.py install"" , I still see that it points to ""Old version of OpenSSL"". Any Pointers on how to successfully get M2Crypto to use 0.9.8i will be useful.",Possibly its looking up shared libs libssl.so and libcrypto.so and finding the old ones in /usr/lib if you add the new_path to the top of /etc/ld.so.conf so it gets searched first it would work. But this might break other OpenSSL applications expecting old OpenSSL.,0.0,False,1,168 2009-05-12 03:20:00.953,How do I check if a disk is in a drive using python?,"Say I want to manipulate some files on a floppy drive or a USB card reader. How do I check to see if the drive in question is ready? (That is, has a disk physically inserted.) The drive letter exists, so os.exists() will always return True in this case. Also, at this point in the process I don't yet know any file names, so checking to see if a given file exists also won't work. Some clarification: the issue here is exception handling. Most of the win32 API calls in question just throw an exception when you try to access a drive that isn't ready. Normally, this would work fine - look for something like the free space, and then catch the raised exception and assume that means there isn't a disk present. However, even when I catch any and all exceptions, I still get an angry exception dialog box from Windows telling me the floppy / card reader isn't ready. So, I guess the real question is - how do I suppress the windows error box?","You can compare len(os.listdir(""path"")) to zero to see if there are any files in the directory.",0.2655860252697744,False,1,169 2009-05-12 23:29:12.147,Running django on OSX,"I've just completed the very very nice django tutorial and it all went swimmingly. One of the first parts of the tutorial is that it says not to use their example server thingie in production, my first act after the tutorial was thus to try to run my app on apache. I'm running OSX 10.5 and have the standard apache (which refuses to run python) and MAMP (which begrudgingly allows it in cgi-bin). The problem is that I've no idea which script to call, in the tutorial it was always localhost:8000/polls but I've no idea how that's meant to map to a specific file. Have I missed something blatantly obvious about what to do with a .htaccess file or does the tutorial not actually explain how to use it somewhere else?","Unless you are planning on going to production with OS X you might not want to bother. If you must do it, go straight to mod_wsgi. Don't bother with mod_python or older solutions. I did mod_python on Apache and while it runs great now, it took countless hours to set up. Also, just to clarify something based on what you said: You're not going to find a mapping between the url path (like /polls) and a script that is being called. Django doesn't work like that. With Django your application is loaded into memory waiting for requests. Once a request comes in it gets dispatched through the url map that you created in urls.py. That boils down to a function call somewhere in your code. That's why for a webserver like Apache you need a module like mod_wsgi, which gives your app a spot in memory in which to live. Compare that with something like CGI where the webserver executes a specific script on demand at a location that is physically mapped between the url and the filesystem. I hope that's helpful and not telling you something you already knew. :)",0.4701041941942874,False,2,170 2009-05-12 23:29:12.147,Running django on OSX,"I've just completed the very very nice django tutorial and it all went swimmingly. One of the first parts of the tutorial is that it says not to use their example server thingie in production, my first act after the tutorial was thus to try to run my app on apache. I'm running OSX 10.5 and have the standard apache (which refuses to run python) and MAMP (which begrudgingly allows it in cgi-bin). The problem is that I've no idea which script to call, in the tutorial it was always localhost:8000/polls but I've no idea how that's meant to map to a specific file. Have I missed something blatantly obvious about what to do with a .htaccess file or does the tutorial not actually explain how to use it somewhere else?","Yet another option is to consider using a virtual machine for your development. You can install a full version of whatever OS your production server will be running - say, Debian - and run your Apache and DB in the VM. You can connect to the virtual disk in the Finder, so you can still use TextMate (or whatever) on OSX to do your editing. I've had good experiences doing this via VMWare Fusion.",0.2012947653214861,False,2,170 2009-05-16 12:01:37.463,Most Efficient Way to Find Whether a Large List Contains a Specific String (Python),"I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is ""in English"" (i.e. if this exact word is in the list). What would be the most efficient way to do this in Python? The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I ""abuse"" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long). Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization. Thanks","You're basically testing whether a member is in a set or not, right? If so, and because you said you have lots of memory, why not just load all the words as keys in memcache, and then for every word, just check if it is present in memcache or not. Or use that data structure that is used by bash to autocomplete command names - this is fast and highly efficient in memory (can't remember the name).",0.0904550252145576,False,2,171 2009-05-16 12:01:37.463,Most Efficient Way to Find Whether a Large List Contains a Specific String (Python),"I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is ""in English"" (i.e. if this exact word is in the list). What would be the most efficient way to do this in Python? The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I ""abuse"" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long). Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization. Thanks","Two things: The Python 'mutable set' type has an 'add' method ( s.add(item) ), so you could go right from reading (a line) from your big file straight into a set without using a list as an intermediate data structure. Python lets you 'pickle' a data structure, so you could save your big set to a file and save the time of reinitiating the set. Second, I've been looking for a list of all the single-syllable words in English for my own amusement, but the ones I've found mentioned seem to be proprietary. If it isn't being intrusive, could I ask whether your list of English words can be obtained by others?",0.0904550252145576,False,2,171 2009-05-16 16:19:40.790,does someone know how to show content on screen (covering up any window) using Ruby or Python?,"using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen as the canvas), and then press the key again, and everything restores to the same as before? (like Mac OS X's dash board).",I would recommend PyGame.,0.1352210990936997,False,2,172 2009-05-16 16:19:40.790,does someone know how to show content on screen (covering up any window) using Ruby or Python?,"using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen as the canvas), and then press the key again, and everything restores to the same as before? (like Mac OS X's dash board).","You could use the systems dashboard (desktop widgets, or whatever it's called) API. In order to do that you need bindings to it for Python or Ruby. Alternatively you could use some generic gui toolkit or application framework and just create a frameless window with transparent background. Then you need to be sure that the chosen toolkit supports 'always-on-top' options on your desired platform(s).",1.2,True,2,172 2009-05-17 12:09:47.610,Admin privileges for script,how can i check admin-privileges for my script during running?,"The concept of ""admin-privileges"" in our day of fine grained privilege control is becoming hard to define. If you are running on unix with ""traditional"" access control model, getting the effective user id (available in os module) and checking that against root (0) could be what you are looking for. If you know accessing a file on the system requires the privileges you want your script to have, you can use the os.access() to check if you are privileged enough. Unfortunately there is no easy nor portable method to give. You need to find out or define the security model used, what system provided APIs are available to query and set privileges and try to locate (or possibly implement yourself) the appropriate python modules that can be used to access the API. The classic question, why do you need to find out? What if your script tries to do what it needs to do and ""just"" catches and properly handles failures?",0.7408590612005881,False,1,173 2009-05-17 19:00:20.693,Simple data storing in Python,"I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed. I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would have been sloppy to get it to work and I'm sure there is a better approach. So far I've tried: the array.toFile() method but couldn't figure out how to get it to work with nested arrays of strings, it seemed geared towards integer data. Lists and sets do not have a toFile method built in, so I would have had to parse and encode it manually. CSV seemed like a good approach but this would also require manually parsing it, and did not allow me to simply append new lines at the end - so any new calls the the CSVWriter would overwrite the file existing data. I'm really trying to avoid using databases (maybe SQLite but it seems a bit overkill) because I'm trying to develop this to have no software prerequisites besides Python.","I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed. Is the data only ever going to be parsed by Python programs? If not, then I'd avoid pickle et al (shelve and marshal) since they're very Python specific. JSON and YAML have the important advantage that parsers are easily available for most any language.",0.1618299653758019,False,1,174 2009-05-18 03:15:35.257,"PyQt: splash screen while loading ""heavy"" libraries","My PyQt application that uses matplotlib takes several seconds to load for the first time, even on a fast machine (the second load time is much shorter as the DLLs are kept in memory by Windows). I'm wondering whether it's feasible to show a splash screen while the matplotlib library is being loaded. Where does the actual loading take place - is it when the from line is executed? If so, how can I make this line execute during the splash screen and still be able to use the module throughout the code? A related dilemma is how to test this - can I ask Windows to load the DLLs for every execution and not cache them?","Yes, loading the module takes place at the line where the import statement is. If you create your QApplication and show your splash screen before that, you should be able to do what you want -- also you need to call QApplication.processEvents() whenever you need the splash screen to update with a new message.",1.2,True,1,175 2009-05-20 01:22:36.397,How does MySQL's RENAME TABLE statment work/perform?,"MySQL has a RENAME TABLE statemnt that will allow you to change the name of a table. The manual mentions The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running The manual does not (to my knowedge) state how this renaming is accomplished. Is an entire copy of the table created, given a new name, and then the old table deleted? Or does MySQL do some magic behind the scenes to quickly rename the table? In other words, does the size of the table have an effect on how long the RENAME table statement will take to run. Are there other things that might cause the renaming of a block to significantly block?",I believe MySQL only needs to alter metadata and references to the table's old name in stored procedures -- the number of records in the table should be irrelevant.,1.2,True,1,176 2009-05-25 12:16:07.597,show lyrics on ubuntu,"I'm writing a little script for Ubuntu. My intention is to call rhythmbox lyrics plug-in with a global short-cut (configuring gnome) . I can call it from rhythmbox python console, but I don't know how to import rhythmbox built-in modules (eg. rhythmdb). Any ideas?","You can't import rhythmbox ""built-in"" modules from a standard python console. As far as I know they aren't real modules, they are just objects from the rhythmbox process exposed to plugins. So you can access them only if you are running your script from the rhythmbox process.",0.3869120172231254,False,2,177 2009-05-25 12:16:07.597,show lyrics on ubuntu,"I'm writing a little script for Ubuntu. My intention is to call rhythmbox lyrics plug-in with a global short-cut (configuring gnome) . I can call it from rhythmbox python console, but I don't know how to import rhythmbox built-in modules (eg. rhythmdb). Any ideas?","in this case i guess you'll have to write the whole plugin yourself and , then listen to dbus for change of songs in rhythmbox , to detect which song is being played .",0.0,False,2,177 2009-05-25 18:05:23.203,Making a Python script executable chmod755?,"My hosting provider says my python script must be made to be executable(chmod755). What does this mean & how do I do it? Cheers!","In addition to the other fine answers here, you should be aware that most FTP clients have a chmod command to allow you to set permissions on files at the server. You may not need this if permissions come across properly, but there's a good chance they do not.",0.0,False,1,178 2009-05-28 14:55:26.907,How to compare data of two tables transformed in SSIS package,"A table has been ETLed to another table. My task is to verify the data between two tables programmatically. One of the difficulties I m facing rite now is: how to use the expression that I can get from, let s say, derived column task and verify with the source and destination. or in other words, how can I use the expression to work in the code. Any ideas....highly appreciated Sagar","Set up a column which holds a CHECKSUM() of each row. Do a left outer join between the two tables . If you have any nulls for the right side, you have problems.",0.6730655149877884,False,1,179 2009-06-01 07:14:45.760,Packaging script source files in IronPython and IronRuby,"Does anyone know how to add python and ruby libs as a resource in a dll for deployment? I want to host a script engine in my app, but dont want to have to deploy the entire standard libraries of the respective languages in source files. Is there a simple way to do this so that a require or import statement will find the embedded resources?","IronPython 2.0 has a sample compiler called PYC on Codeplex.com/ironpython which can create DLL's (and applications if you need them too). IronPython 2.6 has a newer version of PYC under Tools\script. Cheers, Davy",0.0,False,2,180 2009-06-01 07:14:45.760,Packaging script source files in IronPython and IronRuby,"Does anyone know how to add python and ruby libs as a resource in a dll for deployment? I want to host a script engine in my app, but dont want to have to deploy the entire standard libraries of the respective languages in source files. Is there a simple way to do this so that a require or import statement will find the embedded resources?","You could add custom import hook that looks for embedded resources when an import is executed. This is slightly complex and probably not worth the trouble. A better technique would be to fetch all of the embedded modules at startup time, execute them with the ScriptEngine and put the modules you have created into the sys.modules dictionary associated with the engine. This automatically makes them available for import by Python code executed by the engine.",0.1352210990936997,False,2,180 2009-06-03 13:19:54.927,How can I check for NaN values?,float('nan') represents NaN (not a number). But how do I check for it?,numpy.isnan(number) tells you if it's NaN or not.,0.9999999999953056,False,1,181 2009-06-04 17:51:31.243,Recursive Function palindrome in Python,I need help writing a recursive function which detects whether a string is a palindrome. But i can't use any loops it must be recursive. Can anyone help show me how this is done . Im using Python.,"If a string is zero or one letters long, it's a palindrome. If a string has the first and last letters the same, and the remaining letters (I think it's a [1: -1] slice in Python, but my Python is a bit rusty) are a palindrome, it's a palindrome. Now, write that as a palindrome function that takes a string. It will call itself.",0.1108597247651115,False,2,182 2009-06-04 17:51:31.243,Recursive Function palindrome in Python,I need help writing a recursive function which detects whether a string is a palindrome. But i can't use any loops it must be recursive. Can anyone help show me how this is done . Im using Python.,"Here's another viewpoint A palindromic string is Some letter, x. Some palindromic substrinng. The same letter, x, repeated. Also, note that you may be given a proper English sentence ""Able was I ere I saw Elba."" with punctuation. Your palindrome checker may have to quietly skip punctuation. Also, you may have to quietly match without considering case. This is slightly more complex. Some leading punctuation. Some letter, x. Some palindromic substring. Some letter, x, repeated without regard to case. Some trailing punctuation. And, by definition, a zero-length string is a palindrome. Also a single-letter string (after removing punctuation) is a palindrome.",0.0740755660660223,False,2,182 2009-06-06 20:33:32.037,how can I add a QMenu and QMenuItems to a window from Qt Designer,Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.,"I have a single main window with a QGraphicsView and lots of QGraphicsItem objects. Each type of the Items have a different context menu. I find that not being able to create the contextMenu's, or at least the actions that are in them a serious limitation of QtDesigner. It means that I can create about 10% or so of the actions using the designer, and I have to create 90% programaticaly. Compare that with the Microsoft resource editor which allows all of these things to be created, and maintained effortlessly. I hope this will be addressed at some point.",0.3869120172231254,False,3,183 2009-06-06 20:33:32.037,how can I add a QMenu and QMenuItems to a window from Qt Designer,Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.,"When you edit a QMainWindow you can right click the window and then choose ""create menu bar"". Or are you talking about a ""context menu"" aka ""right click menu""?",1.2,True,3,183 2009-06-06 20:33:32.037,how can I add a QMenu and QMenuItems to a window from Qt Designer,Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.,"Adding menu editing for every widget in the designer would probably make a very awkward and inconvenient UI. There's really no place you can visualize it on. If you're editing a QMainWindow you can edit the menu bar and its popups because there's a proper place for them to be displayed in.",0.0,False,3,183 2009-06-08 11:30:28.043,how to remove text between using python?,how to remove text between using python?,"If you're removing everything between why not just remove the entire node? Are you expecting a resig-style src and body?",0.0,False,2,184 2009-06-08 11:30:28.043,how to remove text between using python?,how to remove text between using python?,"I don't know Python good enough to tell you a solution. But if you want to use that to sanitize the user input you have to be very, very careful. Removing stuff between and just doesn't catch everything. Maybe you can have a look at existing solutions (I assume Django includes something like this).",-0.0453204071731508,False,2,184 2009-06-09 00:29:59.137,python truncate after a hundreds?,"How can truncate an input like 315.15321531321 I want to truncate all the values after the hundredths position so it becomes 315.15 how do i do that?","You have several options - you can round the number using round(), however this can introduce some inaccuracies (315.15 might round to 315.150000003 for example). If you're just looking to truncate the value of the float when you're displaying it, you can specify the width of the output using printf(""%.2f"", mynumber). This is probably a better solution, since without knowing more about your specific application it's a good idea in general to keep the entire length of the number for calculation.",0.0509761841073563,False,1,185 2009-06-09 19:18:06.150,Django - Website Home Page,"I've been having a look at Django and, from what I've seen, it's pretty darn fantastic. I'm a little confused, however, how I go about implementing a ""home page"" for my website? Would it be a separate app, or just a view within the project, or what?","There's no real rule for this, But one thing I like to do is actually arrange for the index access to redirect to another spot. If you prefer, though, you can just give the index page a plain view. That said, It's probably a good idea to keep all your code in an actual app, so that you can refactor it more easily, and so that it appears on the python path as a normal module. Putting views in the project rather than an app seems to cause more headaches than it solves.",1.2,True,1,186 2009-06-10 03:11:55.320,how to integrate ZSH and (i)python?,"I have been in love with zsh for a long time, and more recently I have been discovering the advantages of the ipython interactive interpreter over python itself. Being able to cd, to ls, to run or to ! is indeed very handy. But now it feels weird to have such a clumsy shell when in ipython, and I wonder how I could integrate my zsh and my ipython better. Of course, I could rewrite my .zshrc and all my scripts in python, and emulate most of my shell world from ipython, but it doesn't feel right. And I am obviously not ready to use ipython as a main shell anyway. So, here comes my question: how do you work efficiently between your shell and your python command-loop ? Am I missing some obvious integration strategy ? Should I do all that in emacs ?","I asked this question on the zsh list and this answer worked for me. YMMV. In genutils.py after the line if not debug: Remove the line: stat = os.system(cmd) Replace it with: stat = subprocess.call(cmd,shell=True,executable='/bin/zsh') you see, the problem is that that ""!"" call uses os.system to run it, which defaults to manky old /bin/sh . Like I said, it worked for me, although I'm not sure what got borked behind the scenes.",1.2,True,1,187 2009-06-10 10:42:38.667,python not starting properly,I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting path. So how do i make it to run properly?,"In your path, I think you need to have both the location of the Python install and the Python\Scripts folder. For example, on XP, I have C:\Python25;C:\Python25\Scripts. Can you verify that you have both?",0.0,False,3,188 2009-06-10 10:42:38.667,python not starting properly,I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting path. So how do i make it to run properly?,"Either use the system control panel to set the PATH environment variable that applies permanently or Reinstall Python as a system administrator so that the installer can set the registry and environment variables for you. If you install the ""just for me"" option, then you have to set the PATH variable in the control panel.",1.2,True,3,188 2009-06-10 10:42:38.667,python not starting properly,I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting path. So how do i make it to run properly?,"you can't run a command that isn't in your path. it should be set globally when you installed python. type 'set' at a dos prompt and look at the PATH variable. c:\python25 (or whever you installed python) has to be in that variable ie PATH=c:\windows;c:\python25;... etc if it isn't in PATH then you or the installer missed the part where you needed to set it. It can be done from the 'Environment Variables' button in the 'System' control panel.",0.1016881243684853,False,3,188 2009-06-10 23:35:16.360,"Vim, Python, and Django autocompletion (pysmell?)","Does anyone know how to set up auto completion to work nicely with python, django, and vim? I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project directory, then I also run pysmell in the project directory. Vim doesn't pick up the django tags, though, and they don't get auto completed. Does anyone know how to set up auto completion in vim so that it will complete the long django functions (like get_object_or_404) as well as classes/functions in my own code? I have poked around on google but haven't found any good resources. Thanks.","I've had good luck with exuberant-ctags for this. I use this macro in my vimrc: execute 'map :!/usr/bin/exuberant-ctags -f '.&tags.' --recurse '.$_P4ROOT.' ' You'll want to modify that slightly, so that it includes your python /site-packages/django/ directory as well as your own code. Then, hit F2 inside vim to update the tags, and use the regular vim tag bindings to navigate.",0.2401167094949473,False,2,189 2009-06-10 23:35:16.360,"Vim, Python, and Django autocompletion (pysmell?)","Does anyone know how to set up auto completion to work nicely with python, django, and vim? I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project directory, then I also run pysmell in the project directory. Vim doesn't pick up the django tags, though, and they don't get auto completed. Does anyone know how to set up auto completion in vim so that it will complete the long django functions (like get_object_or_404) as well as classes/functions in my own code? I have poked around on google but haven't found any good resources. Thanks.","Today, you not need special extentions for django autocomplete in vim. Make sure that you have vim with python support. To check it, type in xterm: vim --version|grep python output: +python -python3 +quickfix +reltime +rightleft -ruby +scrollbind +signs ... ... To make work autocomplete, add this lines in your .vimrc: autocmd FileType python set omnifunc=pythoncomplete#Complete if has(""python"") python import sys,os python sys.path.append('/home/sergey/workspace/django') python os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoProject.settings' endif where: sys.path.append is path to your django workspace directory djangoProject is name of your django project, which is going just after '/home/sergey/workspace/django' Finally, save it and restart vim. Now, after '.', you press default ctrl-x ctrl-o to get your autocomplete.",0.1618299653758019,False,2,189 2009-06-12 05:28:54.720,How to specify native library search path for python,"I have installed lxml which was built using a standalone version of libxml2. Reason for this was that the lxml needed a later version of libxml2 than what was currently installed. When I use the lxml module how do I tell it (python) where to find the correct version of the libxml2 shared library?","Assuming you're talking about a .so file, it's not up to Python to find it -- it's up to the operating system's dynamic library loaded. For Linux, for example, LD_LIBRARY_PATH is the environment variable you need to set.",1.2,True,1,190 2009-06-15 09:15:37.030,Using python regex to extract namespaces from C++ sources,"I am trying to extract the namespaces defined in C++ files. Basically, if my C++ file contains: namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 I want to be able to retrieve: n1, n1::n2, n1::n3. Does someone have any suggestion of how I could do that using python-regex? Thanks.","The need is simple enough that you may not need a complex parser. You need to: extract the namespace names count the open/close braces to keep track of where your namespace is defined. This simple approach works if the other conditions are met: you don't get spurious namespace like strings inside comments or inside strings you don't get unmatched open/closeing braces inside comments or strings I don't think this is too much asking from your source.",0.1352210990936997,False,5,191 2009-06-15 09:15:37.030,Using python regex to extract namespaces from C++ sources,"I am trying to extract the namespaces defined in C++ files. Basically, if my C++ file contains: namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 I want to be able to retrieve: n1, n1::n2, n1::n3. Does someone have any suggestion of how I could do that using python-regex? Thanks.","Searching for the namespace names is pretty easy with a regular expression. However, to determine the nesting level you will have to keep track of the curly bracket nesting level in the source file. This is a parsing problem, one that cannot be solved (sanely) with regular expressions. Also, you may have to deal with any C preprocessor directives in the file which can definitely affect parsing. C++ is a notoriously tricky language to parse completely, but you may be able to get by with a tokeniser and a curly bracket counter.",0.3869120172231254,False,5,191 2009-06-15 09:15:37.030,Using python regex to extract namespaces from C++ sources,"I am trying to extract the namespaces defined in C++ files. Basically, if my C++ file contains: namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 I want to be able to retrieve: n1, n1::n2, n1::n3. Does someone have any suggestion of how I could do that using python-regex? Thanks.",You could write a basic lexer for it. It's not that hard.,0.0679224682270276,False,5,191 2009-06-15 09:15:37.030,Using python regex to extract namespaces from C++ sources,"I am trying to extract the namespaces defined in C++ files. Basically, if my C++ file contains: namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 I want to be able to retrieve: n1, n1::n2, n1::n3. Does someone have any suggestion of how I could do that using python-regex? Thanks.","Most of the time when someone asks how to do something with regex, they're doing something very wrong. I don't think this case is different. If you want to parse c++, you need to use a c++ parser. There are many things that can be done that will defeat a regex but still be valid c++.",0.0,False,5,191 2009-06-15 09:15:37.030,Using python regex to extract namespaces from C++ sources,"I am trying to extract the namespaces defined in C++ files. Basically, if my C++ file contains: namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 I want to be able to retrieve: n1, n1::n2, n1::n3. Does someone have any suggestion of how I could do that using python-regex? Thanks.","That is what I did earlier today: Extract the comment out of the C++ files Use regex to extract the namespace definition Use a simple string search to get the open & close braces positions The various sanity check added show that I am successfully processing 99.925% of my files (5 failures ouf of 6678 files). The issues are due to mismatches in numbers of { and } cause by few '{' or '}' in strings, and unclean usage of the preprocessor instruction. However, I am only dealing with header files, and I own the code. That limits the number of scenari that could cause some issues and I can manually modify the ones I don't cover. Of course I know there are plenty of cases where it would fail but it is probably enough for what I want to achieve. Thanks for your answers.",0.0,False,5,191 2009-06-15 19:25:28.390,System theme icons and PyQt4,"I'm writing a basic program in python using the PyQt4 module. I'd like to be able to use my system theme's icons for things like the preference dialog's icon, but i have no idea how to do this. So my question is, how do you get the location of an icon, but make sure it changes with the system's icon theme? If it matters, i'm developing this under ubuntu 9.04, so i am using the gnome desktop.","I spent a decent amount of researching this myself not long ago, and my conclusion was that, unfortunately, Qt doesn't provide this functionality in a cross-platform fashion. Ideally the QIcon class would have defaults for file open, save, '+', '-', preferences, etc, but considering it doesn't you'll have to grab the appropriate icon for your desktop environment.",0.0,False,1,192 2009-06-16 14:09:44.313,How To Reversibly Store Password With Python On Linux?,"First, my question is not about password hashing, but password encryption. I'm building a desktop application that needs to authentificate the user to a third party service. To speed up the login process, I want to give the user the option to save his credentials. Since I need the password to authentificate him to the service, it can't be hashed. I thought of using the pyCrypto module and its Blowfish or AES implementation to encrypt the credentials. The problem is where to store the key. I know some applications store the key directly in the source code, but since I am coding an open source application, this doesn't seem like a very efficient solution. So I was wondering how, on Linux, you would implement user specific or system specific keys to increase password storing security. If you have a better solution to this problem than using pyCrypto and system/user specific keys, don't hesitate to share it. As I said before, hashing is not a solution and I know password encryption is vulnerable, but I want to give the option to the user. Using Gnome-Keyring is not an option either, since a lot of people (including myself) don't use it.","Encrypting the passwords doesn't really buy you a whole lot more protection than storing in plaintext. Anyone capable of accessing the database probably also has full access to your webserver machines. However, if the loss of security is acceptable, and you really need this, I'd generate a new keyfile (from a good source of random data) as part of the installation process and use this. Obviously store this key as securely as possible (locked down file permissions etc). Using a single key embedded in the source is not a good idea - there's no reason why seperate installations should have the same keys.",1.2,True,1,193 2009-06-16 18:50:48.037,Number of visitors in Django,"In Django, how can I see the number of current visitors? Or how do I determine the number of active sessions? Is this a good method? use django.contrib.sessions.models.Session, set the expiry time short. Every time when somebody does something on the site, update expiry time. Then count the number of sessions that are not expired.","Edit: Added some more information about why I present this answer here. I found chartbeat when I tried to answer this same question for my django based site. I don't work for them. Not specifically Django, but chartbeat.com is very interesting to add to a website as well. django-tracking is great, +1 for that answer, etc. Couple of things I could not do with django-tracking, that chartbeat helped with; tracked interactions with completely cached pages which never hit the django tracking code and pages not delivered through django (e.g. wordpress, etc.)",-0.2012947653214861,False,1,194 2009-06-18 17:57:24.017,wxPython: how to make two toolbars use one statusbar for tooltips?,"I have an interface that has two toolbars, one attached to the frame and one embedded in a notebook tab. The one in the frame dutifully shows longHelp strings in the statusbar, the one in the notebook tab does not. How do I tell the one on the notebook tab where to display its help, or do I have to manage enter and leave bindings myself?","from wxPython docs """""" longHelpString This string is shown in the statusbar (if any) of the parent frame when the mouse pointer is inside the tool """""" so toolbar in notebook doesn't get any statusbar to display long help, so either thru src we should invertigate how it inquires abt status bar and supply a ref to main frame status bar else i think better way is to just override wxToolBar::OnMouseEnter and display help directly on status bar",0.0,False,1,195 2009-06-19 04:04:12.297,Synthesis of general programming language (Python) with tailored language (PureData/MaxMSP/ChucK),"I am learning Python because it appeals to me as a mathematician but also has many useful libraries for scientific computing, image processing, web apps, etc etc. It is frustrating to me that for certain of my interests (eletronic music or installation art) there are very specific programming languages which seem better suited to these purposes, such as Max/MSP, PureData, and ChucK -- all quite fascinating. My question is, how should one approach these different languages? Should I simply learn Python and manage the others by using plugins and Python interpreters in them? Are there good tools for integrating the languages, or is the proper way simply to learn all of them?","I would say learn them all. While it's true that many languages can do many things, specialised languages are usually more expressive and easier to use for a particular task. Case-in-point is while most languages allow shell interaction and process control very few are as well suited to the task as bash scripts. Plugins and libraries can bridge the gap between general and specialised languages but in my experience this is not always without drawbacks - be they speed, stability or complexity. It isn't uncommon to have to compile additional libraries or apply patches or use untrusted and poorly supported modules. It also isn't uncommon that the resulting interface is still harder to use than the original language. I know about 15 languages well and a few of those very well. I do not use my prefered languages when another is more suitable.",1.2,True,2,196 2009-06-19 04:04:12.297,Synthesis of general programming language (Python) with tailored language (PureData/MaxMSP/ChucK),"I am learning Python because it appeals to me as a mathematician but also has many useful libraries for scientific computing, image processing, web apps, etc etc. It is frustrating to me that for certain of my interests (eletronic music or installation art) there are very specific programming languages which seem better suited to these purposes, such as Max/MSP, PureData, and ChucK -- all quite fascinating. My question is, how should one approach these different languages? Should I simply learn Python and manage the others by using plugins and Python interpreters in them? Are there good tools for integrating the languages, or is the proper way simply to learn all of them?","This thread is a little old, but I wanted to point out that the majority of the mature audio development environments e.g. supercollider/max-msp/pure data can be controlled via open sound control. You can google up a better description of OSC, but suffice it to say that it allows you to send control data to synths built in these environments similar to how MIDI works, but way more extensive. This does not solve the problem of actually building synths in python per se but it allows you to ""drive"" these other environments without having to know the ins and outs of the language.",0.3869120172231254,False,2,196 2009-06-19 19:35:07.567,Sandboxing in Linux,"I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications. So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option. The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method? What would be the best way to go about this - other than ""don't do it at all""? :) What other glaring security problems have I missed? FWIW, the web app will be written in Python.",Spawning a new VM under KVM or qemu to compile and run the code looks like the way to go. Running the code under jail/LXC can compromise the machine if it exploits the unsecured parts of the OS like networking code. Advantage of running under a VM are obvious. One can only hack the VM but not the machine itself. But the side effect is you need lots of resources (CPU and Memory) to spawn a VM for each request.,0.0,False,3,197 2009-06-19 19:35:07.567,Sandboxing in Linux,"I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications. So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option. The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method? What would be the best way to go about this - other than ""don't do it at all""? :) What other glaring security problems have I missed? FWIW, the web app will be written in Python.","I think your solutions must concentrate on analyzing the source code. I don't know any tools, and I think this would be pretty hard with C, but, for example, a Pascal program which doesn't include any modules would be pretty harmless in my opinion.",0.0,False,3,197 2009-06-19 19:35:07.567,Sandboxing in Linux,"I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications. So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option. The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method? What would be the best way to go about this - other than ""don't do it at all""? :) What other glaring security problems have I missed? FWIW, the web app will be written in Python.","About the only chance you have is running a VirtualMachine and those can have vulnerabilities. If you want your machine hacked in the short term just use permissions and make a special user with access to maybe one directory. If you want to postpone the hacking to some point in the future then run a webserver inside a virtual machine and port forward to that. You'll want to keep a backup of that because you'll probably have that hacked in under an hour and want to restart a fresh copy every few hours. You'll also want to keep an image of the whole machine to just reimage the whole thing once a week or so in order to overcome the weekly hackings. Don't let that machine talk to any other machine on your network. Blacklist it everywhere. I'm talking about the virtual machine and the physical machine IP addresses. Do regular security audits on any other machines on your other machines on the network. Please rename the machines IHaveBeenHacked1 and IHaveBeenHacked2 and prevent access to those in your hosts lists and firewalls. This way you might stave off your level of hackage for a while.",-0.0679224682270276,False,3,197 2009-06-21 23:31:10.947,What's the best way to implement web service for ajax autocomplete,"I'm implementing a ""Google Suggest"" like autocomplete feature for tag searching using jQuery's autocomplete. I need to provide a web service to jQuery giving it a list of suggestions based on what the user has typed. I see 2 ways of implementing the web service: 1) just store all the tags in a database and search the DB using user input as prefix. This is simple, but I'm concerned about latency. 2) Use an in-process trie to store all the tags and search it for matching results. As everything will be in-process, I expect this to have much lower latency. But there are several difficulties: -What's a good way to initialize the trie on process start up? Presumable I'll store the tag data in a DB and retrieve them and turn them into a trie when I frist start up the process. But I'm not sure how. I'm using Python/Django. -When a new tag is created by a user, I need to insert the new tag into the trie. But let's say I have 5 Django processes and hence 5 tries, how do I tell the other 4 tries that they need to insert a new tag too? -How to make sure the trie is threadsafe as my Django processes will be threaded (I'm using mod_wsgi). Or do I not have to worry about threadsafty because of Python's GIL? -Any way I can store the tag's frequency of use within the trie as well? How do I tell when does the tag's string end and when does the frequency start - eg. if I store apple213 into the trie, is it ""apple"" with frequency 213 or is it ""apple2"" with frequency 13?? Any help on the issues above or any suggestions on a different approach would be really appreciated.","I would use the first option. 'KISS' - (Keep It Simple Stupid). For small amounts of data there shouldn't be much latency. We run the same kind of thing for a name search and results appear pretty quickly on a few thousand rows. Hope that helps, Josh",0.2012947653214861,False,1,198 2009-06-23 14:24:51.560,how to addreference to Ritmo for iSeries in ironpython,"I was just wondering if anybody knows how to add reference to ""Ritmo for iSeries"" in IronPython. I did it successfully in C# and get it to work (since it is just click click click) And I was trying to do the same in IronPython but it says, ""could not add reference to assembly Ritmo for iSeries"". I was doing import clr clr.AddReference('Ritmo for iSeries') from Ritmo........ IOError: Could not add reference to assembly Ritmo for iSeries","Jonathan helped me to figure out that I had not copied the dll file to the location where IronPython can find it. After copying the dll file to the location, usually it s ""c:\Program Files\IronPython 2.0\"" unless stated otherwise, I did: import clr clr.AddReference('System.Data') clr.AddReferenceToFile('Sql400.dll') from System.Data import Sql400 from System.Data.Sql400 import *",0.0,False,2,199 2009-06-23 14:24:51.560,how to addreference to Ritmo for iSeries in ironpython,"I was just wondering if anybody knows how to add reference to ""Ritmo for iSeries"" in IronPython. I did it successfully in C# and get it to work (since it is just click click click) And I was trying to do the same in IronPython but it says, ""could not add reference to assembly Ritmo for iSeries"". I was doing import clr clr.AddReference('Ritmo for iSeries') from Ritmo........ IOError: Could not add reference to assembly Ritmo for iSeries","You need to use the actual name of the assembly (it won't have spaces). In your C# project, what does it list under the 'references' folder once you've added it as a reference? Try putting that. Also, make sure you've copied the dll for the library to where your IronPython script can find it (if it's not in the GAC).",0.0,False,2,199 2009-06-24 12:54:21.517,HTML conversion,"How to convert HTML CSS file to wxPython files? That is, how to create slidsheet in wxPython like HTML CSS files?","stylesheet, not slidesheet. f = open('NAMEOFSTYLESHEET.css','w') f.write('#ID{}\n.class{}')",0.0,False,1,200 2009-06-25 11:19:47.427,Encrypt a string using a public key,"I need to take a string in Python and encrypt it using a public key. Can anyone give me an example or recommendation about how to go about doing this?","I looked at the ezPyCrypto library that was recommended in another answer. Please don't use this library. It is very incomplete and in some cases incorrect and highly insecure. Public key algorithms have many pitfalls and need to be implemented carefully. For example, RSA message should use a padding scheme such as PKCS #1, OAEP etc to be secure. This library doesn't pad. DSA signatures should use the SHA1 hash function. This library uses the broken MD5 hash and there is even a bigger bug in the random number generation. Hence the DSA implementation is neither standards conform nor secure. ElGamal is also implemented incorrectly. Following standards does make implementations somewhat more complex. But not following any is not an option. At least not if you care about security.",0.2012947653214861,False,1,201 2009-06-25 11:59:01.843,Best Practise for transferring a MySQL table to another server?,"I have a system sitting on a ""Master Server"", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web. Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solution for this. Currently I'm looking into: XMLRPC RestFul Services a simple POST to a processing script socket transfers The app on my master is a TurboGears app, so I would prefer ""pythonic"" aka less ugly solutions. Copying a dumped table to another server via FTP / SCP or something like that might be quick, but in my eyes it is also very (quick and) dirty, and I'd love to have a nicer solution. Can anyone describe shortly how you would do this the ""best-practise"" way? This doesn't necessarily have to involve Databases. Dumping the table on Server1 and transferring the raw data in a structured way so server2 can process it without parsing too much is just as good. One requirement though: As soon as the data arrives on server2, I want it to be processed, so there has to be a notification of some sort when the transfer is done. Of course I could just write my whole own server sitting on a socket on the second machine and accepting the file with own code and processing it and so forth, but this is just a very very small piece of a very big system, so I dont want to spend half a day implementing this. Thanks, Tom","Assuming your situation allows this security-wise, you forgot one transport mechanism: simply opening a mysql connection from one server to another. Me, I would start by thinking about one script that ran regularly on the write server and opens a read only db connection to the read server (A bit of added security) and a full connection to it's own data base server. How you then proceed depends on the data (is it just inserts to deal with? do you have to mirror deletes? how many inserts vs updates? etc) but basically you could write a script that pulled data from the read server and processed it immediately into the write server. Also, would mysql server replication work or would it be to over-blown as a solution?",0.0,False,2,202 2009-06-25 11:59:01.843,Best Practise for transferring a MySQL table to another server?,"I have a system sitting on a ""Master Server"", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web. Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solution for this. Currently I'm looking into: XMLRPC RestFul Services a simple POST to a processing script socket transfers The app on my master is a TurboGears app, so I would prefer ""pythonic"" aka less ugly solutions. Copying a dumped table to another server via FTP / SCP or something like that might be quick, but in my eyes it is also very (quick and) dirty, and I'd love to have a nicer solution. Can anyone describe shortly how you would do this the ""best-practise"" way? This doesn't necessarily have to involve Databases. Dumping the table on Server1 and transferring the raw data in a structured way so server2 can process it without parsing too much is just as good. One requirement though: As soon as the data arrives on server2, I want it to be processed, so there has to be a notification of some sort when the transfer is done. Of course I could just write my whole own server sitting on a socket on the second machine and accepting the file with own code and processing it and so forth, but this is just a very very small piece of a very big system, so I dont want to spend half a day implementing this. Thanks, Tom","Server 1: Convert rows to JSON, call the RESTful api of second with JSON data Server 2: listens on a URI e.g. POST /data , get json data convert back to dictionary or ORM objects, insert into db sqlalchemy/sqlobject and simplejson is what you need.",1.2,True,2,202 2009-06-26 10:44:01.177,Hiding characters typed into password field,"I am developing an student attendance application in wxpython and I need to know how to ensure that password field doesn't echo characters to the screen. Forexample :if I give the name as moni means then it should be displayed as in format of ****","You need to give your text control the TE_PASSWORD style. (As Jørn's comment points out, this isn't ""encryption"" - I'm assuming you're only talking about the visual presentation of the password.)",0.3869120172231254,False,1,203 2009-06-26 16:39:30.670,"Get remote text file, process, and update database - approach and scripting language to use?","I've been having to do some basic feed processing. So, get a file via ftp, process it (i.e. get the fields I care about), and then update the local database. And similarly the other direction: get data from db, create file, and upload by ftp. The scripts will be called by cron. I think the idea would be for each type of feed, define the ftp connection/file information. Then there should be a translation of how data fields in the file relate to data fields that the application can work with (and of course process this translation). Additionally write separate scripts that do the common inserting functions for the different objects that may be used in different feeds. As an e-commerce example, lets say I work with different suppliers who provide feeds to me. The feeds can be different (object) types: product, category, or order information. For each type of feed I obviously work with different fields and call different update or insert scripts. What is the best language to implement this in? I can work with PHP but am looking for a project to start learning Perl or Python so this could be good for me as well. If Perl or Python, can you briefly give high level implementation. So how to separate the different scripts, object oriented approach?, how to make it easy to implement new feeds or processing functions in the future, etc. [full disclosure: There were already classes written in PHP which I used to create a new feed recently. I already did my job, but it was super messy and difficult to do. So this question is not 'Please help me do my job' but rather a 'best approach' type of question for my own development.] Thanks!","Most modern languages scripting languages allow you to do all of these things. Because of that, I think your choice of language should be based on what you and the people who read your code know. In Perl I'd make use of the following modules: Net::FTP to access the ftp sites. DBI to insert data into your database. Modules like that are nice reusable pieces of code that you don't have to write, and interaction with ftp sites and databases are so common that every modern scripting language should have similar modules. I don't think that PHP is a great language so I'd avoid it if possible, but it might make sense for you if you have a lot of experience in it.",0.1016881243684853,False,1,204 2009-06-27 22:41:01.413,Changing python interpreter windows,"I have two python installations, 2.5 and 2.6 I want to change the default python interpreter from 2.5 to 2.6. Anyone know how?","PYTHONPATH is NOT what you are looking for. That is for varying where Python's ""import"" looks for packages and modules. You need to change the PATH variable in your environment so that it contains e.g. ""....;c:\python26;...."" instead of ""....;c:\python25;...."". Click on start > control panel > system > advanced > environment variables. Select ""path"". Edit it. Click on OK enough times to get out of there.",1.2,True,2,205 2009-06-27 22:41:01.413,Changing python interpreter windows,"I have two python installations, 2.5 and 2.6 I want to change the default python interpreter from 2.5 to 2.6. Anyone know how?","just FYI, since both c:\python25 and c:\python26 are on PATH, I copy C:\Python25\python.exe to C:\Python25\py25.exe, and copy C:\Python26\python.exe to C:\Python26\py26.exe Then just type py25(or py26) get the specific version.",0.2012947653214861,False,2,205 2009-06-30 13:14:59.567,how to use french letters in a django template?,"I have some french letters (é, è, à...) in a django template but when it is loaded by django, an UnicodeDecodeError exception is raised. If I don't load the template but directly use a python string. It works ok. Is there something to do to use unicode with django template?","You are probably storing the template in a non-unicode encoding, such as latin-1. I believe Django assumes that templates are in UTF-8 by default (though there is a setting to override this). Your editor should be capable of saving the template file in the UTF-8 encoding (probably via a dropdown on the save as page, though this may depend on your editor). Re-save the file as UTF-8, and the error should go away.",1.2,True,1,206 2009-06-30 13:45:12.203,"In Python, Using pyodbc, How Do You Perform Transactions?","I have a username which I must change in numerous (up to ~25) tables. (Yeah, I know.) An atomic transaction seems to be the way to go for this sort of thing. However, I do not know how to do this with pyodbc. I've seen various tutorials on atomic transactions before, but have never used them. The setup: Windows platform, Python 2.6, pyodbc, Microsoft SQL 2005. I've used pyodbc for single SQL statements, but no compound statements or transactions. Best practices for SQL seem to suggest that creating a stored procedure is excellent for this. My fears about doing a stored procedure are as follows, in order of increasing importance: 1) I have never written a stored procedure. 2) I heard that pyodbc does not return results from stored procedures as of yet. 3) This is most definitely Not My Database. It's vendor-supplied, vendor-updated, and so forth. So, what's the best way to go about this?",I don't think pyodbc has any specific support for transactions. You need to send the SQL command to start/commit/rollback transactions.,-0.9999092042625952,False,1,207 2009-07-02 16:16:07.920,How to debug SCons scripts using eclipse and pydev?,I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?,"I'm not an Eclipse expert, but since you didn't get any other answer... If you make the SCons source a part of the Eclipse project, and run the whole command from within Eclipse it should work like any Eclipse debugging. SCons is written in Python, there is no reason it shouldn't be debuggable in Eclipse just like anything else.",1.2,True,5,208 2009-07-02 16:16:07.920,How to debug SCons scripts using eclipse and pydev?,I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?,"You are right. Since the SCons is python based, the SCons scripts are debuggable via EClipse PyDev. For this, you need to do the following in the debug configuration... 1. Under the main tab, set the main module to the SCons file which will be available under the python/scripts directory if you have installed SCons. If you have not run the install of SCons you can point to this file under the SCons directory. 2. Under the arguments tab, set the working directory to the root of your project. Now set the breakpoint either on SConstruct or SConcript and run in debug mode. That's all!! With this approach you can not only debug your product code but also the build scripts that builds your product :-) Happy Debugging!!!!",0.3869120172231254,False,5,208 2009-07-02 16:16:07.920,How to debug SCons scripts using eclipse and pydev?,I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?,"I've since gain more experience with SCons / Python and I'd recommend using python's pdb module. To use it simply add the following code to your SCons/Python files. import pdb; pdb.set_trace() When the file is run from the command line a breakpoint will be hit at this line. I also moved away from Eclipse. A lightweight editor will be just as good for Python development. I use Sublime.",0.0,False,5,208 2009-07-02 16:16:07.920,How to debug SCons scripts using eclipse and pydev?,I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?,"On MAC to debug scons through pydev follow Lennart's answer but with one simply addition. Using Finder (or terminal) browse to where scons is installed. You can find this with the ""which"" command. e.g. which scons -> /usr/local/bin/scons Make a copy of the scons file and call it scons.py. Now when you create the Debug Configuration in Eclipse use scons.py as the ""Main Module"". PS: To add a scons project to Eclipse I found it easier to use a ""Linked Folder"" pointing at /usr/local/bin/. i.e. Because I was getting a read-only error when trying to add the directory itself.",0.0679224682270276,False,5,208 2009-07-02 16:16:07.920,How to debug SCons scripts using eclipse and pydev?,I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?,"As an addendum: on Windows, I had to copy the scons-installed files to reside under C:\Python27\Lib\site-packages\scons in order for this to work. Adding the original installed location, qualified with the version number, to the PYTHONPATH, did not work.",0.0,False,5,208 2009-07-03 03:24:31.120,Windows Application Programming & wxPython,"Developing a project of mine I realize I have a need for some level of persistence across sessions, for example when a user executes the application, changes some preferences and then closes the app. The next time the user executes the app, be it after a reboot or 15 minutes, I would like to be able to retain the preferences that had been changed. My question relates to this persistence. Whether programming an application using the win32 API or the MFC Framework .. or using the newer tools for higher level languages such as wxPython or wxRuby, how does one maintain the type of persistence I refer to? Is it done as a temporary file written to the disk? Is it saved into some registry setting? Is there some other layer it is stored in that I am unaware of?","I would advice to do it in two steps. First step is to save your prefs. as string, for that you can a) Use any xml lib or output xml by hand to output string and read similarly from string b) Just use pickle module to dump your prefs object as a string c) Somehow generate a string from prefs which you can read back as prefs e.g. use yaml, config , JSON etc actually JSON is a good option when simplejson makes it so easy. Once you have your methods to convert to and from string are ready, you just need to store it somewhere where it is persisted and you can read back next time, for that you can a) Use wx.Config which save to registry in windows and to other places depending on platform so you don't have to worry where it saves, you can just read back values in platform independent way. But if you wish you can just use wx.Config for directly saving reading prefs. b) Directly save prefs. string to a file in a folder assigned by OS to your app e.g. app data folder in windows. Benefit of saving to a string and than using wx.Config to save it, is that you can easily change where data is saved in future e.g. in future if there is a need to upload prefs. you can just upload prefs. string.",1.2,True,1,209 2009-07-06 03:33:04.817,how to make table partitions?,"I am not very familiar with databases, and so I do not know how to partition a table using SQLAlchemy. Your help would be greatly appreciated.","Automatic partitioning is a very database engine specific concept and SQLAlchemy doesn't provide any generic tools to manage partitioning. Mostly because it wouldn't provide anything really useful while being another API to learn. If you want to do database level partitioning then do the CREATE TABLE statements using custom Oracle DDL statements (see Oracle documentation how to create partitioned tables and migrate data to them). You can use a partitioned table in SQLAlchemy just like you would use a normal table, you just need the table declaration so that SQLAlchemy knows what to query. You can reflect the definition from the database, or just duplicate the table declaration in SQLAlchemy code. Very large datasets are usually time-based, with older data becoming read-only or read-mostly and queries usually only look at data from a time interval. If that describes your data, you should probably partition your data using the date field. There's also application level partitioning, or sharding, where you use your application to split data across different database instances. This isn't all that popular in the Oracle world due to the exorbitant pricing models. If you do want to use sharding, then look at SQLAlchemy documentation and examples for that, for how SQLAlchemy can support you in that, but be aware that application level sharding will affect how you need to build your application code.",0.3869120172231254,False,1,210 2009-07-07 22:55:08.403,Matrix from Python to MATLAB,"I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? Thanks!","I would probably use numpy.savetxt('yourfile.mat',yourarray) in Python and then yourarray = load('yourfile.mat') in MATLAB.",0.283556384140347,False,2,211 2009-07-07 22:55:08.403,Matrix from Python to MATLAB,"I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? Thanks!",You could write the matrix in Python to a CSV file and read it in MATLAB using csvread.,0.229096917477335,False,2,211 2009-07-11 05:45:38.637,List of installed fonts OS X / C,"I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how?","Do you want to write a program to do it, or do you want to use a program to do it? There are many programs that list fonts, xlsfonts comes to mind.",0.0814518047658113,False,1,212 2009-07-11 06:02:43.720,How to keep an App Engine/Java app running with deaf requests from a Java/Python web cron?,"App Engine allows you 30 seconds to load your application My application takes around 30 seconds - sometimes more, sometimes less. I don't know how to fix this. If the app is idle (does not receive a request for a while), it needs to be re-loaded. So, to avoid the app needing to be reloaded, I want to simulate user activity by pinging the app every so often. But there's a catch . . . If I ping the app and it has already been unloaded by App Engine, my web request will be the first request to the app and the app will try to reload. This could take longer than 30 seconds and exceed the loading time limit. So my idea is to ping the app but not wait for the response. I have simulated this manually by going to the site from a browser, making the request and immediately closing the browser - it seems to keep the app alive. Any suggestions for a good way to do this in a Python or Java web cron (I'm assuming a Python solution will be simpler)?","App engine also has a new PAY feature where you can have it ""always-on"". Costs about $0.30 USD cents a day. Just go into your billing settings and enable it if you don't mind paying for the feature. I believe it guarantees you at least 3 instances always running. (I didn't realize hitting a /ping url which caused an instance to spin up would cause it to exceed the 30 sec limit!)",0.1016881243684853,False,1,213 2009-07-11 18:11:18.877,How do I check if a process is alive in Python on Linux?,"I have a process id in Python. I know I can kill it with os.kill(), but how do I check if it is alive ? Is there a built-in function or do I have to go to the shell?","os.kill does not kill processes, it sends them signals (it's poorly named). If you send signal 0, you can determine whether you are allowed to send other signals. An error code will indicate whether it's a permission problem or a missing process. See man 2 kill for more info. Also, if the process is your child, you can get a SIGCHLD when it dies, and you can use one of the wait calls to deal with it.",0.999823161659962,False,1,214 2009-07-14 15:19:21.097,Python: Persistent shell variables in subprocess,"I'm trying to execute a series of commands using Pythons subprocess module, however I need to set shell variables with export before running them. Of course the shell doesn't seem to be persistent so when I run a command later those shell variables are lost. Is there any way to go about this? I could create a /bin/sh process, but how would I get the exit codes of the commands run under that?","subprocess.Popen takes an optional named argument env that's a dictionary to use as the subprocess's environment (what you're describing as ""shell variables""). Prepare a dict as you need it (you may start with a copy of os.environ and alter that as you need) and pass it to all the subprocess.Popen calls you perform.",1.2,True,1,215 2009-07-14 17:28:02.430,Best way to have full Python install under cygwin/XP?,"Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.","Just a little off the question, but... Have you considered running Sun's VirtualBox with Fedora or Ubuntu inside of it? I'm assuming you have to / need to use windows because you still are, but don't like it. Then you would have python running inside a native linux desktop without any of the troubles you mentioned. And if you want something that is really easy and portable, then just use Python on Windows, not mixed in with cygwin. $0.02",0.0,False,4,216 2009-07-14 17:28:02.430,Best way to have full Python install under cygwin/XP?,"Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.","I use Python from within cygwin, but I don't use the version that cygwin gives you the option of installing as I don't have the control over version number used that I need (we use an older version at work). I have my python version installed via the windows installer (the xp version as you put it) and add the /cygdrive/c/Python2x directory to my PATH environment variable.",1.2,True,4,216 2009-07-14 17:28:02.430,Best way to have full Python install under cygwin/XP?,"Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.","I accidentally stumbled on this - If I launch Cygwin from the Cygwin.bat file (which is present directly under the main folder), I get access to the Python version installed under Cygwin (i.e 2.6.8) If I instead launch the Cygwin from bash.exe under bin directory (C:\Cygwin\bin\bash.exe for me), running ""Python -V"" shows that I have access to 2.7.3 version of Python (that was installed for Windows). So, I guess you can do the same.",0.0,False,4,216 2009-07-14 17:28:02.430,Best way to have full Python install under cygwin/XP?,"Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.","This probably has little value, but... I found myself in this exact situation -- we use ActivePython2.5 in production (pure windows environment) and I was trying to do my development within cygwin and cygwin's Python... After ripping out half of my hair, I have now switched over to Console2, gvim, iPython and ActivePython2.5. I'm less than thrilled dealing with Windows tools (and their concomitant warts), but at least I'm not getting in my own way when it comes to development. For a while I found I was spending more time trying to get my tools to play nice than actually getting any work done. Good luck on this one.",0.0,False,4,216 2009-07-14 20:29:34.933,Python object has no referrers but still accessible via a weakref?,"Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference? If so how would I start trying to identify the cause for this object not being garbage collected? Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers(). Edit: Solved. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.","I am glad you have found your problem, unrelated to the initial question. Nonetheless, I have a different take on the answer for posterity, in case others have the problem. It IS legal for the object to have no referrers and yet not be garbage collected. From the Python 2.7 manual: ""An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable."" The NO-OP garbage collector is legal. The discussions about generational and reference-counting garbage collectors are referring to a particular CPython implementation (as tagged in the question)",0.0814518047658113,False,2,217 2009-07-14 20:29:34.933,Python object has no referrers but still accessible via a weakref?,"Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference? If so how would I start trying to identify the cause for this object not being garbage collected? Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers(). Edit: Solved. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.","It might also be the case that a reference was leaked by a buggy C extension, IMHO you will not see the referer, yet still the refcount does not go down to 0. You might want to check the return value of sys.getrefcount.",0.0814518047658113,False,2,217 2009-07-15 03:15:27.133,creating non-reloading dynamic webapps using Django,"As far as I know, for a new request coming from a webapp, you need to reload the page to process and respond to that request. For example, if you want to show a comment on a post, you need to reload the page, process the comment, and then show it. What I want, however, is I want to be able to add comments (something like facebook, where the comment gets added and shown without having to reload the whole page, for example) without having to reload the web-page. Is it possible to do with only Django and Python with no Javascript/AJAX knowledge? I have heard it's possible with AJAX (I don't know how), but I was wondering if it was possible to do with Django. Thanks,","Maybe a few iFrames and some Comet/long-polling? Have the comment submission in an iFrame (so the whole page doesn't reload), and then show the result in the long-polled iFrame... Having said that, it's a pretty bad design idea, and you probably don't want to be doing this. AJAX/JavaScript is pretty much the way to go for things like this. I have heard it's possible with AJAX...but I was wondering if it was possible to do with Django. There's no reason you can't use both - specifically, AJAX within a Django web application. Django provides your organization and framework needs (and a page that will respond to AJAX requests) and then use some JavaScript on the client side to make AJAX calls to your Django-backed page that will respond correctly. I suggest you go find a basic jQuery tutorial which should explain enough basic JavaScript to get this working.",0.1016881243684853,False,2,218 2009-07-15 03:15:27.133,creating non-reloading dynamic webapps using Django,"As far as I know, for a new request coming from a webapp, you need to reload the page to process and respond to that request. For example, if you want to show a comment on a post, you need to reload the page, process the comment, and then show it. What I want, however, is I want to be able to add comments (something like facebook, where the comment gets added and shown without having to reload the whole page, for example) without having to reload the web-page. Is it possible to do with only Django and Python with no Javascript/AJAX knowledge? I have heard it's possible with AJAX (I don't know how), but I was wondering if it was possible to do with Django. Thanks,","You want to do that with out any client side code (javascript and ajax are just examples) and with out reloading your page (or at least part of it)? If that is your question, then the answer unfortunately is you can't. You need to either have client side code or reload your page. Think about it, once the client get's the page it will not change unless The client requests the same page from the server and the server returns and updated one the page has some client side code (eg: javascript) that updates the page. I can not imagine a third possibility. I have not coded in Django for more than 30 mins and this is clearly obvious to me. If I am wrong plz down vote :D",1.2,True,2,218 2009-07-17 22:18:26.670,"How to override Py_GetPrefix(), Py_GetPath()?","I'm trying to embed the Python interpreter and need to customize the way the Python standard library is loaded. Our library will be loaded from the same directory as the executable, not from prefix/lib/. We have been successful in making this work by manually modifying sys.path after calling Py_Initialize(), however, this generates a warning because Py_Initialize is looking for site.py in ./lib/, and it's not present until after Py_Initialize has been called and we have updated sys.path. The Python c-api docs hint that it's possible to override Py_GetPrefix() and Py_GetPath(), but give no indication of how. Does anyone know how I would go about overriding them?",Have you considered using putenv to adjust PYTHONPATH before calling Py_Initialize?,0.3869120172231254,False,2,219 2009-07-17 22:18:26.670,"How to override Py_GetPrefix(), Py_GetPath()?","I'm trying to embed the Python interpreter and need to customize the way the Python standard library is loaded. Our library will be loaded from the same directory as the executable, not from prefix/lib/. We have been successful in making this work by manually modifying sys.path after calling Py_Initialize(), however, this generates a warning because Py_Initialize is looking for site.py in ./lib/, and it's not present until after Py_Initialize has been called and we have updated sys.path. The Python c-api docs hint that it's possible to override Py_GetPrefix() and Py_GetPath(), but give no indication of how. Does anyone know how I would go about overriding them?","You could set Py_NoSiteFlag = 1, call PyInitialize and import site.py yourself as needed.",1.2,True,2,219 2009-07-20 05:00:42.560,tkMessageBox,Can anybody help me out in how to activate 'close' button of askquestion() of tkMessageBox??,"By 'activate', do you mean make it so the user can close the message box by clicking the close ('X') button? I do not think it is possible using tkMessageBox. I guess your best bet is to implement a dialog box with this functionality yourself. BTW: What should askquestion() return when the user closes the dialog box?",1.2,True,1,220 2009-07-20 19:38:26.637,"Django, how to make a view atomic?","I have a simple django app to simulate a stock market, users come in and buy/sell. When they choose to trade, the market price is read, and based on the buy/sell order the market price is increased/decreased. I'm not sure how this works in django, but is there a way to make the view atomic? i.e. I'm concerned that user A's actions may read the price but before it's updated because of his order, user B's action reads the price. Couldn't find a simple, clean solution for this online. Thanks.",Wrap the DB queries that read and the ones that update in a transaction. The syntax depends on what ORM you are using.,-0.1352210990936997,False,1,221 2009-07-21 20:28:25.470,how do I read everything currently in a subprocess.stdout pipe and then return?,"I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline. How can I do a read of all the characters in the stdout pipe of a subprocess instance? If it matters, I'm running in Linux.",You should loop using read() against a set number of characters.,0.3869120172231254,False,1,222 2009-07-22 19:26:48.607,"In Python, how do I indicate I'm overriding a method?","In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?","Python ain't Java. There's of course no such thing really as compile-time checking. I think a comment in the docstring is plenty. This allows any user of your method to type help(obj.method) and see that the method is an override. You can also explicitly extend an interface with class Foo(Interface), which will allow users to type help(Interface.method) to get an idea about the functionality your method is intended to provide.",0.1352210990936997,False,1,223 2009-07-22 22:05:47.193,"Recommended ways to split some functionality into functions, modules and packages?","There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.","I sympathize with you. You are suffering from self-doubt. Don't worry. If you can speak any language, including your mother tongue, you are qualified to do modularization on your own. For evidence, you may read ""The Language Instinct,"" or ""The Math Instinct."" Look around, but not too much. You can learn a lot from them, but you can learn many bad things from them too. Some projects/framework get a lot fo hype. Yet, some of their groupings of functionality, even names given to modules are misleading. They don't ""reveal intention"" of the programmers. They fail the ""high cohesiveness"" test. Books are no better. Please apply 80/20 rule in your book selection. Even a good, very complete, well-researched book like Capers Jones' 2010 ""Software Engineering Best Practices"" is clueless. It says 10-man Agile/XP team would take 12 years to do Windows Vista or 25 years to do an ERP package! It says there is no method till 2009 for segmentation, its term for modularization. I don't think it will help you. My point is: You must pick your model/reference/source of examples very carefully. Don't over-estimate famous names and under-estimate yourself. Here is my help, proven in my experience. It is a lot like deciding what attributes go to which DB table, what properties/methods go to which class/object etc? On a deeper level, it is a lot like arranging furniture at home, or books in a shelf. You have done such things already. Software is the same, no big deal! Worry about ""cohesion"" first. e.g. Books (Leo Tolstoy, James Joyce, DE Lawrence) is choesive .(HTML, CSS, John Keats. jQuery, tinymce) is not. And there are many ways to arrange things. Even taxonomists are still in serious feuds over this. Then worry about ""coupling."" Be ""shy"". ""Don't talk to strangers."" Don't be over-friendly. Try to make your package/DB table/class/object/module/bookshelf as self-contained, as independent as possible. Joel has talked about his admiration for the Excel team that abhor all external dependencies and that even built their own compiler.",0.0679224682270276,False,4,224 2009-07-22 22:05:47.193,"Recommended ways to split some functionality into functions, modules and packages?","There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.","Actually it varies for each project you create but here is an example: core package contains modules that are your project cant live without. this may contain the main functionality of your application. ui package contains modules that deals with the user interface. that is if you split the UI from your console. This is just an example. and it would really you that would be deciding which and what to go where.",0.0,False,4,224 2009-07-22 22:05:47.193,"Recommended ways to split some functionality into functions, modules and packages?","There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.","Take out a pen and piece of paper. Try to draw how your software interacts on a high level. Draw the different layers of the software etc. Group items by functionality and purpose, maybe even by what sort of technology they use. If your software has multiple abstraction layers, I would say to group them by that. On a high level, the elements of a specific layer all share the same general purpose. Now that you have your software in layers, you can divide these layers into different projects based on specific functionality or specialization. As for a certain stage that you reach in which you should do this? I'd say when you have multiple people working on the code base or if you want to keep your project as modular as possible. Hopefully your code is modular enough to do this with. If you are unable to break apart your software on a high level, then your software is probably spaghetti code and you should look at refactoring it. Hopefully that will give you something to work with.",0.2655860252697744,False,4,224 2009-07-22 22:05:47.193,"Recommended ways to split some functionality into functions, modules and packages?","There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.","IMHO this should probably one of the things you do earlier in the development process. I have never worked on a large-scale project, but it would make sense that you make a roadmap of what's going to be done and where. (Not trying to rib you for asking about it like you made a mistake :D ) Modules are generally grouped somehow, by purpose or functionality. You could try each implementation of an interface, or other connections.",0.0679224682270276,False,4,224 2009-07-25 17:36:18.193,How can I launch a background process in Pylons?,"I am trying to write an application that will allow a user to launch a fairly long-running process (5-30 seconds). It should then allow the user to check the output of the process as it is generated. The output will only be needed for the user's current session so nothing needs to be stored long-term. I have two questions regarding how to accomplish this while taking advantage of the Pylons framework: What is the best way to launch a background process such as this with a Pylons controller? What is the best way to get the output of the background process back to the user? (Should I store the output in a database, in session data, etc.?) Edit: The problem is if I launch a command using subprocess in a controller, the controller waits for the subprocess to finish before continuing, showing the user a blank page that is just loading until the process is complete. I want to be able to redirect the user to a status page immediately after starting the subprocess, allowing it to complete on its own.","I think this has little to do with pylons. I would do it (in whatever framework) in these steps: generate some ID for the new job, and add a record in the database. create a new process, e.g. through the subprocess module, and pass the ID on the command line (*). have the process write its output to /tmp/project/ID in pylons, implement URLs of the form /job/ID or /job?id=ID. That will look into the database whether the job is completed or not, and merge the temporary output into the page. (*) It might be better for the subprocess to create another process immediately, and have the pylons process wait for the first child, so that there will be no zombie processes.",0.2012947653214861,False,1,225 2009-07-26 23:01:51.647,How to associate py extension with python launcher on Mac OS X?,"Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?","The python.org OS X Python installers include an application called ""Python Launcher.app"" which does exactly what you want. It gets installed into /Applications /Python n.n/ for n.n > 2.6 or /Applications/MacPython n.n/ for 2.5 and earlier. In its preference panel, you can specify which Python executable to launch; it can be any command-line path, including the Apple-installed one at /usr/bin/python2.5. You will also need to ensure that .py is associated with ""Python Launcher""; you can use the Finder's Get Info command to do that as described elsewhere. Be aware, though, that this could be a security risk if downloaded .py scripts are automatically launched by your browser(s). (Note, the Apple-supplied Python in 10.5 does not include ""Python Launcher.app"").",0.5457054096481145,False,3,226 2009-07-26 23:01:51.647,How to associate py extension with python launcher on Mac OS X?,"Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?","The file associations are done with the ""Get Info"". You select your .PY file, select the File menu; Get Info menu item. Mid-way down the Get Info page is ""Open With"". You can pick the Python Launcher. There's a Change All.. button that changes the association for all .py files.",0.296905446847765,False,3,226 2009-07-26 23:01:51.647,How to associate py extension with python launcher on Mac OS X?,"Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?","The default python installation (atleast on 10.6.8) includes the Python Launcher.app in /System/Library/Frameworks/Python.framework/Resources/, which is aliased to the latest/current version of Python installed on the system. This application launches terminal and sets the right environment to run the script.",0.0,False,3,226 2009-07-27 12:44:15.817,How to exit from Python without traceback?,"I would like to know how to I exit from Python without having an traceback dump on the output. I still want want to be able to return an error code but I do not want to display the traceback log. I want to be able to exit using exit(number) without trace but in case of an Exception (not an exit) I want the trace.","Use the built-in python function quit() and that's it. No need to import any library. I'm using python 3.4",0.1218406379589197,False,2,227 2009-07-27 12:44:15.817,How to exit from Python without traceback?,"I would like to know how to I exit from Python without having an traceback dump on the output. I still want want to be able to return an error code but I do not want to display the traceback log. I want to be able to exit using exit(number) without trace but in case of an Exception (not an exit) I want the trace.",something like import sys; sys.exit(0) ?,0.3516689306882844,False,2,227 2009-07-27 15:11:19.977,Python POST ordered params,"I have a web service that accepts passed in params using http POST but in a specific order, eg (name,password,data). I have tried to use httplib but all the Python http POST libraries seem to take a dictionary, which is an unordered data structure. Any thoughts on how to http POST params in order for Python? Thanks!","Why would you need a specific order in the POST parameters in the first place? As far as I know there are no requirements that POST parameter order is preserved by web servers. Every language I have used, has used a dictionary type object to hold these parameters as they are inherently key/value pairs.",1.2,True,1,228 2009-07-28 18:56:50.007,How to start a background process in Python?,"I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with ""&"". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.",I haven't tried this yet but using .pyw files instead of .py files should help. pyw files dosen't have a console so in theory it should not appear and work like a background process.,0.0,False,1,229 2009-07-29 04:00:35.017,Convert html entities to ascii in Python,"I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML. Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads correctly with things like accented characters. I think a basic example is the html entity ""& aacute;"" or á being encoded into ASCII. Furthermore, I'm not even 100% sure that ASCII is what I need for a plaintext email. As you can tell, I'm completely lost on this encoding stuff.","ASCII is the American Standard Code for Information Interchange and does not include any accented letters. Your best bet is to get Unicode (as you say you can) and encode it as UTF-8 (maybe ISO-8859-1 or some weird codepage if you're dealing with seriously badly coded user-agents/clients, sigh) -- the content type header of that part together with text/plain can express what encoding you've chosen to use (I do recommend trying UTF-8 unless you have positively demonstrated it cannot work -- it's almost universally supported these days and MUCH more flexible than any ISO-8859 or ""codepage"" hack!).",1.2,True,1,230 2009-07-30 03:52:42.753,Getting total/free RAM from within Python,"From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way? Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process.","You can't do this with just the standard Python library, although there might be some third party package that does it. Barring that, you can use the os package to determine which operating system you're on and use that information to acquire the info you want for that system (and encapsulate that into a single cross-platform function).",0.2401167094949473,False,1,231 2009-07-30 09:22:31.380,Neural net input/output,"Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out if someone could provide examples in python that would be a big help","More complex data usually means adding more neurons in the input and output layers. You can feed each ""field"" of your register, properly encoded as a real value (normalized, etc.) to each input neuron, or maybe you can even decompose even further into bit fields, assigning saturated inputs of 1 or 0 to the neurons... for the output, it depends on how you train the neural network, it will try to mimic the training set outputs.",0.0,False,4,232 2009-07-30 09:22:31.380,Neural net input/output,"Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out if someone could provide examples in python that would be a big help","You have to add the number of units for input and output you need for the problem. If the unknown function to approximate depends on n parameter, you will have n input units. The number of output units depends on the nature of the funcion. For real functions with n real parameters you will have one output unit. Some problems, for example in forecasting of time series, you will have m output units for the m succesive values of the function. The encoding is important and depends on the choosen algorithm. For example, in backpropagation for feedforward nets, is better to transform, if possible, the greater number of features in discrete inputs, as for classification tasks. Other aspect of the encoding is that you have to evaluate the number of input and hidden units in function of the amount of data. Too many units related to data may give poor approximation due the course ff dimensionality problem. In some cases, you may to aggregate some of the input data in some way to avoid that problem or use some reduction mechanism as PCA.",0.0,False,4,232 2009-07-30 09:22:31.380,Neural net input/output,"Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out if someone could provide examples in python that would be a big help","You have to encode your input and your output to something that can be represented by the neural network units. ( for example 1 for ""x has a certain property p"" -1 for ""x doesn't have the property p"" if your units' range is in [-1, 1]) The way you encode your input and the way you decode your output depends on what you want to train the neural network for. Moreover, there are many ""neural networks"" algoritms and learning rules for different tasks( Back propagation, boltzman machines, self organizing maps).",1.2,True,4,232 2009-07-30 09:22:31.380,Neural net input/output,"Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out if someone could provide examples in python that would be a big help","Your features must be decomposed into parts that can be represented as real numbers. The magic of a Neural Net is it's a black box, the correct associations will be made (with internal weights) during the training Inputs Choose as few features as are needed to accurately describe the situation, then decompose each into a set of real valued numbers. Weather: [temp today, humidity today, temp yesterday, humidity yesterday...] the association between today's temp and today's humidity is made internally Team stats: [ave height, ave weight, max height, top score,...] Dice: not sure I understand this one, do you mean how to encode discrete values?* Complex number: [a,ai,b,bi,...] * Discrete valued features are tricky, but can still still be encoded as (0.0,1.0). The problem is they don't provide a gradient to learn the threshold on. Outputs You decide what you want the output to mean, and then encode your training examples in that format. The fewer output values, the easier to train. Weather: [tomorrow's chance of rain, tomorrow's temp,...] ** Team stats: [chance of winning, chance of winning by more than 20,...] Complex number: [x,xi,...] ** Here your training vectors would be: 1.0 if it rained the next day, 0.0 if it didn't Of course, whether or not the problem can actually be modeled by a neural net is a different question.",0.2012947653214861,False,4,232 2009-07-31 04:38:14.510,"Django ..""join"" query?","guys, how or where is the ""join"" query in Django? i think that Django dont have ""join""..but how ill make join? Thanks","If you're using models, the select_related method will return the object for any foreign keys you have set up (up to a limit you specify) within that model.",1.2,True,2,233 2009-07-31 04:38:14.510,"Django ..""join"" query?","guys, how or where is the ""join"" query in Django? i think that Django dont have ""join""..but how ill make join? Thanks","SQL Join queries are a hack because SQL doesn't have objects or navigation among objects. Objects don't need ""joins"". Just access the related objects.",-0.9974579674738372,False,2,233 2009-07-31 08:47:34.600,downloading files to users machine?,"I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to. any ideas?","Don't do this. Most files are cached anyway. But if you really want to add this (because users asked for it), make it optional (default off).",0.2655860252697744,False,2,234 2009-07-31 08:47:34.600,downloading files to users machine?,"I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to. any ideas?","You can't forcefully download files to a user without his consent. If that was possible you can only imagine what severe security flaw that would be. You can do one of two things: count on the browser to cache the media file serve the media via some 3rd party plugin (Flash, for example)",1.2,True,2,234 2009-07-31 15:49:14.583,how can I get the uuid module for python 2.4.3,I have an older version of python on the server i'm using and cannot upgrade it. is there a way to get the uuid module?,"To continue where Alex left off.. Download the uuid-1.30.tar.gz from Alex's pypi link. unzip and untar. place the uuid.py to your application's python path (e.g., same dir with your own .py files)",0.2012947653214861,False,1,235 2009-08-02 01:22:31.573,PyOpenGL + Pygame capped to 60 FPS in Fullscreen,"I'm currently working on a game engine written in pygame and I wanted to add OpenGL support. I wrote a test to see how to make pygame and OpenGL work together, and when it's running in windowed mode, it runs between 150 and 200 fps. When I run it full screen (all I did was add the FULLSCREEN flag when I set up the window), it drops down to 60 fps. I added a lot more drawing functions to see if it was just a huge performance drop, but it always ran at 60 fps. Is there something extra I need to do to tell OpenGL that it's running fullscreen or is this a limitation of OpenGL? (I am running in Windows XP)","If you are not changing your clock.tick() when you change between full screen and windowed mode this is almost certainly a vsync issue. If you are on an LCD then it's 100% certain. Unfortunately v-sync can be handled in many places including SDL, Pyopengl, your display server and your video drivers. If you are using windows you can adjust the vsync toggle in the nvidia control panel to test, and there's more than likely something in nvidia-settings for linux as well. I'd guess other manufacturers drivers have similar settings but that's a guess.",0.0,False,1,236 2009-08-04 04:03:09.093,How to control Webpage dialog with python,"When I try to automatically download a file from some webpage using Python, I get Webpage Dialog window (I use IE). The window has two buttons, such as 'Continue' and 'Cancel'. I cannot figure out how to click on the Continue Button. The problem is that I don't know how to control Webpage Dialog with Python. I tried to use winGuiAuto to find the controls of the window, but it fails to recognize any Button type controls... An ideas? Sasha A clarification of my question: My purpose is to download stock data from a certain web site. I need to perform it for many stocks so I need python to do it for me in a repetitive way. This specific site exports the data by letting me download it in Excel file by clicking a link. However after clicking the link I get a Web Page dialog box asking me if I am sure that I want to download this file. This Web page dialog is my problem - it is not an html page and it is not a regular windows dialog box. It is something else and I cannot configure how to control it with python. It has two buttons and I need to click on one of them (i.e. Continue). It seems like it is a special kind of window implemented in IE. It is distinguished by its title which looks like this: Webpage Dialog -- Download blalblabla. If I click Continue mannually it opens a regular windows dialog box (open,save,cancel) which i know how to handle with winGuiAuto library. Tried to use this library for the Webpage Dialog window with no luck. Tried to recognize the buttons with Autoit Info tool -no luck either. In fact, maybe these are not buttons, but actually links, however I cannot see the links and there is no source code visible... What I need is someone to tell me what this Web page Dialog box is and how to control it with Python. That was my question.","You can't, and you don't want to. When you ask a question, try explaining what you are trying to achieve, and not just the task immediately before you. You are likely barking down the wrong path. There is some other way of doing what you are trying to do.",0.0,False,1,237 2009-08-04 18:10:52.940,"With Python, can I keep a persistent dictionary and modify it?","So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file? It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.","pickling has one disadvantage. it can be expensive if your dictionary has to be read and written frequently from disk and it's large. pickle dumps the stuff down (whole). unpickle gets the stuff up (as a whole). if you have to handle small dicts, pickle is ok. If you are going to work with something more complex, go for berkelydb. It is basically made to store key:value pairs.",0.0,False,3,238 2009-08-04 18:10:52.940,"With Python, can I keep a persistent dictionary and modify it?","So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file? It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.","Unpickle from file when program loads, modify as a normal dictionary in memory while program is running, pickle to file when program exits? Not sure exactly what more you're asking for here.",0.296905446847765,False,3,238 2009-08-04 18:10:52.940,"With Python, can I keep a persistent dictionary and modify it?","So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file? It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.","Assuming the keys and values have working implementations of repr, one solution is that you save the string representation of the dictionary (repr(dict)) to file. YOu can load it using the eval function (eval(inputstring)). There are two main disadvantages of this technique: 1) Is will not work with types that have an unuseable implementation of repr (or may even seem to work, but fail). You'll need to pay at least some attention to what is going on. 2) Your file-load mechanism is basically straight-out executing Python code. Not great for security unless you fully control the input. It has 1 advantage: Absurdly easy to do.",0.0509761841073563,False,3,238 2009-08-05 19:59:22.827,"In GTK, how do I make a window unable to be closed?","For example, graying out the ""X"" on windows systems.",Just call the set_deletable with False on the window in question. It will work as long as GTK can convince the window manager to make the window unclosable.,0.6730655149877884,False,1,239 2009-08-05 22:16:28.883,Compiling python modules with DEBUG defined on MSVC,"Python rather stupidly has a pragma directive in its include files that forces a link against python26_d.lib when the DEBUG preprocessor variable is defined. This is a problem because the python installer doesn't come with python26_d.lib! So I can't build applications in MSVC in debug mode. If I temporarily #undef DEBUG for just one file I get many complaints about inconsistent DLL linkage. If I change the pragma in pythons include file I get undefined references to various debug functions. I have tried compiling my own version of python but its somehow different enough from the python that gets distributed that I can't use my modules with apps built with the vanilla version of python Can anyone give me any advice on how to get round this?","This works also when linking with static libraries. I made a copy of python26.lib, and renamed it python26_d.lib. I commented out the line #define PY_DEBUG in pyconfig.h. Also changed the pragma to ""pragma comment(lib,""python26.lib"")"" on line 332. Voila! It worked.",0.1618299653758019,False,1,240 2009-08-09 01:02:37.763,What is the importance of an IDE when programming in Python?,"I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to program outside of such a tool. However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language. How important is an IDE to normal Python development? Are there good IDEs available for the language? If you do use an IDE for Python, how do you use it effectively?","A matter of habit and personal preferences. Me, I use vim (I have to admit emacs is at least as powerful, but my fingers are deeply trained by over 30 years of vi, and any other editor gives me the jitters, especially when it tries to imitate vi and never really manages to get it 100% right;-), occasionally an interactive environment (python itself, sometimes ipython), and on even rarer occasions a debugger (pdb). A good editor gives me all I need in term of word completion, lookup, &c. I've tried Eclipse, its plugins, eric, and Kommodo, but I just don't like them -- Wing, I think I could get used to, and I have to admit its debugger is absolutely out of this world... but, I very rarely use (or need!) advanced debugging functionality, so after every rare occasion I'd forget, and have to learn it all over again a few months later when the need arose again... nah!-)",0.2655860252697744,False,4,241 2009-08-09 01:02:37.763,What is the importance of an IDE when programming in Python?,"I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to program outside of such a tool. However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language. How important is an IDE to normal Python development? Are there good IDEs available for the language? If you do use an IDE for Python, how do you use it effectively?","How important is an IDE to normal Python development? Not very, IMHO. It's a lightweight language with much less boilerplate and simpler idioms than in some other languages, so there's less need for an IDE for that part. The standard interactive interpreter provides help and introspection functionality and a reasonable debugger (pdb). When I want a graphical look at my class hierarchies, I use epydoc to generate it. The only IDE-like functionality I sometimes wish I had is something that would help automate refactoring. Are there good IDEs available for the language? So I hear. Some of my coworkers use Wing. If you do use an IDE for Python, how do you use it effectively? N/A. I tried using Wing a few times but found that it interfered with my normal development process rather than supporting it.",0.2012947653214861,False,4,241 2009-08-09 01:02:37.763,What is the importance of an IDE when programming in Python?,"I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to program outside of such a tool. However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language. How important is an IDE to normal Python development? Are there good IDEs available for the language? If you do use an IDE for Python, how do you use it effectively?","(1) IDEs are less important than for other languages, but if you find one that is useful, it still makes things easier. Without IDEs -- what are doing? Always running Python from command line? (2-3) On my Mac there's included IDLE which I keep always open for its Python shell (it's colored unlike the one in Terminal) and I use free Komodo Edit which I consider to be well-suited for Python as it doesn't go into the language deeply but rather focuses on coloring, tab management, parsing Python output, running frequent commands etc.",0.0,False,4,241 2009-08-09 01:02:37.763,What is the importance of an IDE when programming in Python?,"I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to program outside of such a tool. However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language. How important is an IDE to normal Python development? Are there good IDEs available for the language? If you do use an IDE for Python, how do you use it effectively?","In contrast to the other answers i think that IDE's are very important especially for script languages. Almost all code is bad documentated and an IDE with a good debugger gives you much insides about what is really going on what datatypes are assigned to this values. Is this a hash of lists of hashes or a list of hashs of hashs. And the easy documentation lookup will save you time. But this is only important for people who need to count there time, this normally excludes beginners or hobbyists.",0.0679224682270276,False,4,241 2009-08-09 05:31:05.883,Network Support for Pygame,"I am making a simple multiplayer economic game in pygame. It consists of turns of a certain length, at the end of which, data is sent to the central server. A few quick calculations are done on the data and the results are sent back to the players. My question is how I should implement the network support. I was looking at Twisted and at Pyro and any suggestions or advice would be appreciated.","I've nothing against Twisted and PyRo, but the sort of simple messages you're going to be sending don't require anything like that and might be overcomplicated by using some sort of framework. Pickling an object and sending it over a socket is actually a very easy operation and well worth trying, even if you do eventually go with a more heavyweight framework. Don't fear the network!",0.1352210990936997,False,1,242 2009-08-10 13:13:10.300,Call PHP code from Python,"I'm trying to integrate an old PHP ad management system into a (Django) Python-based web application. The PHP and the Python code are both installed on the same hosts, PHP is executed by mod_php5 and Python through mod_wsgi, usually. Now I wonder what's the best way to call this PHP ad management code from within my Python code in a most efficient manner (the ad management code has to be called multiple times for each page)? The solutions I came up with so far, are the following: Write SOAP interface in PHP for the ad management code and write a SOAP client in Python which then calls the appropriate functions. The problem I see is, that will slow down the execution of the Python code considerably, since for each page served, multiple SOAP client requests are necessary in the background. Call the PHP code through os.execvp() or subprocess.Popen() using PHP command line interface. The problem here is that the PHP code makes use of the Apache environment ($_SERVER vars and other superglobals). I'm not sure if this can be simulated correctly. Rewrite the ad management code in Python. This will probably be the last resort. This ad management code just runs and runs, and there is no one remaining who wrote a piece of code for this :) I'd be quite afraid to do this ;) Any other ideas or hints how this can be done? Thanks.","I've done this in the past by serving the PHP portions directly via Apache. You could either put them in with your media files, (/site_media/php/) or if you prefer to use something more lightweight for your media server (like lighttpd), you can set up another portion of the site that goes through apache with PHP enabled. From there, you can either take the ajax route in your templates, or you can load the PHP from your views using urllib(2) or httplib(2). Better yet, wrap the urllib2 call in a templatetag, and call that in your templates.",0.0,False,1,243 2009-08-13 17:03:13.610,Python Twisted: restricting access by IP address,"What would be the best method to restrict access to my XMLRPC server by IP address? I see the class CGIScript in web/twcgi.py has a render method that is accessing the request... but I am not sure how to gain access to this request in my server. I saw an example where someone patched twcgi.py to set environment variables and then in the server access the environment variables... but I figure there has to be a better solution. Thanks.","I'd use a firewall on windows, or iptables on linux.",0.0,False,1,244 2009-08-18 12:28:03.767,Proxies in Python FTP application,"I'm developing an FTP client in Python ftplib. How do I add proxies support to it (most FTP apps I have seen seem to have it)? I'm especially thinking about SOCKS proxies, but also other types... FTP, HTTP (is it even possible to use HTTP proxies with FTP program?) Any ideas how to do it?",Standard module ftplib doesn't support proxies. It seems the only solution is to write your own customized version of the ftplib.,0.1352210990936997,False,1,245 2009-08-19 06:07:17.173,Is there an easy way to use a python tempfile in a shelve (and make sure it cleans itself up)?,"Basically, I want an infinite size (more accurately, hard-drive rather than memory bound) dict in a python program I'm writing. It seems like the tempfile and shelve modules are naturally suited for this, however, I can't see how to use them together in a safe manner. I want the tempfile to be deleted when the shelve is GCed (or at guarantee deletion after the shelve is out of use, regardless of when), but the only solution I can come up with for this involves using tempfile.TemporaryFile() to open a file handle, getting the filename from the handle, using this filename for opening a shelve, keeping the reference to the file handle to prevent it from getting GCed (and the file deleted), and then putting a wrapper on the shelve that stores this reference. Anyone have a better solution than this convoluted mess? Restrictions: Can only use the standard python library and must be fully cross platform.","I would rather inherit from shelve.Shelf, and override the close method (*) to unlink the files. Notice that, depending on the specific dbm module being used, you may have more than one file that contains the shelf. One solution could be to create a temporary directory, rather than a temporary file, and remove anything in the directory when done. The other solution would be to bind to a specific dbm module (say, bsddb, or dumbdbm), and remove specifically those files that these libraries create. (*) notice that the close method of a shelf is also called when the shelf is garbage collected. The only case how you could end up with garbage files is when the interpreter crashes or gets killed.",1.2,True,1,246 2009-08-20 07:59:36.877,how to install new packages with python 3.1.1?,"I've tried to install pip on windows, but it's not working: giving me ImportError: No module named pkg_resources easy_install doesn't have version 3.1 or so, just 2.5, and should be replaced by pim. is there easy way to install it on windows?","setuptools doesn't quite work on Python 3.1 yet. Try installing packages with regular distutils, or use binary packages (.exe, .msi) provided by the package author.",1.2,True,1,247 2009-08-20 10:13:54.017,Django - Edit data in db,"I have a question regarding editing/saving data in database using Django. I have template that show data from database. And after each record i have link that link you to edit page. But now is the question how to edit data in db without using admin panel? I run thought tutorial in djangobook but i didn't see how to achieve this without using the shell Thanks in advice!",You can use Django authenticaion system to create users and giving them permissions to modify the data.,0.0,False,1,248 2009-08-20 16:21:38.407,How do I programmatically pull lists/arrays of (itunes urls to) apps in the iphone app store?,"I'd like to know how to pragmatically pull lists of apps from the iphone app store. I'd code this in python (via the google app engine) or in an iphone app. My goal would be to select maybe 5 of them and present them to the user. (for instance a top 5 kind of thing, or advanced filtering or queries)","Unfortunately the only API that seems to be around for Apple's app store is a commercial offering from ABTO; nobody seems to have developed a free one. I'm afraid you'll have to resort to ""screen scraping"" -- urlget things, use beautifulsoup or the like for interpreting the HTML you get, and be ready to fix breakages whenever Apple tweaks their formats &c. It seems Apple has no interest in making such a thing available to developers (although as far as I can't tell they're not actively fighting against it either, they appear to just not care).",1.2,True,1,249 2009-08-23 23:42:52.663,How to submit data of a flash form? [python],"I would like to know if it is possible to submit a flash form from python and, if it is, how? I have done form submitting from python before, but the forms were HTML not flash. I really have no idea on how to do this. In my research about this I kept getting 'Ming'. However, Ming is only to create .swf files and that's not what I intend to do. Any help on this is greatly appreciated.","You can set the url attribute (I think it's url, please correct me if I'm wrong) on a Flash form control to a Python script - then it will pass it through HTTP POST like any normal HTML form. You've got nothing to be afraid of, it uses the same protocol to communicate, it's just a different submission process.",1.2,True,2,250 2009-08-23 23:42:52.663,How to submit data of a flash form? [python],"I would like to know if it is possible to submit a flash form from python and, if it is, how? I have done form submitting from python before, but the forms were HTML not flash. I really have no idea on how to do this. In my research about this I kept getting 'Ming'. However, Ming is only to create .swf files and that's not what I intend to do. Any help on this is greatly appreciated.","For your flash app, there's no difference if the backend is python, php or anything, so you can follow a normal ""php + flash contact form"" guide and then build the backend using django or any other python web framework, receive the information from the http request (GET or POST, probably the last one) and do whatever you wanted to do with them. Notice the response from python to flash works the same as with php, it's just http content, so you can use XML or even better, JSON.",0.0,False,2,250 2009-08-25 00:30:51.707,Importing a text file into SQL Server in Python,"I am writing a python script that will be doing some processing on text files. As part of that process, i need to import each line of the tab-separated file into a local MS SQL Server (2008) table. I am using pyodbc and I know how to do this. However, I have a question about the best way to execute it. I will be looping through the file, creating a cursor.execute(myInsertSQL) for each line of the file. Does anyone see any problems waiting to commit the statements until all records have been looped (i.e. doing the commit() after the loop and not inside the loop after each individual execute)? The reason I ask is that some files will have upwards of 5000 lines. I didn't know if trying to ""save them up"" and committing all 5000 at once would cause problems. I am fairly new to python, so I don't know all of these issues yet. Thanks.","If I understand what you are doing, Python is not going to be a problem. Executing a statement inside a transaction does not create cumulative state in Python. It will do so only at the database server itself. When you commit you will need to make sure the commit occurred, since having a large batch commit may conflict with intervening changes in the database. If the commit fails, you will have to re-run the batch again. That's the only problem that I am aware of with large batches and Python/ODBC (and it's not even really a Python problem, since you would have that problem regardless.) Now, if you were creating all the SQL in memory, and then looping through the memory-representation, that might make more sense. Still, 5000 lines of text on a modern machine is really not that big of a deal. If you start needing to process two orders of magnitude more, you might need to rethink your process.",1.2,True,1,251 2009-08-30 16:17:03.933,How to implement a multiprocessing priority queue in Python?,Anybody familiar with how I can implement a multiprocessing priority queue in python?,"Depending on your requirements you could use the operating system and the file system in a number of ways. How large will the queue grow and how fast does it have to be? If the queue may be big but you are willing to open a couple files for every queue access you could use a BTree implementation to store the queue and file locking to enforce exclusive access. Slowish but robust. If the queue will remain relatively small and you need it to be fast you might be able to use shared memory on some operating systems... If the queue will be small (1000s of entries) and you don't need it to be really fast you could use something as simple as a directory with files containing the data with file locking. This would be my preference if small and slow is okay. If the queue can be large and you want it to be fast on average, then you probably should use a dedicated server process like Alex suggests. This is a pain in the neck however. What are your performance and size requirements?",0.0,False,2,252 2009-08-30 16:17:03.933,How to implement a multiprocessing priority queue in Python?,Anybody familiar with how I can implement a multiprocessing priority queue in python?,"I had the same use case. But with a finite number of priorities. What I am ending up doing is creating one Queue per priority, and my Process workers will try to get the items from those queues, starting with the most important queue to the less important one (moving from one queue to the other is done when the queue is empty)",0.0679224682270276,False,2,252 2009-09-02 00:03:32.233,How to deal with user authentication and wrongful modification in scripting languages?,"I'm building a centralized desktop application using Python/wxPython. One of the requirements is User authentication, which I'm trying to implement using LDAP (although this is not mandatory). Users of the system will be mechanical and electrical engineers making budgets, and the biggest problem would be industrial espionage. Its a common problem that leaks occur commonly from the bottom on informal ways, and this could pose problems. The system is set up in such a way that every user has access to all and only the information it needs, so that no one person but the people on top has monetary information on the whole project. The problem is that, for every way I can think to implement the authentication system, Python's openness makes me think of at least one way of bypassing/getting sensible information from the system, because ""compiling"" with py2exe is the closest I can get to obfuscation of the code on Windows. I'm not really trying to hide the code, but rather make the authentication routine secure by itself, make it in such a way that access to the code doesn't mean capability to access the application. One thing I wanted to add, was some sort of code signing to the access routine, so the user can be sure that he is not running a modified client app. One of the ways I've thought to avoid this is making a C module for the authentication, but I would rather not have to do that. Of course this question is changing now and is not just ""Could anyone point me in the right direction as to how to build a secure authentication system running on Python? Does something like this already exist?"", but ""How do you harden an scripting (Python) against wrongful modification?""","Possibly: The user enters their credentials into the desktop client. The client says to the server: ""Hi, my name username and my password is password"". The server checks these. The server says to the client: ""Hi, username. Here is your secret token: ..."" Subsequently the client uses the secret token together with the username to ""sign"" communications with the server.",0.2012947653214861,False,2,253 2009-09-02 00:03:32.233,How to deal with user authentication and wrongful modification in scripting languages?,"I'm building a centralized desktop application using Python/wxPython. One of the requirements is User authentication, which I'm trying to implement using LDAP (although this is not mandatory). Users of the system will be mechanical and electrical engineers making budgets, and the biggest problem would be industrial espionage. Its a common problem that leaks occur commonly from the bottom on informal ways, and this could pose problems. The system is set up in such a way that every user has access to all and only the information it needs, so that no one person but the people on top has monetary information on the whole project. The problem is that, for every way I can think to implement the authentication system, Python's openness makes me think of at least one way of bypassing/getting sensible information from the system, because ""compiling"" with py2exe is the closest I can get to obfuscation of the code on Windows. I'm not really trying to hide the code, but rather make the authentication routine secure by itself, make it in such a way that access to the code doesn't mean capability to access the application. One thing I wanted to add, was some sort of code signing to the access routine, so the user can be sure that he is not running a modified client app. One of the ways I've thought to avoid this is making a C module for the authentication, but I would rather not have to do that. Of course this question is changing now and is not just ""Could anyone point me in the right direction as to how to build a secure authentication system running on Python? Does something like this already exist?"", but ""How do you harden an scripting (Python) against wrongful modification?""","How malicious are your users? Really. Exactly how malicious? If your users are evil sociopaths and can't be trusted with a desktop solution, then don't build a desktop solution. Build a web site. If your users are ordinary users, they'll screw the environment up by installing viruses, malware and keyloggers from porn sites before they try to (a) learn Python (b) learn how your security works and (c) make a sincere effort at breaking it. If you actually have desktop security issues (i.e., public safety, military, etc.) then rethink using the desktop. Otherwise, relax, do the right thing, and don't worry about ""scripting"". C++ programs are easier to hack because people are lazy and permit SQL injection.",1.2,True,2,253 2009-09-02 00:07:14.003,"On localhost, how do I pick a free port number?","I'm trying to play with inter-process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally. The server is able to launch slaves in a separate process and listens on some port. The slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21? I'm using Python, if that cuts the choices down.","You can listen on whatever port you want; generally, user applications should listen to ports 1024 and above (through 65535). The main thing if you have a variable number of listeners is to allocate a range to your app - say 20000-21000, and CATCH EXCEPTIONS. That is how you will know if a port is unusable (used by another process, in other words) on your computer. However, in your case, you shouldn't have a problem using a single hard-coded port for your listener, as long as you print an error message if the bind fails. Note also that most of your sockets (for the slaves) do not need to be explicitly bound to specific port numbers - only sockets that wait for incoming connections (like your master here) will need to be made a listener and bound to a port. If a port is not specified for a socket before it is used, the OS will assign a useable port to the socket. When the master wants to respond to a slave that sends it data, the address of the sender is accessible when the listener receives data. I presume you will be using UDP for this?",0.3153999413393242,False,2,254 2009-09-02 00:07:14.003,"On localhost, how do I pick a free port number?","I'm trying to play with inter-process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally. The server is able to launch slaves in a separate process and listens on some port. The slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21? I'm using Python, if that cuts the choices down.",Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname() right after bind().,0.999999986313458,False,2,254 2009-09-03 07:50:17.240,Importing external module in IronPython,"I'm currently working on an application written in C#, which I'm embedding IronPython in. I generally have no problems about it, but there's one thing that I don't know how to deal with. I want to import an external module into the script. How can I do that? Simple import ext_lib doesn't work. Should I add a path to the lib to sys.path? Maybe it is possible to copy the lib's .py file into app directory and import from there? EDIT: I finally chosen another solution - compiled my script with py2exe and I'm just running it from main C# app with Process (without using IronPython). Anyway, thanks for help ;)",If you have installed IronPython from NuGet packages and you want modules from the CPython Standard Library then the best way to do it is by installing the IronPython.StdLib NuGet package which is from the same authors of IronPython.,0.3869120172231254,False,1,255 2009-09-04 01:40:30.637,calculate user inputed time with Python,"I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. === Edit ================== To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.","First of all, you'll need some conventions. Is 3.55 five minutes to four hours, five milliseconds to four seconds, or 3 and 55/100 of a minute/hour/second? The same applies to 3:55. At least have a distinction between dot and colon, specifying that a dot means a fraction and a colon, a separator of hour/minute/second. Although you haven't specified what ""time"" is (since or o'clock?), you'll need that too. Then, it's simple a matter of having a final representation of a time that you want to work with, and keep converting the input until your final representation is achieved. Let's say you decide that ultimately time should be represented as MM:SS (two digits for minutes, a colon, two digits for seconds), you'll need to search the string for allowed occurrences of characters, and act accordingly. For example, having a colon and a dot at the same time is not allowed. If there's a single colon, you have a fraction, therefore you'll treat the second part as a fraction of 60. Keep doing this until you have your final representation, and then just do what you gotta do with said ""time"". I don't know on what constraints you're working with, but the problem could be narrowed if instead of a single ""time"" input, you had two: The first, where people type the hours, and the second, where they type the minutes. Of course, that would only work if you can divide the input...",0.0,False,3,256 2009-09-04 01:40:30.637,calculate user inputed time with Python,"I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. === Edit ================== To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.","There are a few possible solutions, but at some point you're gonna run into ambiguous cases that will result in arbitrary conversions. Overall I'd suggest taking any input and parsing the separators (whether : or . or something else) and then converting to seconds based on some schema of units you've defined. Alternatively you could do a series of try/except statements to test it against different time formatting schemes to see if it matches. I'm not sure what will be best in your case...",0.0,False,3,256 2009-09-04 01:40:30.637,calculate user inputed time with Python,"I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. === Edit ================== To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.","Can you do this with a GUI and restrict the user input? Processing the text seems super error prone otherwise (on the part of the user, not to mention the programmer), and for hours worked... you sort-of want to get that right.",0.0,False,3,256 2009-09-05 12:33:03.783,Can I use __init__.py to define global variables?,"I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the __init__.py file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from these modules? Of course, if this is totally wrong, and there is a better alternative, I'd like to know it.","You can define global variables from anywhere, but it is a really bad idea. import the __builtin__ module and modify or add attributes to this modules, and suddenly you have new builtin constants or functions. In fact, when my application installs gettext, I get the _() function in all my modules, without importing anything. So this is possible, but of course only for Application-type projects, not for reusable packages or modules. And I guess no one would recommend this practice anyway. What's wrong with a namespace? Said application has the version module, so that I have ""global"" variables available like version.VERSION, version.PACKAGE_NAME etc.",0.2012947653214861,False,1,257 2009-09-07 06:56:51.613,C++ with Python embedding: crash if Python not installed,"I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing. I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embedding code definitely works and there are no crashes. I sent the run folder to my friend who doesn't have Python installed, and the app crashes for him during the scripting setup phase. A few hours ago, I tried the app on my laptop that has Python 2.6 installed. I got the same crash behavior as my friend, and through debugging found that it was the Py_Initialize() call that fails. I installed Python 3.1 on my laptop without changing the app code. I ran it and it runs perfectly. I uninstalled Python 3.1 and the app crashes again. I put in code in my app to dynamically link from the local python31.dll, to ensure that it was using it, but I still get the crash. I don't know if the interpreter needs more than the DLL to start up or what. I haven't been able to find any resources on this. The Python documentation and other guides do not seem to ever address how to distribute your C/C++ applications that use Python embedding without having the users install Python locally. I know it's more of an issue on Windows than on Unix, but I've seen a number of Windows C/C++ applications that embed Python locally and I'm not sure how they do it. What else do I need other than the DLL? Why does it work when I install Python and then stop working when I uninstall it? It sounds like it should be so trivial; maybe that's why nobody really talks about it. Nevertheless, I can't really explain how to deal with this crash issue. Thank you very much in advance.","A zip of the Python standard library worked for me with Python27. I zipped the contents of Lib and dll, and made sure there was no additional python27-subfolder or Lib or dll subfolder. i.e. just a zip named python27.zip containing all the files. I copied that zip and the python27.dll alongside the executable.",0.5457054096481145,False,2,258 2009-09-07 06:56:51.613,C++ with Python embedding: crash if Python not installed,"I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing. I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embedding code definitely works and there are no crashes. I sent the run folder to my friend who doesn't have Python installed, and the app crashes for him during the scripting setup phase. A few hours ago, I tried the app on my laptop that has Python 2.6 installed. I got the same crash behavior as my friend, and through debugging found that it was the Py_Initialize() call that fails. I installed Python 3.1 on my laptop without changing the app code. I ran it and it runs perfectly. I uninstalled Python 3.1 and the app crashes again. I put in code in my app to dynamically link from the local python31.dll, to ensure that it was using it, but I still get the crash. I don't know if the interpreter needs more than the DLL to start up or what. I haven't been able to find any resources on this. The Python documentation and other guides do not seem to ever address how to distribute your C/C++ applications that use Python embedding without having the users install Python locally. I know it's more of an issue on Windows than on Unix, but I've seen a number of Windows C/C++ applications that embed Python locally and I'm not sure how they do it. What else do I need other than the DLL? Why does it work when I install Python and then stop working when I uninstall it? It sounds like it should be so trivial; maybe that's why nobody really talks about it. Nevertheless, I can't really explain how to deal with this crash issue. Thank you very much in advance.","In addition to pythonxy.dll, you also need the entire Python library, i.e. the contents of the lib folder, plus the extension modules, i.e. the contents of the DLLs folder. Without the standard library, Python won't even start, since it tries to find os.py (in 3.x; string.py in 2.x). On startup, it imports a number of modules, in particular site.py. There are various locations where it searches for the standard library; in your cases, it eventually finds it in the registry. Before, uses the executable name (as set through Py_SetProgramName) trying to find the landmark; it also checks for a file python31.zip which should be a zipped copy of the standard library. It also checks for a environment variable PYTHONHOME. You are free to strip the library from stuff that you don't need; there are various tools that compute dependencies statically (modulefinder in particular). If you want to minimize the number of files, you can link all extension modules statically into your pythonxy.dll, or even link pythonxy.dll statically into your application use the freeze tool; this will allow linking the byte code of the standard library into your pythonxy.dll. (alternatively to 2.) use pythonxy.zip for the standard library.",1.2,True,2,258 2009-09-07 07:08:12.007,Django: Simple rate limiting,"Many of my views fetch external resources. I want to make sure that under heavy load I don't blow up the remote sites (and/or get banned). I only have 1 crawler so having a central lock will work fine. So the details: I want to allow at most 3 queries to a host per second, and have the rest block for a maximum of 15 seconds. How could I do this (easily)? Some thoughts : Use django cache Seems to only have 1 second resolution Use a file based semaphore Easy to do locks for concurrency. Not sure how to make sure only 3 fetches happen a second. Use some shared memory state I'd rather not install more things, but will if I have to.","What about using a different process to handle scraping, and a queue for the communication between it and Django? This way you would be able to easily change the number of concurrent requests, and it would also automatically keep track of the requests, without blocking the caller. Most of all, I think it would help lowering the complexity of the main application (in Django).",0.2012947653214861,False,1,259 2009-09-07 09:36:41.473,Upgrade python in linux,"I have a linux VPS that uses an older version of python (2.4.3). This version doesn't include the UUID module, but I need it for a project. My options are to upgrade to python2.6 or find a way to make uuid work with the older version. I am a complete linux newbie. I don't know how to upgrade python safely or how I could get the UUID modules working with the already installed version. What is a better option and how would I go about doing it?","The safest way to upgrading Python is to install it to a different location (away from the default system path). To do this, download the source of python and do a ./configure --prefix=/opt (Assuming you want to install it to /opt which is where most install non system dependant stuff to) The reason why I say this is because some other system libraries may depend on the current version of python. Another reason is that as you are doing your own custom development, it is much better to have control over what version of the libraries (or interpreters) you are using rather than have a operating system patch break something that was working before. A controlled upgrade is better than having the application break on you all of a sudden.",0.6730655149877884,False,2,260 2009-09-07 09:36:41.473,Upgrade python in linux,"I have a linux VPS that uses an older version of python (2.4.3). This version doesn't include the UUID module, but I need it for a project. My options are to upgrade to python2.6 or find a way to make uuid work with the older version. I am a complete linux newbie. I don't know how to upgrade python safely or how I could get the UUID modules working with the already installed version. What is a better option and how would I go about doing it?","The best solution will be installing python2.6 in the choosen directory - It will you give you access to many great features and better memory handling (infamous python=2.4 memory leak problem). I have got several pythons installed onto my two computers, I found that the best solution for are two directories: $HOME/usr-32 $HOME/usr-64 respectively to using operating system (I share $HOME between 32 and 64 bit versions of Linux). In each I have one directory for every application/program, for example: ls ~/usr-64/python-2.6.2/ bin include lib share It leads completetely to avoiding conflicts between version and gives great portability (you can use usb pendrives etc). Python 2.6.2 in previously example has been installed with option: ./configure --prefix=$HOME/usr-64/python-2.6.2",0.0,False,2,260 2009-09-10 23:48:56.300,send an arbitrary number of inputs from python to a .exe,"p = subprocess.Popen(args = ""myprog.exe"" + "" "" + str(input1) + "" "" + str(input2) + "" "" + str(input3) + "" "" + strpoints, stdout = subprocess.PIPE) in the code above, input1, input2, and input3 are all integers that get converted to strings. the variable ""strpoints"" is a list of arbitrary length of strings. input1 tells myprog the length of strpoints. of course, when i try to run the above code, i get the following error message: TypeError: Can't convert 'list' object to str implicitly how do i pass all the elements of strpoints to myprog.exe? am i doomed to having to do str(strpoints) and then have myprog.exe parse this for commas, apostrophes, etc.? e.g., `>>> x = ['a', 'b'] `>>> str(x) ""['a', 'b']"" or should i create a huge string in advance? e.g., '>>> x = ['a', 'b'] '>>> stringify(x) ' a b' where stringify would be something like def stringify(strlist): rlist = """" for i in strlist: rlist = rlist + i + "" "" return rlist","Avoid concatenating all arguments into one string using that string. It's a lot simpler and better and safer to just pass a sequence (list or tuple) of arguments. This is specially true if any argument contains a space character (which is quite common for filenames).",0.1016881243684853,False,1,261 2009-09-12 20:10:43.223,"Python - Virtualenv , python 3?","Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have python 3.1.1 with subversion pygame to write my own stuff, and python 2.6 with normal stable pygame to use to run other things, like pygame games downloaded from pygame.org. Any help on how to accomplish that? Thanks. OK I realized virtualenv is not what I'm looking for.",Your use case doesn't actually need virtualenv. You just need to install several different Python versions.,1.2,True,2,262 2009-09-12 20:10:43.223,"Python - Virtualenv , python 3?","Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have python 3.1.1 with subversion pygame to write my own stuff, and python 2.6 with normal stable pygame to use to run other things, like pygame games downloaded from pygame.org. Any help on how to accomplish that? Thanks. OK I realized virtualenv is not what I'm looking for.","Not sure if I understood you correctly, but here goes :) I don't know about OS X, but in Linux you can install both 2.6 and 3. Then you can either specify to use python25 or python3, or change the /usr/bin/python symlink to the version you want to use by default.",0.0,False,2,262 2009-09-14 23:28:28.893,Default save path for Python IDLE?,"Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?","On Windows (Vista at least, which is what I'm looking at here), shortcut icons on the desktop have a ""Start in"" field where you can set the directory used as the current working directory when the program starts. Changing that works for me. Anything like that on the Mac? (Starting in the desired directory from the command line works, too.)",0.0370887312438237,False,8,263 2009-09-14 23:28:28.893,Default save path for Python IDLE?,"Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?","I actually just discovered the easiest answer, if you use the shortcut link labeled ""IDLE (Python GUI)"". This is in Windows Vista, so I don't know if it'll work in other OS's. 1) Right-click ""Properties"". 2) Select ""Shortcut"" tab. 3) In ""Start In"", write file path (e.g. ""C:\Users...""). Let me know if this works!",0.1473426351731879,False,8,263 2009-09-14 23:28:28.893,Default save path for Python IDLE?,"Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?","For OS X: Open a new finder window,then head over to applications. Locate your Python application. (For my mac,it's Python 3.5) Double click on it. Right click on the IDLE icon,show package contents. Then go into the contents folder,then resources. Now,this is the important part: (Note: You must be the administrator or have the administrator's password for the below to work) Right click on the idlemain.py,Get Info. Scroll all the way down. Make sure under the Sharing & Permissions tab,your ""name""(Me) is on it with the privilege as Read & Write. If not click on the lock symbol and unlock it. Then add/edit yourself to have the Read & Write privilege. Lastly,as per Ned Deily's instructions,edit the line: os.chdir(os.path.expanduser('~/Documents')) with your desired path and then save the changes. Upon restarting the Python IDLE,you should find that your default Save as path to be the path you've indicated.",0.0370887312438237,False,8,263 2009-09-14 23:28:28.893,Default save path for Python IDLE?,"Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?","I am using windows 7 and by going to Start-> IDLE(Python 3.6 32-bit) The click on properties and then in the shortcut tab go to Start in and entering the desired path worked for me kindly note if IDLE is open and running while you do this you'll have to shut it down and restart it for this to work",0.0370887312438237,False,8,263 2009-09-14 23:28:28.893,Default save path for Python IDLE?,"Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?","It seems like you can get idle into the directory you want if you run any module from that directory. I had previously tried opening idlemain.py through the path browser. I was able to open and edit the file, but it seemed like I wasn't able to save my modifications. I'm just glad to hear other people are having this problem. I just thought I was being stupid.",0.0740755660660223,False,8,263 2009-09-14 23:28:28.893,Default save path for Python IDLE?,"Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?","If you open a module, that sets the default working directory. Start IDLE. File -> Open to open your file. And set the current working directory.",0.0370887312438237,False,8,263 2009-09-14 23:28:28.893,Default save path for Python IDLE?,"Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?","If you locate the idlelib directory in your Python install, it will have a few files with the .def extension. config-main.def has instructions on where to put the custom config files. However, looking through these I did not find any configurable paths (your install may vary). Looks like you might need to crack open the editor code to alter it.",0.0,False,8,263 2009-09-14 23:28:28.893,Default save path for Python IDLE?,"Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?","In Windows 10+, click the Windows Start button, then type idle, and then right-click on the IDLE desktop app and open the file location. This should bring you to the Start Menu shortcuts for Python, and you'll find a shortcut to IDLE there. Right-click on the IDLE shortcut and select properties. Set the ""Start in"" directory to be where you want default save path to be.",0.0740755660660223,False,8,263 2009-09-15 04:48:36.987,Symmetrically adressable matrix,"I'm looking to create a 2d matrix of integers with symmetric addressing ( i.e. matrix[2,3] and matrix[3,2] will return the same value ) in python. The integers will have addition and subtraction done on them, and be used for logical comparisons. My initial idea was to create the integer objects up front and try to fill a list of lists with some python equivalent of pointers. I'm not sure how to do it, though. What is the best way to implement this, and should I be using lists or another data structure?","You're probably better off using a full square numpy matrix. Yes, it wastes half the memory storing redundant values, but rolling your own symmetric matrix in Python will waste even more memory and CPU by storing and processing the integers as Python objects.",0.2012947653214861,False,2,264 2009-09-15 04:48:36.987,Symmetrically adressable matrix,"I'm looking to create a 2d matrix of integers with symmetric addressing ( i.e. matrix[2,3] and matrix[3,2] will return the same value ) in python. The integers will have addition and subtraction done on them, and be used for logical comparisons. My initial idea was to create the integer objects up front and try to fill a list of lists with some python equivalent of pointers. I'm not sure how to do it, though. What is the best way to implement this, and should I be using lists or another data structure?",You only need to store the lower triangle of the matrix. Typically this is done with one n(n+1)/2 length list. You'll need to overload the __getitem__ method to interpret what the entry means.,0.1016881243684853,False,2,264 2009-09-17 19:44:09.870,Finding the command for a specific PID in Linux from Python,"I'd like to know if it's possible to find out the ""command"" that a PID is set to. When I say command, I mean what you see in the last column when you run the command ""top"" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID. Any help would be great. Thanks.","Look in /proc/$PID/cmdline, and then os.readlink() on /proc/$PID/exe. /proc/$PID/cmdline is not necessarily going to be correct, as a program can change its argument vector or it may not contain a full path. Three examples of this from my current process list are: avahi-daemon: chroot helper qmgr -l -t fifo -u /usr/sbin/postgrey --pidfile=/var/run/postgrey.pid --daemonize --inet=127.0.0.1:60000 --delay=55 That first one is obvious - it's not a valid path or program name. The second is just an executable with no path name. The third looks ok, but that whole command line is actually in argv[0], with spaces separating the arguments. Normally you should have NUL separated arguments. All this goes to show that /proc/$PID/cmdline (or the ps(1) output) is not reliable. However, nor is /proc/$PID/exe. Usually it is a symlink to the executable that is the main text segment of the process. But sometimes it has "" (deleted)"" after it if the executable is no longer in the filesystem. Also, the program that is the text segment is not always what you want. For instance, /proc/$PID/exe from that /usr/sbin/postgrey example above is /usr/bin/perl. This will be the case for all interpretted scripts (#!). I settled on parsing /proc/$PID/cmdline - taking the first element of the vector, and then looking for spaces in that, and taking all before the first space. If that was an executable file - I stopped there. Otherwise I did a readlink(2) on /proc/$PID/exe and removed any "" (deleted)"" strings on the end. That first part will fail if the executable filename actually has spaces in it. There's not much you can do about that. BTW. The argument to use ps(1) instead of /proc/$PID/cmdline does not apply in this case, since you are going to fall back to /proc/$PID/exe. You will be dependent on the /proc filesystem, so you may as well read it with read(2) instead of pipe(2), fork(2), execve(2), readdir(3)..., write(2), read(2). While ps and /proc/$PID/cmdline may be the same from the point of view of lines of python code, there's a whole lot more going on behind the scenes with ps.",0.283556384140347,False,3,265 2009-09-17 19:44:09.870,Finding the command for a specific PID in Linux from Python,"I'd like to know if it's possible to find out the ""command"" that a PID is set to. When I say command, I mean what you see in the last column when you run the command ""top"" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID. Any help would be great. Thanks.",Look in /proc/$PID/cmdline,0.336246259354525,False,3,265 2009-09-17 19:44:09.870,Finding the command for a specific PID in Linux from Python,"I'd like to know if it's possible to find out the ""command"" that a PID is set to. When I say command, I mean what you see in the last column when you run the command ""top"" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID. Any help would be great. Thanks.","The proc filesystem exports this (and other) information. Look at the /proc/PID/cmd symlink.",0.0,False,3,265 2009-09-18 17:52:53.017,Passing Python Data to JavaScript via Django,"I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it? Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML. I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place. I'm not (yet) using a JavaScript library like jQuery.","Putting Java Script embedded into Django template is rather always bad idea. Rather, because there are some exceptions from this rule. Everything depends on the your Java Script code site and functionality. It is better to have seperately static files, like JS, but the problem is that every seperate file needs another connect/GET/request/response mechanism. Sometimes for small one, two liners code os JS to put this into template, bun then use django templatetags mechanism - you can use is in other templates ;) About objects - the same. If your site has AJAX construction/web2.0 like favour - you can achieve very good effect putting some count/math operation onto client side. If objects are small - embedded into template, if large - response them in another connection to avoid hangind page for user.",0.0509761841073563,False,3,266 2009-09-18 17:52:53.017,Passing Python Data to JavaScript via Django,"I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it? Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML. I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place. I'm not (yet) using a JavaScript library like jQuery.","You can include