content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Passing a pre_delete() or post_delete() signal arguments? I am using signals to perform an action after an object has been deleted; however, sometimes I want to perform a different action (not the default one) depending on an arugment. Is there a way to pass an argument to my signal catcher? Or will I have to a...
Passing a pre_delete() or post_delete() signal arguments?
I am using signals to perform an action after an object has been deleted; however, sometimes I want to perform a different action (not the default one) depending on an arugment. Is there a way to pass an argument to my signal catcher? Or will I have to abandon the signal and instead hard code what I want to do in th...
[ "I don't think you need to hardcode your actions in the model - you can still use signals. But you will need to override delete() to at the very least accept the send_email parameter and - since I don't think you can pass extra parameters into post_delete() - trigger your own custom signal.\nSomething like this: (w...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001643332_django_python.txt
Q: Why do I get this error when I try to print something in Putty? UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 38: ordinal not in range(128) I am downloading a website and then printing its contents...simple. Do I have to encode it somehow? A: Try utf-8 for start. Website you dow...
Why do I get this error when I try to print something in Putty?
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 38: ordinal not in range(128) I am downloading a website and then printing its contents...simple. Do I have to encode it somehow?
[ "Try utf-8 for start. Website you download might have different charset than ANSI and those extra characters can not be printed on console.\nSo in place where you do print text do print text.encode('utf-8') instead.\n", "Make sure you have Putty configured to accept UTF-8 encoded data.\n", "printing stuff to st...
[ 2, 0, 0 ]
[]
[]
[ "ascii", "encoding", "python", "unicode" ]
stackoverflow_0001643023_ascii_encoding_python_unicode.txt
Q: Killing Python webservers I am looking for a simple Python webserver that is easy to kill from within code. Right now, I'm playing with Bottle, but I can't find any way at all to kill it in code. If you know how to kill Bottle (in code, no Ctrl+C) that would be super, but I'll take anything that's Python, simple, ...
Killing Python webservers
I am looking for a simple Python webserver that is easy to kill from within code. Right now, I'm playing with Bottle, but I can't find any way at all to kill it in code. If you know how to kill Bottle (in code, no Ctrl+C) that would be super, but I'll take anything that's Python, simple, and killable.
[ "We use this.\nimport os\nos._exit(3)\n\nTo crash in a 'controlled' way.\n", "If you want to kill a process from Python, on a Unix-like platform, you can send signals equivalent to Ctrl-C at the console using Pythons os module e.g. \n# Get this processes PID\npid_of_process = os.getpid()\n# Send the interrupt sig...
[ 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001643362_python.txt
Q: Forward slash in a Python regex I'm trying to use a Python regex to find a mathematical expression in a string. The problem is that the forward slash seems to do something unexpected. I'd have thought that [\w\d\s+-/*]* would work for finding math expressions, but it finds commas too for some reason. A bit of expe...
Forward slash in a Python regex
I'm trying to use a Python regex to find a mathematical expression in a string. The problem is that the forward slash seems to do something unexpected. I'd have thought that [\w\d\s+-/*]* would work for finding math expressions, but it finds commas too for some reason. A bit of experimenting reveals that forward slashe...
[ "Look here for documentation on Python's re module.\nI think it is not the /, but rather the - in your first character class: [+-/] matches +, / and any ASCII value between, which happen to include the comma.\nMaybe this hint from the docs help:\n\nIf you want to include a ']' or a '-' inside a set, precede it with...
[ 31, 9, 4, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001643772_python_regex.txt
Q: creating a .mat file from python I have a variable exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]. I would like to create a mat file like the following >> exon : [3*2 double] [2*2 double] When I used the python code to do the same it is showing error message. here is my python code import scipy.io exon ...
creating a .mat file from python
I have a variable exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]. I would like to create a mat file like the following >> exon : [3*2 double] [2*2 double] When I used the python code to do the same it is showing error message. here is my python code import scipy.io exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], ...
[ "You seem to want two different arrays linked to same variable name in Matlab. That is not possible. In MATLAB you can have cell arrays, or structs, which contain other arrays, but you cannot have just a tuple of arrays assigned to a single variable (which is what you have in mdict={'exon': (exon[0], exon1)) - ther...
[ 10, 1 ]
[]
[]
[ "mat_file", "python", "scipy" ]
stackoverflow_0001526002_mat_file_python_scipy.txt
Q: Simple AtomPub server library What simple AtomPub server libraries with file- or DB-based backends can you recommend? Unix-style servers that "do one thing, do it well" are especially welcome. Maybe even libraries in Python? A: Maybe this? http://atomserver.codehaus.org/ If someone is looking for a library to us...
Simple AtomPub server library
What simple AtomPub server libraries with file- or DB-based backends can you recommend? Unix-style servers that "do one thing, do it well" are especially welcome. Maybe even libraries in Python?
[ "Maybe this?\nhttp://atomserver.codehaus.org/\nIf someone is looking for a library to use in building Atompub into an existing service, they should definitely use Abdera directly. AtomServer, by contrast, is a full java web application that can be up and running in a few minutes by configuring a database and a few ...
[ 2, 1, 1 ]
[]
[]
[ "atom_feed", "atompub", "http", "python" ]
stackoverflow_0001544196_atom_feed_atompub_http_python.txt
Q: Rose diagrams in Google Chart I searched around for ways to make rose diagrams (circular histograms) in Google Chart. The API has only radar diagrams, so it seems not technically possible (am I correct?). This wind rose example was the closest I came to a solution. Because I needed them, I figured out a way to fak...
Rose diagrams in Google Chart
I searched around for ways to make rose diagrams (circular histograms) in Google Chart. The API has only radar diagrams, so it seems not technically possible (am I correct?). This wind rose example was the closest I came to a solution. Because I needed them, I figured out a way to fake them quickly using the Radar plot...
[ "Well, it looks like no-one has any other examples. I DID decide to play around with this to see what else is possible and created a quick proof of concept for time-based rose diagrams. It's just a silly thing to show your relative Twitter posting amount by time of day, but shows how Google Chart can be used for ro...
[ 1 ]
[]
[]
[ "google_visualization", "histogram", "python" ]
stackoverflow_0001368822_google_visualization_histogram_python.txt
Q: Django Custom Managers for User model How would I go about extending the default User model with custom managers? My app has many user types that will be defined using the built-in Groups model. So a User might be a client, a staff member, and so on. It would be ideal to be able to do something like: User.clients....
Django Custom Managers for User model
How would I go about extending the default User model with custom managers? My app has many user types that will be defined using the built-in Groups model. So a User might be a client, a staff member, and so on. It would be ideal to be able to do something like: User.clients.filter(name='Test') To get all clients wit...
[ "Yes, you can add a custom manager directly to the User class. This is monkeypatching, and it does make your code less maintainable (someone trying to figure out your code may have no idea where the User class acquired that custom manager, or where they could look to find it). In this case it's relatively harmless,...
[ 18 ]
[ "You can user Profile for this\n\nAUTH_PROFILE_MODULE =\n 'accounts.UserProfile'\nWhen a user profile model has been\n defined and specified in this manner,\n each User object will have a method --\n get_profile() -- which returns the\n instance of the user profile model\n associated with that User.\n\nOr you...
[ -2 ]
[ "django", "python" ]
stackoverflow_0001642779_django_python.txt
Q: Is there any way to use a strftime-like function for dates before 1900 in Python? I didn't realize this, but apparently Python's strftime function doesn't support dates before 1900: >>> from datetime import datetime >>> d = datetime(1899, 1, 1) >>> d.strftime('%Y-%m-%d') Traceback (most recent call last): File "...
Is there any way to use a strftime-like function for dates before 1900 in Python?
I didn't realize this, but apparently Python's strftime function doesn't support dates before 1900: >>> from datetime import datetime >>> d = datetime(1899, 1, 1) >>> d.strftime('%Y-%m-%d') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: year=1899 is before 1900; the datetime strfti...
[ "isoformat works on datetime instances w/o limitation of range:\n>>> import datetime\n>>> x=datetime.datetime(1865, 7, 2, 9, 30, 21)\n>>> x.isoformat()\n'1865-07-02T09:30:21'\n\nIf you need a different-format string it's not too hard to slice, dice and remix pieces of the string you get from isoformat, which is ver...
[ 15, 11, 3, 3, 1 ]
[]
[]
[ "datetime", "oracle", "python", "sql_loader", "strftime" ]
stackoverflow_0001643967_datetime_oracle_python_sql_loader_strftime.txt
Q: Unable to find solution for a practice problem in codechef Here is the problem from code chef : A set of N dignitaries have arrived in close succession at Delhi and are awaiting transportation to Roorkee to participate in the inaugural ceremony of Cognizance. Being big sponsors of Cognizance, it has been deemed u...
Unable to find solution for a practice problem in codechef
Here is the problem from code chef : A set of N dignitaries have arrived in close succession at Delhi and are awaiting transportation to Roorkee to participate in the inaugural ceremony of Cognizance. Being big sponsors of Cognizance, it has been deemed unsuitable by the organizing team to arrange for more than one di...
[ "One first error (I doubt it's blocking you):\nif int(test[0]) is not len(test[1:]):\n\nIt's never correct to use is / is not to test immutables (such as numbers): use = or != instead. The code you've written may accidentally work as an implementation-based artifact in versions of Python that \"cache\" small integ...
[ 2, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0001644456_algorithm_python.txt
Q: Customising Install location for Django (or any Python module) I'd like to to install Django into a custom location, I've read the distutils documentation and it suggests that I should be able to do something like the following to install under my home directory (when run from an unpacked django tarball). > python...
Customising Install location for Django (or any Python module)
I'd like to to install Django into a custom location, I've read the distutils documentation and it suggests that I should be able to do something like the following to install under my home directory (when run from an unpacked django tarball). > python setup.py install --home=~/code/packages/install --install-purelib=m...
[ "I would strongly suggest that you look at Virtualenv and Pip for creating basically silos of python packages.\nThe Pinax project uses this exclusively now for bundling requirements together for other people to use, and it's becoming more and more of a defacto standard in the reusable apps space.\n", "Ok, so I've...
[ 2, 1, 0, 0 ]
[]
[]
[ "distutils", "django", "python" ]
stackoverflow_0001643540_distutils_django_python.txt
Q: How to handle Unicode (non-ASCII) characters in Python? I'm programming in Python and I'm obtaining information from a web page through the urllib2 library. The problem is that that page can provide me with non-ASCII characters, like 'ñ', 'á', etc. In the very moment urllib2 gets this character, it provokes an exc...
How to handle Unicode (non-ASCII) characters in Python?
I'm programming in Python and I'm obtaining information from a web page through the urllib2 library. The problem is that that page can provide me with non-ASCII characters, like 'ñ', 'á', etc. In the very moment urllib2 gets this character, it provokes an exception, like this: File "c:\Python25\lib\httplib.py", line 71...
[ "You just read a set of bytes from the socket. If you want a string you have to decode it:\nyourstring = receivedbytes.decode(\"utf-8\") \n\n(substituting whatever encoding you're using for utf-8)\nThen you have to do the reverse to send it back out:\noutbytes = yourstring.encode(\"utf-8\")\n\n", "You want to us...
[ 11, 6, 0 ]
[]
[]
[ "character_encoding", "python", "unicode" ]
stackoverflow_0001644640_character_encoding_python_unicode.txt
Q: Django db reset without loading fixtures Is there an easy way to reset a django database (i.e. drop all data/tables, create new tables and create indexes) without loading fixture data afterwords? What I want to have is just an empty database because all data is loaded from another source (a kind of a post-processe...
Django db reset without loading fixtures
Is there an easy way to reset a django database (i.e. drop all data/tables, create new tables and create indexes) without loading fixture data afterwords? What I want to have is just an empty database because all data is loaded from another source (a kind of a post-processed backup). I know that this could be achieved...
[ "shouldn't you be able do do this with manage.py's reset option?\n", "As far as I know, the fixtures (in initial_data file) are automatically loaded after manage.py syndcb and not after reset. So, if you do a manage.py reset yourapp it should not load the fixtures. Hmm?\n" ]
[ 2, 2 ]
[]
[]
[ "database", "django", "fixtures", "python" ]
stackoverflow_0001645310_database_django_fixtures_python.txt
Q: How this keyword is provided for object instances in C#? When you have an object instance in C#, you can use the this keyword inside the instance scope. How does the compiler handles it? Is there any assistance for this at runtime? I am mainly wondering how C# does it vs in python you have to provide self for ever...
How this keyword is provided for object instances in C#?
When you have an object instance in C#, you can use the this keyword inside the instance scope. How does the compiler handles it? Is there any assistance for this at runtime? I am mainly wondering how C# does it vs in python you have to provide self for every function manually.
[ "This is supported at the CLR level. The argument variable at slot 0 represents the \"this\" pointer. C# essentially generates calls to this as ldarg.0\n", "The compiler always creates IL that sets the field using the class name, in any case - whether you specify this or not. The this. is optional unless there...
[ 3, 2 ]
[]
[]
[ ".net", "c#", "clr", "python" ]
stackoverflow_0001645550_.net_c#_clr_python.txt
Q: Threading in a PyQt application: Use Qt threads or Python threads? I'm writing a GUI application that regularly retrieves data through a web connection. Since this retrieval takes a while, this causes the UI to be unresponsive during the retrieval process (it cannot be split into smaller parts). This is why I'd li...
Threading in a PyQt application: Use Qt threads or Python threads?
I'm writing a GUI application that regularly retrieves data through a web connection. Since this retrieval takes a while, this causes the UI to be unresponsive during the retrieval process (it cannot be split into smaller parts). This is why I'd like to outsource the web connection to a separate worker thread. [Yes, I ...
[ "This was discussed not too long ago in PyQt mailing list. Quoting Giovanni Bajo's comments on the subject:\n\nIt's mostly the same. The main difference is that QThreads are better\n integrated with Qt (asynchrnous signals/slots, event loop, etc.).\n Also, you can't use Qt from a Python thread (you can't for inst...
[ 120, 38, 22, 14, 9, 5, 0 ]
[]
[]
[ "multithreading", "pyqt", "python" ]
stackoverflow_0001595649_multithreading_pyqt_python.txt
Q: insert string in the middle of a file given a file object I am working on a problem and got stuck at a wall I have a (potentially large) set of text files, and I need to apply a sequence of filters and transformations to it and export it to some other places. so I roughly have def apply_filter_transformer(basepath...
insert string in the middle of a file given a file object
I am working on a problem and got stuck at a wall I have a (potentially large) set of text files, and I need to apply a sequence of filters and transformations to it and export it to some other places. so I roughly have def apply_filter_transformer(basepath = None, newpath = None, fts= None): #because all the raw s...
[ "There is handy python module for modifing or reading a group of files: fileinput\nI'm not sure what is causing this error. But you are reading the whole file into memory which is a bad idea in your case because the files are potentially large. Using fileinput you can replace the files easily. For example:\nimport ...
[ 1, 1 ]
[]
[]
[ "file", "python", "string" ]
stackoverflow_0001645384_file_python_string.txt
Q: Django: Extending Querysets / Connect multiple filters with OR I have to work with a queryset, that is already filtered, eg. qs = queryset.filter(language='de') but in some further operation i need to undo some of the already applied filtering, eg not to take only the rows with language='de' but entries in all lan...
Django: Extending Querysets / Connect multiple filters with OR
I have to work with a queryset, that is already filtered, eg. qs = queryset.filter(language='de') but in some further operation i need to undo some of the already applied filtering, eg not to take only the rows with language='de' but entries in all languages. Is there a way to apply filter again and have the new parame...
[ "I don't believe it is possible to do what you are asking.\nThe way you do ORs in django is like this:\nModel.objects.filter(Q(question__startswith='Who') | Q(question__startswith='What'))\n\nso if you actually wanted to do this:\nModel.objects.filter(Q(language='de') | Q(language='en'))\n\nyou would need to put th...
[ 3 ]
[]
[]
[ "django", "django_queryset", "filter", "python" ]
stackoverflow_0001645778_django_django_queryset_filter_python.txt
Q: how convert list of int to list of tuples I want to convert a list like this l1 = [1,2,3,4,5,6,7,8] to l2 = [(1,2),(3,4),(5,6),(7,8)] because want to loop for x,y in l2: draw_thing(x,y) A: One good way is: from itertools import izip it = iter([1, 2, 3, 4]) for x, y in izip(it, it): print x, y Output:...
how convert list of int to list of tuples
I want to convert a list like this l1 = [1,2,3,4,5,6,7,8] to l2 = [(1,2),(3,4),(5,6),(7,8)] because want to loop for x,y in l2: draw_thing(x,y)
[ "One good way is:\nfrom itertools import izip\nit = iter([1, 2, 3, 4])\nfor x, y in izip(it, it):\n print x, y\n\nOutput:\n1 2\n3 4\n>>> \n\n", "Building on Nick D's answer:\n>>> from itertools import izip\n>>> t = [1,2,3,4,5,6,7,8,9,10,11,12]\n>>> for a, b in izip(*[iter(t)]*2):\n... print a, b\n...\n1 2\...
[ 10, 7, 5, 2, 0, 0, 0, 0 ]
[ "What's wrong with just accessing the correct index and incrementing?\nfor (int i=0;i<myList.Length;i++)\n{\n draw_thing(myList[i],myList[++i]);\n}\nOops - sorry, in C# mode. I'm sure you get the idea.\n" ]
[ -3 ]
[ "python" ]
stackoverflow_0001645673_python.txt
Q: Python, subprocess, devenv, why no output? I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output. p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() ret...
Python, subprocess, devenv, why no output?
I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output. p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() ret = p.returncode Here, both out and err are alwa...
[ "Change it from 'devenv' to 'devenv.com'. Apparenty Popen looks for .EXEs first but the shell looks for .COMs first. Switching to 'devenv.com' worked for me.\ndevenv is significantly faster then msbuild for incremental builds. I just did a build with an up to date project, meaning nothing should happen.\ndevenv 23...
[ 26, 2, 0 ]
[ "Probably your problem is the same that the pipe's buffer fills up. Check this question for a good answer.\n" ]
[ -2 ]
[ "python", "subprocess" ]
stackoverflow_0001525696_python_subprocess.txt
Q: psyco complains about unsupported opcode 54, what is it? The Psyco log output look like this: 21:08:47.56 Logging started, 10/29/09 %%%%%%%%%%%%%%%%%%%% 21:08:47.56 unsupported opcode 54 at create_l0:124 % % 21:08:47.56 unsupported opcode 54 at create_lx:228 ...
psyco complains about unsupported opcode 54, what is it?
The Psyco log output look like this: 21:08:47.56 Logging started, 10/29/09 %%%%%%%%%%%%%%%%%%%% 21:08:47.56 unsupported opcode 54 at create_l0:124 % % 21:08:47.56 unsupported opcode 54 at create_lx:228 % % the lines in question class File: def __init__(...
[ "Finding the name of the opcode using the number is actually pretty easy (below uses Python 2.6.2 on Ubuntu, you may get different results):\n>>> import dis\n>>> dis.opname[54]\n'STORE_MAP'\n\nOf course, finding out what exactly this means is another question entirely. :-)\n", "Did you compile with another Psyco...
[ 2, 0 ]
[]
[]
[ "psyco", "python" ]
stackoverflow_0001646260_psyco_python.txt
Q: Setting mod_python's interperter I have mod_python installed on a debian box with python 2.4 and 2.6 installed. I want mod_python to use 2.6 but it is finding 2.4. How can set it to use the other version. A: The version of Python used is set when mod_python is compiled. If you need to use a version other than t...
Setting mod_python's interperter
I have mod_python installed on a debian box with python 2.4 and 2.6 installed. I want mod_python to use 2.6 but it is finding 2.4. How can set it to use the other version.
[ "The version of Python used is set when mod_python is compiled. If you need to use a version other than the default, you'll need to recompile it, or you may be able to find a different package from the repository.\n" ]
[ 1 ]
[]
[]
[ "apache", "mod_python", "python" ]
stackoverflow_0001646017_apache_mod_python_python.txt
Q: Python on AIX: What are my options? I need to make some Python applications for a work project. The target platform is AIX 5.3. My question is: What version of Python should I be using? My requirements are: The Python version must be easy to install on the target machines. Others will do that according to instruc...
Python on AIX: What are my options?
I need to make some Python applications for a work project. The target platform is AIX 5.3. My question is: What version of Python should I be using? My requirements are: The Python version must be easy to install on the target machines. Others will do that according to instructions that I write, so no compiling from ...
[ "Use the AS Package of Python 2.6.3.7 from Activestate. They have a binary package for AIX on their download site.\nIf you don't have an AIX machine to test it on, the install works the same way on Solaris or Linux, so you could write your documentation based on that. Basically, you ungzip the tarball file, use tar...
[ 7, 4, 1 ]
[]
[]
[ "aix", "curses", "ncurses", "python" ]
stackoverflow_0001646293_aix_curses_ncurses_python.txt
Q: referencing a key/value in django-templates after applying a filter say I have the following list that I provide to a django template stuff= [ { 'a':2 , 'b':4 } , { 'a',7} ] I want to access the 'a' attribute of the first element. I can't quite get the syntax right. {{stuff|first}} gives me the first element, b...
referencing a key/value in django-templates after applying a filter
say I have the following list that I provide to a django template stuff= [ { 'a':2 , 'b':4 } , { 'a',7} ] I want to access the 'a' attribute of the first element. I can't quite get the syntax right. {{stuff|first}} gives me the first element, but {{stuff|first.a}} is a dead end ( and weird ) and I can't seem to fi...
[ "This is off the top of my head, but I think it is\n{{ stuff.0.a }}\n\n" ]
[ 4 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0001646757_django_django_templates_python.txt
Q: Is it OK to extend both old and new style classes? When I extended some tool generated classes, I didn't realize that they are old style classes until I tried to use super(). The super() doesn't work with old style classes, so I got this error: TypeError: super() argument 1 must be type, not classobj E.g., try th...
Is it OK to extend both old and new style classes?
When I extended some tool generated classes, I didn't realize that they are old style classes until I tried to use super(). The super() doesn't work with old style classes, so I got this error: TypeError: super() argument 1 must be type, not classobj E.g., try this snippet: >>> class A: ... def greet(self): ... ...
[ "New-style classes have been recommended practice in Python since they were introduced in Python 2.2. In Python 3.x, only new-style classes are available. Therefore, I recommend you switch your classes to new-style.\nI am not aware of any real problems you might have from this. For the most part, new-style class...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001641958_python.txt
Q: Adapt an existing database to a django app I have a Postgresql databese with data. I want to create a django app with that database. How can i import the tables to django models and/or views? A: There is a utility called manage.py inspectdb to generate models from your existing database. It works pretty well. $...
Adapt an existing database to a django app
I have a Postgresql databese with data. I want to create a django app with that database. How can i import the tables to django models and/or views?
[ "There is a utility called manage.py inspectdb to generate models from your existing database. It works pretty well.\n$ python manage.py inspectdb > models.py\n\n", "If your database is not very simple -- or very well designed -- you'll find it a poor fit with Django.\nWhile the reverse engineering works well, ...
[ 19, 3 ]
[]
[]
[ "database", "django_models", "django_views", "postgresql", "python" ]
stackoverflow_0001646786_database_django_models_django_views_postgresql_python.txt
Q: django @login_required decorator error I'm running django 1.1rc. All of my code works correctly using django's built in development server; however, when I move it into production using Apache's mod_python, I get the following error on all of my views: Caught an exception while rendering: Reverse for '<django.con...
django @login_required decorator error
I'm running django 1.1rc. All of my code works correctly using django's built in development server; however, when I move it into production using Apache's mod_python, I get the following error on all of my views: Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin What might...
[ "Having googled on this a bit, it sounds like you may need to delete any .pyc files on the server and let it recompile them the first time they're accessed.\n", "I had a problem with my apache configuration:\nI changed this:\nSetEnv DJANGO_SETTINGS_MODULE settings\nto this:\nSetEnv DJANGO_SETTINGS_MODULE booster....
[ 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001195432_django_python.txt
Q: Django Year/Month based posts archive i'm new to Django and started an application, i did the models, views, templates, but i want to add some kind of archive to the bottom of the page, something like this http://www.flickr.com/photos/ionutgabriel/3990015411/. So i want to list all years and next to them all th...
Django Year/Month based posts archive
i'm new to Django and started an application, i did the models, views, templates, but i want to add some kind of archive to the bottom of the page, something like this http://www.flickr.com/photos/ionutgabriel/3990015411/. So i want to list all years and next to them all the months from that year. The months who hav...
[ "Firstly, the datetime format strings are given in the django docs. I think you want capital instead of lowercase 'M'.\nSince you want to display all 12 months of a year, even if only some have posts, we'll create an archives object to pass to the template. I've chosen to use a dictionary where\n\nthe keys are the ...
[ 12, 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001645962_django_python.txt
Q: Correct way to access related objects I have the following models class Person(models.Model): name = models.CharField(max_length=100) class Employee(Person): job = model.Charfield(max_length=200) class PhoneNumber(models.Model): person = models.ForeignKey(Person) How do I access the PhoneNumbers a...
Correct way to access related objects
I have the following models class Person(models.Model): name = models.CharField(max_length=100) class Employee(Person): job = model.Charfield(max_length=200) class PhoneNumber(models.Model): person = models.ForeignKey(Person) How do I access the PhoneNumbers associated with an employee if I have the em...
[ "You can (and should) filter without knowing the foreign key field:\nPhoneNumber.objects.filter(employee=your_employee).all()\n\n", "You could do:\nemployees = Employee.objects.filter(id=your_id).select_related()\nif employees.count() == 1:\n phone_numbers = employees[0].phonenumber_set.all()\n\nThat should ge...
[ 5, 4 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001647043_django_django_models_python.txt
Q: Multi Language Starter Templates I'm currently working through some code katas in multiple languages (Ruby, Perl, Python)/frameworks (Rails, Django, Mojo). It seems every time I start a new project from scratch I end up tweaking files to my liking, even after using things like newgem, module-starter, script/genera...
Multi Language Starter Templates
I'm currently working through some code katas in multiple languages (Ruby, Perl, Python)/frameworks (Rails, Django, Mojo). It seems every time I start a new project from scratch I end up tweaking files to my liking, even after using things like newgem, module-starter, script/generate, startapp, etc. For those who progr...
[ "Just use the templating capabilities of your editor.\nFor vim, check out this example.\nUpdate:\nWhich editor? The choice of editor is too deeply personal and reliant on individual preference for me to recommend any single editor. Pick a cross platform editor that is powerful enough (like Vim or Emacs), learn to ...
[ 2 ]
[]
[]
[ "perl", "python", "ruby", "starter_kits", "templates" ]
stackoverflow_0001647614_perl_python_ruby_starter_kits_templates.txt
Q: How can I use Microsoft Word's spelling/grammar checker programmatically? I want to process a medium to large number of text snippets using a spelling/grammar checker to get a rough approximation and ranking of their "quality." Speed is not really of concern either, so I think the easiest way is to write a script...
How can I use Microsoft Word's spelling/grammar checker programmatically?
I want to process a medium to large number of text snippets using a spelling/grammar checker to get a rough approximation and ranking of their "quality." Speed is not really of concern either, so I think the easiest way is to write a script that passes off the snippets to Microsoft Word (2007) and runs its spelling an...
[ "It took some digging, but I think I found a useful solution. Following the advice at http://www.nabble.com/Edit-a-Word-document-programmatically-td19974320.html I'm using the win32com module (if the SourceForge link doesn't work, according to this Stack Overflow answer you can use pip to get the module), which al...
[ 9 ]
[]
[]
[ "com", "ms_word", "python", "win32com", "word_2007" ]
stackoverflow_0001646801_com_ms_word_python_win32com_word_2007.txt
Q: Python question on elementwise operation I have two srtings of integer a=[-1,0,-1,0,1] and b=[1] and i want to subtract b from a as elementwise operation but the answer shoud be string contaning element -1 or 0 or 1 A: Maybe you mean this: def elementwise_subtraction_of_strings_of_integer(a, b): c = b * (le...
Python question on elementwise operation
I have two srtings of integer a=[-1,0,-1,0,1] and b=[1] and i want to subtract b from a as elementwise operation but the answer shoud be string contaning element -1 or 0 or 1
[ "Maybe you mean this:\ndef elementwise_subtraction_of_strings_of_integer(a, b):\n c = b * (len(a) // len(b))\n return [aa - bb for aa, bb in zip(a, c)]\n\nif __name__ == '__main__':\n a=[-1,0,-1,0,1]\n b=[1]\n print elementwise_subtraction_of_strings_of_integer(a, b)\n\nIt produces this:\n[-2, -1, -2...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0001647112_python.txt
Q: Python PyQT4 - Adding an unknown number of QComboBox widgets to QGridLayout I want to retrieve a list of people's names from a queue and, for each person, place a checkbox with their name to a QGridLayout using the addWidget() function. I can successfully place the items in a QListView, but they just write over th...
Python PyQT4 - Adding an unknown number of QComboBox widgets to QGridLayout
I want to retrieve a list of people's names from a queue and, for each person, place a checkbox with their name to a QGridLayout using the addWidget() function. I can successfully place the items in a QListView, but they just write over the top of each other rather than creating a new row. Does anyone have any thoughts...
[ "This line:\nQtGui.QCheckBox('%s' % item, self.chk_People)\n\nDoesn't add the check box to the list view, it only creates it with the list view as the parent, and there's a big difference. \nThe simplest way to use a list view is the QListWidget convenience class. For that, create your checkboxes as instances of QL...
[ 1, 0 ]
[]
[]
[ "pyqt", "python", "qcombobox", "qlistview" ]
stackoverflow_0001647664_pyqt_python_qcombobox_qlistview.txt
Q: How to deploy Python to Windows users? I'm soon to launch a beta app and this have the option to create custom integration scripts on Python. The app will target Mac OS X and Windows, and my problem is with Windows where Python normally is not present. My actual aproach is silently run the Python 2.6 install. Howe...
How to deploy Python to Windows users?
I'm soon to launch a beta app and this have the option to create custom integration scripts on Python. The app will target Mac OS X and Windows, and my problem is with Windows where Python normally is not present. My actual aproach is silently run the Python 2.6 install. However I face the problem that is not activated...
[ "Copy a Portable Python folder out of your installer, into the same folder as your Delphi/Lazarus app. Set all paths appropriately for that.\n", "You might try using py2exe. It creates a .exe file with Python already included!\n", "Integrate the python interpreter into your Delphi app with P4D. These compone...
[ 15, 13, 4, 1 ]
[]
[]
[ "delphi", "deployment", "lazarus", "python", "windows" ]
stackoverflow_0001646326_delphi_deployment_lazarus_python_windows.txt
Q: mod_python django logging problem I use logging settings as below in the settings.py file: logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT); handler = logging.handlers.RotatingFileHandler( LOG_FILE_PATH, 'a', LOG_FILE_SIZE,LOG_FILE_NUM ); formatter = logging.Formatter ( LOG_FORMAT ); handler.setFormatter(f...
mod_python django logging problem
I use logging settings as below in the settings.py file: logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT); handler = logging.handlers.RotatingFileHandler( LOG_FILE_PATH, 'a', LOG_FILE_SIZE,LOG_FILE_NUM ); formatter = logging.Formatter ( LOG_FORMAT ); handler.setFormatter(formatter); logging.getLogger().addHandl...
[ "RotatingFileHandler is not designed to work in multiprocess system. Each process you have notice that file is too large and starts new log, so you get up to 5 new logs. It's not as easy to implement it properly: you have to obtain interprocess lock before creating new file and inform each process to reopen it. You...
[ 2 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0001647974_django_logging_python.txt
Q: How to encode an RSA key using PKCS12 in Python? I'm using Python (under Google App Engine), and I have some RSA private keys that I need to export in PKCS#12 format. Is there anything out there that will assist me with this? I'm using PyCrypto/KeyCzar, and I've figured out how to import/export RSA keys in PKCS8 f...
How to encode an RSA key using PKCS12 in Python?
I'm using Python (under Google App Engine), and I have some RSA private keys that I need to export in PKCS#12 format. Is there anything out there that will assist me with this? I'm using PyCrypto/KeyCzar, and I've figured out how to import/export RSA keys in PKCS8 format, but I really need it in PKCS12. Can anybody poi...
[ "If you can handle some ASN.1 generation, you can relatively easily convert a PKCS#8-file into a PKCS#12-file. A PKCS#12-file is basically a wrapper around a PKCS#8 and a certificate, so to make a PKCS#12-file, you just have to add some additional data around your PKCS#8-file and your certificate.\nUsually a PKCS#1...
[ 2, 0, 0 ]
[]
[]
[ "cryptography", "google_app_engine", "pkcs#12", "python", "rsa" ]
stackoverflow_0001647568_cryptography_google_app_engine_pkcs#12_python_rsa.txt
Q: Google wave robot inline reply I've been working on my first robot for google wave recently, a vital part of what it does is to insert inline replies into a blip. I can't for the life of me figure out how to do this! The API docs have a function InsertInlineBlip which sounded promising, however calling that doesn'...
Google wave robot inline reply
I've been working on my first robot for google wave recently, a vital part of what it does is to insert inline replies into a blip. I can't for the life of me figure out how to do this! The API docs have a function InsertInlineBlip which sounded promising, however calling that doesn't appear to do anything! EDIT:: It s...
[ "If you look at the sourcecode for OpBasedDocument.InsertInlineBlip() you will see the following:\n 412 - def InsertInlineBlip(self, position): \n 413 \"\"\"Inserts an inline blip into this blip at a specific position. \n 414 \n 415 Args: \n 416 position: Position to insert the blip at. \n 417 ...
[ 4, 2, 1 ]
[]
[]
[ "google_wave", "python" ]
stackoverflow_0001561655_google_wave_python.txt
Q: How to configure format of Python 2.3 logging messages? In Python 2.4 and later, configuring the logging module to have a more basic formatting is easy: logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s") but for applications which need to support Python 2.3 it seems more difficult, because the logging ...
How to configure format of Python 2.3 logging messages?
In Python 2.4 and later, configuring the logging module to have a more basic formatting is easy: logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s") but for applications which need to support Python 2.3 it seems more difficult, because the logging API was overhauled in Py2.4. In particular, basicConfig doesn...
[ "except: without exception class[es] is a good way to get in trouble. I believe logging module in Python 2.3 has basicConfig() function, but with less options. Since it accepts **kwargs it may fail at any moment after doing some job. I think it already installed a handler with default format then failed to configur...
[ 4 ]
[]
[]
[ "formatting", "legacy", "logging", "python" ]
stackoverflow_0001646470_formatting_legacy_logging_python.txt
Q: Python library path I have a python file "testHTTPAuth.py" which uses module deliciousapi and is kept in "deliciousapi.py". I have kept the files like testHTTPAuth.py lib deliciousapi.py But when i run: "python testHTTPAuth.py" it's giving error import deliciousapi ImportError: No module named deliciousa...
Python library path
I have a python file "testHTTPAuth.py" which uses module deliciousapi and is kept in "deliciousapi.py". I have kept the files like testHTTPAuth.py lib deliciousapi.py But when i run: "python testHTTPAuth.py" it's giving error import deliciousapi ImportError: No module named deliciousapi How can handle these ...
[ "You need to add the 'lib' directory to your path - otherwise, Python can't find your source. The following (included in a module such as testHTTPAuth.py) will do that:\nsys.path.append(os.path.join(os.path.dirname(__file__), 'lib')\n\nNed's suggestion of changing your imports may work, but if anything in the lib d...
[ 9, 1 ]
[]
[]
[ "google_app_engine", "python", "shared_libraries" ]
stackoverflow_0001649186_google_app_engine_python_shared_libraries.txt
Q: Open Source Profiling Frameworks? Have you ever wanted to test and quantitatively show whether your application would perform better as a static build or shared build, stripped or non-stripped, upx or no upx, gcc -O2 or gcc -O3, hash or btree, etc etc. If so this is the thread for you. There are hundreds of ways t...
Open Source Profiling Frameworks?
Have you ever wanted to test and quantitatively show whether your application would perform better as a static build or shared build, stripped or non-stripped, upx or no upx, gcc -O2 or gcc -O3, hash or btree, etc etc. If so this is the thread for you. There are hundreds of ways to tune an application, but how do we co...
[ "There was a talk at PyCon this week discussing the various profiling methods on Python today. I don't think anything is as complete as what your looking for, but it may be worth a look.\nhttp://us.pycon.org/2009/conference/schedule/event/15/\nYou should be able to find the actual talk later this week on blip.tv\n...
[ 2, 0, 0 ]
[]
[]
[ "profiling", "python" ]
stackoverflow_0000224735_profiling_python.txt
Q: Overriding Django views with decorators I have a situation that requires redirecting users who are already logged in away from the login page to another page. I have seen mention that this can be accomplished with decorators which makes sense, but I am fairly new to using them. However, I am using the django log...
Overriding Django views with decorators
I have a situation that requires redirecting users who are already logged in away from the login page to another page. I have seen mention that this can be accomplished with decorators which makes sense, but I am fairly new to using them. However, I am using the django login and a third party view (from django-regist...
[ "Three more ways to do it, though you'll need to use your own urlconf for these:\n\nAdd the decorator to the view directly in the urlconf:\n...\n(regexp, decorator(view)),\n...\n\nYou need to import the view and the decorator into the urlconf though, which is why I don't like this one. I prefer to have as few impor...
[ 6, 2 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0001649351_django_django_views_python.txt
Q: How to handle multiple Set-Cookie header in HTTP response I'm trying to write simple proxy server for some purpose. In it I use httplib to access remote web-server. But there's one problem: web server returns TWO Set-Cookie headers in one response, and httplib mangles them together in httplib.HTTPResponse.getheade...
How to handle multiple Set-Cookie header in HTTP response
I'm trying to write simple proxy server for some purpose. In it I use httplib to access remote web-server. But there's one problem: web server returns TWO Set-Cookie headers in one response, and httplib mangles them together in httplib.HTTPResponse.getheaders(), effectively joining cookies with comma [which is strange,...
[ "HTTPResponse.getheaders() returns a list of combined headers (actually my calling dict.items()). The only place where incoming headers are stored untouched is HTTPResponse.msg.headers.\n" ]
[ 4 ]
[]
[]
[ "httplib", "python" ]
stackoverflow_0001649401_httplib_python.txt
Q: How to test for multiple command line arguments (sys.argv I want to test againts multiple command line arguments in a loop > python Read_xls_files.py group1 group2 group3 No this code tests only for the first one (group1). hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: ...
How to test for multiple command line arguments (sys.argv
I want to test againts multiple command line arguments in a loop > python Read_xls_files.py group1 group2 group3 No this code tests only for the first one (group1). hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) How should I modify this...
[ "You can iterate over sys.argv[1:], e.g. via something like:\nfor grp in sys.argv[1:]:\n for i in range(len(sh.col_values(8))):\n if sh.cell(i, 1).value == grp:\n hlo.append(sh.cell(i, 8).value)\n\n", "outputList = [x for x in values if x in sys.argv[1:]]\n\nSubstitute the bits that are relevant for your ...
[ 7, 3, 2, 1, 0, 0 ]
[]
[]
[ "excel", "loops", "python" ]
stackoverflow_0001643643_excel_loops_python.txt
Q: How can I send an iCalendar email attachment with Django? I want to send an iCalendar http://en.wikipedia.org/wiki/ICalendar email attachment using Django. Is there an open source library to build an iCalendar file in Python and/or available for Django? A: As stated before, there is vobject, that is working fin...
How can I send an iCalendar email attachment with Django?
I want to send an iCalendar http://en.wikipedia.org/wiki/ICalendar email attachment using Django. Is there an open source library to build an iCalendar file in Python and/or available for Django?
[ "As stated before, there is vobject, that is working fine (I have used it recently). \nYou can find good information about ical, vobject and django in this blog post : \nhttp://blog.thescoop.org/archives/2007/07/31/django-ical-and-vobject/\n", "I've used MaxM's icalendar module. It can build and parse iCalendar f...
[ 7, 4, 3 ]
[]
[]
[ "django", "icalendar", "python" ]
stackoverflow_0001647597_django_icalendar_python.txt
Q: Generating a dynamic time delta: python Here's my situation: import foo, bar, etc frequency = ["hours","days","weeks"] class geoProcessClass(): def __init__(self,geoTaskHandler,startDate,frequency,frequencyMultiple=1,*args): self.interval = self.__determineTimeDelta(frequency,frequencyMultiple) ...
Generating a dynamic time delta: python
Here's my situation: import foo, bar, etc frequency = ["hours","days","weeks"] class geoProcessClass(): def __init__(self,geoTaskHandler,startDate,frequency,frequencyMultiple=1,*args): self.interval = self.__determineTimeDelta(frequency,frequencyMultiple) def __determineTimeDelta(self,frequency,freq...
[ "You can call a function with dynamic arguments using syntax like func(**kwargs) where kwargs is dictionary of name/value mappings for the named arguments.\nI also renamed the global frequency list to frequencies since the line if frequency in frequency didn't make a whole lot of sense.\nclass geoProcessClass():\n ...
[ 7, 0 ]
[]
[]
[ "datetime", "eval", "python", "timedelta" ]
stackoverflow_0001649753_datetime_eval_python_timedelta.txt
Q: Django ignoring my DATABASE_ENGINE setting -- sometimes I've got several sites, each with a distinct settings file -- and with distinct names. There's a floral theme to all the variant settings. We have to keep the sites separate. C:\Proj-Carnation> echo %DJANGO_SETTINGS_MODULE% path.to.settings_carnation_win32 ...
Django ignoring my DATABASE_ENGINE setting -- sometimes
I've got several sites, each with a distinct settings file -- and with distinct names. There's a floral theme to all the variant settings. We have to keep the sites separate. C:\Proj-Carnation> echo %DJANGO_SETTINGS_MODULE% path.to.settings_carnation_win32 We have many test procedures which don't use the built-in dj...
[ "Found it.\nWhen your settings module is inside a package, the top-level __init__.py member of that package cannot import any Django material of any kind.\nIf the top-level __init__.py that contains your settings has a Django import, that Django import will (potentially) use the default settings before your setting...
[ 10 ]
[]
[]
[ "configuration", "django", "python" ]
stackoverflow_0001639451_configuration_django_python.txt
Q: Common errors when moving a django app from dev to prod? I am developping a django app on Windows, SQLite and the django dev server . I have deployed it to my host server which is running Linux, Apache, FastCgi, MySQL. Unfortunately, I have an error returned by the server on the prod while everything ok on the dev...
Common errors when moving a django app from dev to prod?
I am developping a django app on Windows, SQLite and the django dev server . I have deployed it to my host server which is running Linux, Apache, FastCgi, MySQL. Unfortunately, I have an error returned by the server on the prod while everything ok on the dev machine. I've asked my provider for a pre-production solution...
[ "Problems I typically have include:\n\nMisconfigured productions settings, whether in my production localsettings.py, wsgi/cgi, or apache site files in /etc/sites-available\nDatabase differences. I use South for migrations and have run into some subtle issues when performing my migration on PostgreSQL when it worke...
[ 7, 1, 0 ]
[]
[]
[ "django", "production_environment", "python" ]
stackoverflow_0001648349_django_production_environment_python.txt
Q: Is there a way to know if a list of elements is on a larger list without using 'in' keyword? I want to do this. I have two python lists, one larger than the other and I want to know is there is a way to check if the elements of the smaller list are in the big list in the exact same order for example: small_list = ...
Is there a way to know if a list of elements is on a larger list without using 'in' keyword?
I want to do this. I have two python lists, one larger than the other and I want to know is there is a way to check if the elements of the smaller list are in the big list in the exact same order for example: small_list = [4,2,5] big_list = [1,2,5,7,2,4,2,5,67,8,5,13,45] I tried using the in keyword but It did not wor...
[ "def in_list(small, big):\n l_sml = len(small)\n l_big = len(big)\n return any((big[i:i+l_sml]==small for i in xrange(l_big-l_sml+1)))\n\nprint in_list([4,2,1], [1,2,3,4,2,1,0,5]) # True\nprint in_list([1,2,3], [1,2,4]) # False\n\n", "Hmm, maybe it's overkill, but you can use the SequenceMatche...
[ 7, 4, 3, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001646641_python.txt
Q: Convert & to & in Python I'm working on a simple crawler in Python. The aim is to create a sitemap.xml. (you can find the very alpha version here: http://code.google.com/p/sitemappy/) I noticed that if I generate the xml with URLs containing non HTML entities (such as &), the xml doesn't validate and it isn't acce...
Convert & to & in Python
I'm working on a simple crawler in Python. The aim is to create a sitemap.xml. (you can find the very alpha version here: http://code.google.com/p/sitemappy/) I noticed that if I generate the xml with URLs containing non HTML entities (such as &), the xml doesn't validate and it isn't accepted by Google Webmaster Tools...
[ "cgi.escape to the rescue:\n\ncgi.escape(s[, quote])\nConvert the characters '&', '<' and '>' in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. If the optional flag quote is true, the quotation mark character ('\"') is also translated; this helps fo...
[ 8, 7 ]
[]
[]
[ "python", "sitemap", "urlencode", "xml" ]
stackoverflow_0001650160_python_sitemap_urlencode_xml.txt
Q: Regular expression to extract "Boolean" and "MessageString" from {'result':(Boolean, MessageString)} How to parse the string " {'result':(Boolean, MessageString)} " using Python regular expressions to get Boolean and the MessageString separated into variables? A: This works: >>> x = re.search('\((.*),\s*(.*)\)',...
Regular expression to extract "Boolean" and "MessageString" from {'result':(Boolean, MessageString)}
How to parse the string " {'result':(Boolean, MessageString)} " using Python regular expressions to get Boolean and the MessageString separated into variables?
[ "This works:\n>>> x = re.search('\\((.*),\\s*(.*)\\)', \" {'result':(Boolean, MessageString)} \")\n>>> x.group(1)\n'Boolean'\n>>> x.group(2)\n'MessageString'\n\n", "It looks like a dictionary+tuple in Python syntax, so eval() would also work (if you trust the source!!!)\n", "Depending on what you need there can...
[ 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001650244_python_regex.txt
Q: Doctest failing inspite of having correct output My function is def validate_latitude(lat): """Enforce latitude is in range >>> validate_latitude(65) 65 >>> validate_latitude(91) 90 >>> validate_latitude(-91) -90 """ lat = min(lat, 90) lat = max(lat, -90) return lat ...
Doctest failing inspite of having correct output
My function is def validate_latitude(lat): """Enforce latitude is in range >>> validate_latitude(65) 65 >>> validate_latitude(91) 90 >>> validate_latitude(-91) -90 """ lat = min(lat, 90) lat = max(lat, -90) return lat And the test fails with this output ****************...
[ "Whitespace?\nIf I highlight your output, I can see additional whitespace following the \"Expected\" value. Not sure whether this is relevant or not.\n", "In these two lines:\n>>> validate_latitude(-91)\n-90 \n\nYou have a Tab character before the - in -90, and four space characters after the 0. When doctests ...
[ 3, 3 ]
[]
[]
[ "doctest", "python" ]
stackoverflow_0001650184_doctest_python.txt
Q: Python: Object identity assertions thrown by differences in import statement notations When checking an object's identity, I am getting assertion errors because the object creation code imports the object-defining module under one notation (base.other_stuff.BarCode) and the identity-checking code imports that same...
Python: Object identity assertions thrown by differences in import statement notations
When checking an object's identity, I am getting assertion errors because the object creation code imports the object-defining module under one notation (base.other_stuff.BarCode) and the identity-checking code imports that same module under a different notation (other_stuff.BarCode). (Please see below for gory detail...
[ "It looks like you have <root>/ and <root>/base in your sys.path, which is always bad. When you do import other_stuff.BarCode as bc from base/stuff/FooCode.py it imports other_stuff as root package, but not subpackage of base. So after doing import base.other_stuff.BarCode as bc you get BarCode module imported twic...
[ 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001650603_python.txt
Q: best way to parse a line in python to a dictionary I have a file with lines like account = "TEST1" Qty=100 price = 20.11 subject="some value" values="3=this, 4=that" There is no special delimiter and each key has a value that is surrounded by double quotes if its a string but not if it is a number. There is no ke...
best way to parse a line in python to a dictionary
I have a file with lines like account = "TEST1" Qty=100 price = 20.11 subject="some value" values="3=this, 4=that" There is no special delimiter and each key has a value that is surrounded by double quotes if its a string but not if it is a number. There is no key without a value though there may exist blank strings w...
[ "We're going to need a regex for this.\nimport re, decimal\nr= re.compile('([^ =]+) *= *(\"[^\"]*\"|[^ ]*)')\n\nd= {}\nfor k, v in r.findall(line):\n if v[:1]=='\"':\n d[k]= v[1:-1]\n else:\n d[k]= decimal.Decimal(v)\n\n>>> d\n{'account': 'TEST1', 'subject': 'some value', 'values': '3=this, 4=th...
[ 11, 5, 0, 0 ]
[]
[]
[ "delimiter", "parsing", "python" ]
stackoverflow_0001644362_delimiter_parsing_python.txt
Q: Get last function's call arguments from traceback? Can I get the parameters of the last function called in traceback? How? I want to make a catcher for standard errors to make readable code, yet provide detailed information to user. In the following example I want GET_PARAMS to return me a tuple of parameters supp...
Get last function's call arguments from traceback?
Can I get the parameters of the last function called in traceback? How? I want to make a catcher for standard errors to make readable code, yet provide detailed information to user. In the following example I want GET_PARAMS to return me a tuple of parameters supplied to os.chown. Examining the inspect module advised b...
[ "For such inspection tasks, always think first of module inspect in the standard library. Here, inspect.getargvalues gives you the argument values given a frame, and inspect.getinnerframes gives you the frames of interest from a traceback object.\n", "Here is an example of such function and some problems that yo...
[ 5, 3, 0 ]
[]
[]
[ "exception_handling", "python", "traceback" ]
stackoverflow_0001650713_exception_handling_python_traceback.txt
Q: Google Federated Login (OpenID+Oauth) for Hosted Apps - changing end points? I'm trying to integrate the Google Federated Login with a premier apps account, but I'm having some problems. When I send the request to: https://www.google.com/accounts/o8/ud with all the parameters (see below), I get back both a request...
Google Federated Login (OpenID+Oauth) for Hosted Apps - changing end points?
I'm trying to integrate the Google Federated Login with a premier apps account, but I'm having some problems. When I send the request to: https://www.google.com/accounts/o8/ud with all the parameters (see below), I get back both a request_token and list of attributes asked for by Attribute Exchange. This is perfect, as...
[ "For the record, posterity, and anyone else who might come asunder of this, I'll document the (ridiculous) answer.\nUltimately, the problem was calling:\nreturn HttpResponseRedirect(\n 'https://www.google.com/a/thedomain.com/o8/ud?be=o8'\n + '?'\n + urllib.urlencode(parameters)\n)\n\nCan you spot it? Yeah,...
[ 7 ]
[]
[]
[ "hybridauthprovider", "oauth", "openid", "python" ]
stackoverflow_0001543123_hybridauthprovider_oauth_openid_python.txt
Q: pyGTK ComboBox List Height I'm just getting started with pyGtk programming, so bear with me. I have a dialog with a ComboBox. The list that shows up when I click on the combo box has 70+ times in it. It extends from the top of the screen to the bottom. I can live with it, but I'd rather have the ComboBox perfo...
pyGTK ComboBox List Height
I'm just getting started with pyGtk programming, so bear with me. I have a dialog with a ComboBox. The list that shows up when I click on the combo box has 70+ times in it. It extends from the top of the screen to the bottom. I can live with it, but I'd rather have the ComboBox perform like an html select element(i...
[ "You can use a gtk.ComboBoxEntry instead of gtk.ComboBox. I have tested a ComboBoxEntry with 100 items and it works how you want. The downside is that the user will be able to type whatever they want into it, but you just need to validate the input before you do anything with it. On the upside you could implement a...
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0001635161_gtk_pygtk_python.txt
Q: IronPython to Original Python comparison. What can I expect from the first one? I wish to learn Python but I'm working all day in .Net as a C# developer, so I decided to download and install IronPython and integrated IronPython studio. How different or similar from the original Python it is? As a .Net developer ca...
IronPython to Original Python comparison. What can I expect from the first one?
I wish to learn Python but I'm working all day in .Net as a C# developer, so I decided to download and install IronPython and integrated IronPython studio. How different or similar from the original Python it is? As a .Net developer can I expect to run conventional Python script in .Net environment with no problem or t...
[ "In your situation it's perfectly reasonable to study IronPython (especially as this book does a great job helping you do that!). You'll have access to essentially all of Python 2.5 functionality (not sure when IronPython will upgrade to a 2.6 version of Python, but 2.5 is already quite usable), plus all the .Net ...
[ 3, 1 ]
[]
[]
[ ".net", "comparison", "ironpython", "ironpython_studio", "python" ]
stackoverflow_0001650898_.net_comparison_ironpython_ironpython_studio_python.txt
Q: Create triplets from list of words Let's say I have a list of words, something like this: ['The', 'Quick', 'Brown', 'Fox', 'Jumps', 'Over', 'The', 'Lazy', 'Dog'] I'd like to generate a list of lists, with each array containing 3 of the words, but with a possible triplet for each one. So it should look something l...
Create triplets from list of words
Let's say I have a list of words, something like this: ['The', 'Quick', 'Brown', 'Fox', 'Jumps', 'Over', 'The', 'Lazy', 'Dog'] I'd like to generate a list of lists, with each array containing 3 of the words, but with a possible triplet for each one. So it should look something like this: ['The', 'Quick', 'Brown'] ['Qu...
[ ">>> words\n['The', 'Quick', 'Brown', 'Fox', 'Jumps', 'Over', 'The', 'Lazy', 'Dog']\n>>> [words[i:i+3] for i in range(len(words) - 2)]\n[['The', 'Quick', 'Brown'], ['Quick', 'Brown', 'Fox'], ['Brown', 'Fox', 'Jumps'], ['Fox', 'Jumps', 'Over'], ['Jumps', 'Over', 'The'], ['Over', 'The', 'Lazy'], ['The', 'Lazy', 'Dog'...
[ 7, 5, 3 ]
[ "Without knowing why you want to do this or how many times it needs to be done, I'd say just slice it. \n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0001651386_list_python.txt
Q: Python Array is read-only, can't append values I am new to Python. The following code is causing an error when it attempts to append values to an array. What am I doing wrong? import re from array import array freq_pattern = re.compile("Frequency of Incident[\(\)A-Za-z\s]*\.*\s*([\.0-9]*)") col_pattern = re.com...
Python Array is read-only, can't append values
I am new to Python. The following code is causing an error when it attempts to append values to an array. What am I doing wrong? import re from array import array freq_pattern = re.compile("Frequency of Incident[\(\)A-Za-z\s]*\.*\s*([\.0-9]*)") col_pattern = re.compile("([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)\s+([-\...
[ "Do you want to append to the array?\ne_rcs.append( float(cols.group(2)) )\n\nDoing this: e_rcs.append = float(cols.group(2)) replaces the append method of the array e-rcs with a floating-point value. Rarely something you want to do.\n", "You are assigning to the append() function, you want instead to call .appe...
[ 6, 6, 3, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0001651430_arrays_python.txt
Q: Extracting ALL matches of a nested regular expression in python I am trying to parse a list of items which satisfies the python regex r'\A(("[\w\s]+"|\w+)\s+)*\Z' that is, it's a space separated list except that spaces are allowed inside quoted strings. I would like to get a list of items in the list (that is of ...
Extracting ALL matches of a nested regular expression in python
I am trying to parse a list of items which satisfies the python regex r'\A(("[\w\s]+"|\w+)\s+)*\Z' that is, it's a space separated list except that spaces are allowed inside quoted strings. I would like to get a list of items in the list (that is of items matched by the r'("[\w\s]+"|\w+)' part. So, for example >>> pa...
[ "I don't think that regex is the right tool here. Try csv module:\n>>> s = 'foo \"bar baz\" \"bob\" '\n>>> for i in csv.reader([s], delimiter=' '):\n print(i)\n\n\n['foo', 'bar baz', 'bob', '']\n\n", "Here's a solution that splits on any whitespace that isn't inside a pair of quotation marks:\nre.split('\\s+(?...
[ 2, 1, 1 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0001633984_parsing_python_regex.txt
Q: Calling types via their name as a string in Python I'm aware of using globals(), locals() and getattr to referance things in Python by string (as in this question) but unless I'm missing something obvious I can't seem to use this with calling types. e.g.: In [12]: locals()['int'] ----------------------------------...
Calling types via their name as a string in Python
I'm aware of using globals(), locals() and getattr to referance things in Python by string (as in this question) but unless I'm missing something obvious I can't seem to use this with calling types. e.g.: In [12]: locals()['int'] --------------------------------------------------------------------------- KeyError ...
[ "There are locals,globals, and then builtins.\nPerhaps you are looking for the builtin:\nimport __builtin__\ngetattr(__builtin__,'int')\n\n", "You've already gotten a solution using builtins, but another worthwhile technique to hold in your toolbag is a dispatch table. If your CSV is designed to be used by multi...
[ 12, 7, 3, 2, 2, 1 ]
[]
[]
[ "getattr", "python" ]
stackoverflow_0001650338_getattr_python.txt
Q: Is it still Python 2.6 versus Python 3? G'day, I'm wanting to go back to Python after not using it for a while and I saw this question "Python Version for a Newbie" while wondering about getting back into Python 2.6 or Python 3. Almost all of the questions' answers were along the lines that most of the code out th...
Is it still Python 2.6 versus Python 3?
G'day, I'm wanting to go back to Python after not using it for a while and I saw this question "Python Version for a Newbie" while wondering about getting back into Python 2.6 or Python 3. Almost all of the questions' answers were along the lines that most of the code out there, libraries, legacy systems, etc., is 2.5 ...
[ "Yes. Virtually all live production systems will use 2.5/2.6 for a long time yet. There's no point learning 3.0, only to have to downgrade it because your host doesn't support it.\n95% of what you will learn in 2.5/2.6 is applicable to 3 anyway.\n", "Depends on the amount of libraries you're going to use.\n\nRaw ...
[ 9, 3, 2, 2, 1 ]
[]
[]
[ "python", "python_3.x", "version" ]
stackoverflow_0001649391_python_python_3.x_version.txt
Q: Close all opened xml tags I have a file, which change it content in a short time. But I'd like to read it before it is ready. The problem is, that it is an xml-file (log). So when you read it, it could be, that not all tags are closed. I would like to know if there is a possibility to close all opened tags correct...
Close all opened xml tags
I have a file, which change it content in a short time. But I'd like to read it before it is ready. The problem is, that it is an xml-file (log). So when you read it, it could be, that not all tags are closed. I would like to know if there is a possibility to close all opened tags correctly, that there are no problems ...
[ "Some XML parsers allow incremental parsing of XML documents that is the parser can start working on the document without needing it to be fully loaded. The XMLTreeBuilder from the xml.etree.ElementTree module in the Python standard library is one such parser: Element Tree\nAs you can see in the example below you c...
[ 6, 1, 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001644994_python_xml.txt
Q: Widget Transparency in PyGTK? What is the best way to have transparency of specific widgets in a PyGTK application? I do not want to use themes because the transparency of each of the widgets will be changing through animation. The only thing I can find is to use cairo to draw widgets with an Alpha, but I can't fi...
Widget Transparency in PyGTK?
What is the best way to have transparency of specific widgets in a PyGTK application? I do not want to use themes because the transparency of each of the widgets will be changing through animation. The only thing I can find is to use cairo to draw widgets with an Alpha, but I can't figure out how to do this. Is there p...
[ "Assuming that your program runs under composition manager, you could get per-widget transparency by manipulating widget's X window. Look at gtk.gdk.Window.set_opacity().\nNote, it is not gtk.Window; you can get this object by getting its window property (buttonWidget.window), but only when widget is realized and o...
[ 3 ]
[]
[]
[ "cairo", "gtk", "linux", "pygtk", "python" ]
stackoverflow_0001652779_cairo_gtk_linux_pygtk_python.txt
Q: Datastore datetimeproperty iterable? I have model class info(db.Model): user = db.UserProperty() last_update_date = db.DateTimeProperty() I need to retrieve last_update_date for specific user. It is working good, i can retrieve this value, i can even pass it to another variable if results: for result ...
Datastore datetimeproperty iterable?
I have model class info(db.Model): user = db.UserProperty() last_update_date = db.DateTimeProperty() I need to retrieve last_update_date for specific user. It is working good, i can retrieve this value, i can even pass it to another variable if results: for result in results: data = res...
[ "An example from the contacts API documentation:\nupdated_min = raw_input('Enter updated min (example: 2007-03-16T00:00:00): ')\nquery = gdata.contacts.service.ContactsQuery()\nquery.updated_min = updated_min\n\nI think the updated_min property takes a string, not a datetime object.\n" ]
[ 1 ]
[]
[]
[ "datetime", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0001642441_datetime_google_app_engine_google_cloud_datastore_python.txt
Q: Lightweight crash recovery for Python What would be the best way to handle lightweight crash recovery for my program? I have a Python program that runs a number of test cases and the results are stored in a dictionary which serves as a cache. If I could save (and then restore) each item that is added to the dicti...
Lightweight crash recovery for Python
What would be the best way to handle lightweight crash recovery for my program? I have a Python program that runs a number of test cases and the results are stored in a dictionary which serves as a cache. If I could save (and then restore) each item that is added to the dictionary, I could simply run the program again...
[ "There's no good way to guard against \"your program crashing while writing a checkpoint to a file\", but why should you worry so much about that?! What ELSE is your program doing at that time BESIDES \"saving checkpoint to a file\", that could easily cause it to crash?!\nIt's hard to beat pickle (or cPickle) for ...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001653460_python.txt
Q: Trapping signals in Python According to the documentation: There is no way to “block” signals temporarily from critical sections (since this is not supported by all Unix flavors). What stops me using signal.signal(signum,SIG_IGN) to block it, then adding the signal back? A: What stops you is that, if the signa...
Trapping signals in Python
According to the documentation: There is no way to “block” signals temporarily from critical sections (since this is not supported by all Unix flavors). What stops me using signal.signal(signum,SIG_IGN) to block it, then adding the signal back?
[ "What stops you is that, if the signal actually arrives while SIG_IGN is in place, then it will be ignored and thrown away. When you add the signal back later, it's too late because it's gone and you'll never get to learn that it happened.\nThus, you will have \"ignored\" (= thrown away) the signal rather than \"bl...
[ 11 ]
[]
[]
[ "python", "signals" ]
stackoverflow_0001654215_python_signals.txt
Q: How can I parse text in Python? Sample Text: SUBJECT = 'NETHERLANDS MUSIC EPA' CONTENT = 'Michael Buble performs in Amsterdam Canadian singer Michael Buble performs during a concert in Amsterdam, The Netherlands, 30 October 2009. Buble released his new album entitled 'Crazy Love'. EPA/OLAF KRAAK ' Expected result...
How can I parse text in Python?
Sample Text: SUBJECT = 'NETHERLANDS MUSIC EPA' CONTENT = 'Michael Buble performs in Amsterdam Canadian singer Michael Buble performs during a concert in Amsterdam, The Netherlands, 30 October 2009. Buble released his new album entitled 'Crazy Love'. EPA/OLAF KRAAK ' Expected result: " NETHERLANDS MUSIC EPA | 36 before...
[ "Looks like you want something like...:\nimport re\n\nx = re.compile(r'^([^\\|]*?)\\s*\\|[^\\n]*\\n\\s*(.*?)\\s*$')\n\ns = \"\"\"NETHERLANDS MUSIC EPA | 36 before\nMichael Buble performs in Amsterdam Canadian singer Michael Buble performs during a concert in Amsterdam, The Netherlands, 30 October 2009. Buble releas...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001653509_python_regex.txt
Q: Run command pipes with subprocess.Popen How can I run the following command using subprocess.Popen? mysqldump database_name table_name | bzip2 > filename I know os.system() can do the job but I dont want to wait for the dump to finish in main program. A: You want the shell=True option to make it execute shell c...
Run command pipes with subprocess.Popen
How can I run the following command using subprocess.Popen? mysqldump database_name table_name | bzip2 > filename I know os.system() can do the job but I dont want to wait for the dump to finish in main program.
[ "You want the shell=True option to make it execute shell commands:\nimport subprocess\nsubprocess.Popen(\"sleep 4s && echo right thar, right thar\",shell=True);\nprint 'i like it when you put it'\n\nwhich yields:\n I like it when you put it\n [4 seconds later]\n right thar, right thar\n\n" ]
[ 6 ]
[]
[]
[ "command", "pipe", "python" ]
stackoverflow_0001654600_command_pipe_python.txt
Q: Find a path in Windows relative to another This problem should be a no-brainer, but I haven't yet been able to nail it. I need a function that takes two parameters, each a file path, relative or absolute, and returns a filepath which is the first path (target) resolved relative to the second path (start). The reso...
Find a path in Windows relative to another
This problem should be a no-brainer, but I haven't yet been able to nail it. I need a function that takes two parameters, each a file path, relative or absolute, and returns a filepath which is the first path (target) resolved relative to the second path (start). The resolved path may be relative to the current directo...
[ "I agree with you: this seems like a deficiency in os.path.join. Looks like you have to deal with the drives separately. This code passes all your tests:\ndef findpath(target, start=os.path.curdir):\n sdrive, start = os.path.splitdrive(start)\n tdrive, target = os.path.splitdrive(target)\n rdrive = tdriv...
[ 3 ]
[]
[]
[ "filesystems", "python", "relative_path", "windows" ]
stackoverflow_0001654659_filesystems_python_relative_path_windows.txt
Q: erlang on google app engine? I know python can be run on GAE what is different erlang and python in lay man term? can erlang run on google app engine ? A: Erlang and Python are programming languages, and each language has one or more "runtimes" that allow you to run programs written in those languages. GAE supp...
erlang on google app engine?
I know python can be run on GAE what is different erlang and python in lay man term? can erlang run on google app engine ?
[ "Erlang and Python are programming languages, and each language has one or more \"runtimes\" that allow you to run programs written in those languages. GAE supplies a Python runtime.\nGAE has no support for Erlang programs.\n" ]
[ 11 ]
[]
[]
[ "erlang", "google_app_engine", "python" ]
stackoverflow_0001654759_erlang_google_app_engine_python.txt
Q: If pickling was interrupted, will unpickling necessarily always fail? - Python Suppose my attempt to write a pickle object out to disk is incomplete due to a crash. Will an attempt to unpickle the object always lead to an exception or is it possible that the fragment that was written out may be interpreted as vali...
If pickling was interrupted, will unpickling necessarily always fail? - Python
Suppose my attempt to write a pickle object out to disk is incomplete due to a crash. Will an attempt to unpickle the object always lead to an exception or is it possible that the fragment that was written out may be interpreted as valid pickle and the error go unnoticed?
[ "Contra the other answers offered, I believe that we can make a strong argument about the recoverability of a pickle. That answer is: \"Yes, an incomplete pickle always leads to an exception.\"\nWhy are we able to do this? Because the \"pickle\" format is in fact a small stack-based language. In a stack-based langu...
[ 8, 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001653897_python.txt
Q: Besides NLTK, what is the best information retrieval library for Python? For use to analyze documents on the Internet! A: Alternatively, R has many tools available for text mining, and it's easy to integrate with Python using RPy2. Have a look at the Natural Language Processing view on CRAN. In particular, look...
Besides NLTK, what is the best information retrieval library for Python?
For use to analyze documents on the Internet!
[ "Alternatively, R has many tools available for text mining, and it's easy to integrate with Python using RPy2.\nHave a look at the Natural Language Processing view on CRAN. In particular, look at the tm package. Here are some relevant links:\n\nPaper about the package in the Journal of Statistical Computing: http...
[ 5, 3 ]
[]
[]
[ "information_retrieval", "python", "text_mining" ]
stackoverflow_0001635014_information_retrieval_python_text_mining.txt
Q: Python MultiThreading With Urllib2 Issue I can download multiple files quite fast with many threads at once but the problem is that after a few minutes it tends to slow down gradually to almost a full stop, I have no idea why. There's nothing wrong with my code that I can see and my RAM/CPU is fine.. The only thin...
Python MultiThreading With Urllib2 Issue
I can download multiple files quite fast with many threads at once but the problem is that after a few minutes it tends to slow down gradually to almost a full stop, I have no idea why. There's nothing wrong with my code that I can see and my RAM/CPU is fine.. The only thing I can think of is that urllib2 isn't handlin...
[ "Can you confirm that doing the same number of simultaneous downloads without python continues to download fast? Perhaps the issue is not with your code, but with your connection getting throttled or with the site serving the files.\nIf that's not the issue you could try the pyprocessing library to implement a mult...
[ 3, 1 ]
[]
[]
[ "multithreading", "python", "sockets", "urllib" ]
stackoverflow_0001654721_multithreading_python_sockets_urllib.txt
Q: Install PyObjC on Python 2.6 on OS X 10.5? OS X 10.5.8 came with Python 2.5, and had PyObjC already installed. I installed Python 2.6 from the python.org site, and PyObjC isn't there. I can't find a download to install PyObjC on my Python 2.6 install. Is checking out the PyObjC trunk and trying to build it my onl...
Install PyObjC on Python 2.6 on OS X 10.5?
OS X 10.5.8 came with Python 2.5, and had PyObjC already installed. I installed Python 2.6 from the python.org site, and PyObjC isn't there. I can't find a download to install PyObjC on my Python 2.6 install. Is checking out the PyObjC trunk and trying to build it my only choice? Will that work "out of the box"?
[ "Apple includes PyObjC with their Pythons that come with OS X 10.5 and 10.6. It is not part of the python.org installers. But it should be easy enough to install. Just install setuptools to the python.org python 2.6 following the instructions here. Then use easy_install-2.6 (which will have been installed in /L...
[ 1, 1, 0 ]
[]
[]
[ "installation", "macos", "pyobjc", "python" ]
stackoverflow_0001653153_installation_macos_pyobjc_python.txt
Q: Output file redirection in Python I'm writing a backup script I intend to execute in a cronjob every night. The script sets sys.stdout and sys.stderr to an output file to keep a log of what happens. To do the backup I use the following code cmd = 'rsync -av --del --stats --filter "- .thumbnails/" ' + \ '--fil...
Output file redirection in Python
I'm writing a backup script I intend to execute in a cronjob every night. The script sets sys.stdout and sys.stderr to an output file to keep a log of what happens. To do the backup I use the following code cmd = 'rsync -av --del --stats --filter "- .thumbnails/" ' + \ '--filter "- *~" --filter "- *.iso" --filter ...
[ "I just found the solution here in a Stackoverflow answer.\nReplace \nsys.stderr = sys.stdout = logFile = open( tmpLogFileName, 'a' )\n\nwith \nsys.stderr = sys.stdout = logFile = open( tmpLogFileName, 'a', 0 )\n\nThis tells python to not assign any output buffer to file.\n", "Have you tried putting the flush cal...
[ 3, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0001654875_file_python.txt
Q: Explanation of PyAPI_DATA() macro? I've searched all over the web and can't seem to find documentation or even a simple explanation of what PyAPI_DATA() does (even though it is used in the Python header files and cited on python.org). Could anyone care to explain what this is or point me to documentation I am over...
Explanation of PyAPI_DATA() macro?
I've searched all over the web and can't seem to find documentation or even a simple explanation of what PyAPI_DATA() does (even though it is used in the Python header files and cited on python.org). Could anyone care to explain what this is or point me to documentation I am overlooking? Thanks.
[ "It's used to mark public API variables (as Python's core is usually a dynamic library), e.g. on Windows, it's expanded to extern __declspec(dllexport) RTYPE when core is compiled and to extern __declspec(dllimport) RTYPE when e.g. modules are compiled. It's defined in Include/pyport.h.\n" ]
[ 9 ]
[]
[]
[ "api", "c", "python", "python_c_api" ]
stackoverflow_0001655271_api_c_python_python_c_api.txt
Q: Subclassing python's dict, override of __setitem__ doesn't retain new value I'm subclassing dict, but ran into a problem with setitem where one assignment works, but another assignment does not. I've boiled it down to the following basic problem: class CustomDict(dict): def __setitem__(self, key, value): super(...
Subclassing python's dict, override of __setitem__ doesn't retain new value
I'm subclassing dict, but ran into a problem with setitem where one assignment works, but another assignment does not. I've boiled it down to the following basic problem: class CustomDict(dict): def __setitem__(self, key, value): super(CustomDict, self).__setitem__(key, value) Test 1 fails: data = {"message":"foo"}...
[ "You are constructing new instances of CustomDict on each line. CustomDict(data) makes a new instance, which copies data.\nTry this:\ncd = CustomData({\"message\":\"foo\"})\ncd[\"message\"] = \"bar\"\nprint cd # prints \"{'message': 'bar'}\".\n\n" ]
[ 10 ]
[]
[]
[ "dictionary", "python", "subclass" ]
stackoverflow_0001655422_dictionary_python_subclass.txt
Q: Can I access the __dict__ object for the local scope? Here is my situation... I am trying to dynamically generate a bunch of stuff in my settings.py file on a django site. I am setting up several sites, (via sites framework) and I want to have some values I plug in to a function that will generate a portion of the...
Can I access the __dict__ object for the local scope?
Here is my situation... I am trying to dynamically generate a bunch of stuff in my settings.py file on a django site. I am setting up several sites, (via sites framework) and I want to have some values I plug in to a function that will generate a portion of the settings file for each site. for example: from universal_s...
[ "Dict returned by locals() (or globals()) is mutable, so you could do:\ndef get_dynamic_settings(context_dict):\n context_dict['DEFAULT_FROM_EMAIL'] = '%s <noreply@otakupride.com>' % context_dict['SITE_NAME']\n context_dict['ROOT_URLCONF'] = 'mysite.urls.%s' % context_dict['SITE_SLUG']\n context_dict['TEMP...
[ 3, 3 ]
[]
[]
[ "django", "python", "scope", "settings" ]
stackoverflow_0001655509_django_python_scope_settings.txt
Q: Converting Python code to PHP What is the following Python code in PHP? import sys li = range(1,777); def countFigure(li, n): m = str(n); return str(li).count(m); # counting figures for substr in range(1,10): print substr, " ", countFigure(li, substr); Wanted output for 777 1 258 2 ...
Converting Python code to PHP
What is the following Python code in PHP? import sys li = range(1,777); def countFigure(li, n): m = str(n); return str(li).count(m); # counting figures for substr in range(1,10): print substr, " ", countFigure(li, substr); Wanted output for 777 1 258 2 258 3 258 4 258 5 258 6 258...
[ "It's been a while since I did any Python but I think this should do it.\nIf you could clarify what str(li) looks like it would help.\n<?php\n\n$li = implode('', range(1, 776));\n\nfunction countFigure($li, $n)\n{\n return substr_count($li, $n);\n}\n\n// counting figures\n\nforeach (range(1, 9) as $substr)\n ...
[ 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0001655556_php_python.txt
Q: How can I generate random numbers in Python? Are there any built-in libraries in Python or Numpy to generate random numbers based on various common distributions, such as: Normal Poisson Exponential Bernoulli And various others? Are there any such libraries with multi-variate distributions? A: #!/usr/bin/env p...
How can I generate random numbers in Python?
Are there any built-in libraries in Python or Numpy to generate random numbers based on various common distributions, such as: Normal Poisson Exponential Bernoulli And various others? Are there any such libraries with multi-variate distributions?
[ "#!/usr/bin/env python\nfrom scipy.stats import bernoulli,poisson,norm,expon\n\nbernoulli, poisson, norm, expon and many others are documented here \nprint(norm.rvs(size=30))\nprint(bernoulli.rvs(.3,size=30))\nprint(poisson.rvs(1,2,size=30))\nprint(expon.rvs(5,size=30))\n\nAll the distributions defined in scipy.sta...
[ 27, 5 ]
[]
[]
[ "python", "random" ]
stackoverflow_0001655559_python_random.txt
Q: Help with a AppEngine Handler Regex? I've been trying to design a Google AppEngine Python handler regex and haven't been too successful in getting it to work. I'm trying to handle API calls similar to OpenStreetMap's. My current regex looks like this: /api/0.6/(.*?)/(.*?)\/?(.*?) But when this comes in: /api/0.6/c...
Help with a AppEngine Handler Regex?
I've been trying to design a Google AppEngine Python handler regex and haven't been too successful in getting it to work. I'm trying to handle API calls similar to OpenStreetMap's. My current regex looks like this: /api/0.6/(.*?)/(.*?)\/?(.*?) But when this comes in: /api/0.6/changeset/723/close It incorrectly groups 7...
[ "Try this:\n^/api/0.6/([^/]+)/([^/]+)/?([^/]*)$\n\nMy Python tests:\n>>> regex = re.compile(r\"^/api/0.6/([^/]+)/([^/]+)/?([^/]*)$\")\n>>> regex.match(\"/api/0.6/changeset\") is None\nTrue\n>>> regex.match(\"/api/0.6/changeset/723\").groups()\n('changeset', '723', '')\n>>> regex.match(\"/api/0.6/changeset/723/close...
[ 3 ]
[]
[]
[ "google_app_engine", "python", "regex" ]
stackoverflow_0001655745_google_app_engine_python_regex.txt
Q: Querying the connecting device for usb devices in OS X Ok, so here's the setup. In OS X (>= 10.5), is it possible, given a mounted usb device with a known location, say /Volumes/FLASHDRIVE, to find out whether this device is connecting through another usb device (a card reader for example) and if so, which one. I...
Querying the connecting device for usb devices in OS X
Ok, so here's the setup. In OS X (>= 10.5), is it possible, given a mounted usb device with a known location, say /Volumes/FLASHDRIVE, to find out whether this device is connecting through another usb device (a card reader for example) and if so, which one. Ideally, this could all be done in python, but if not that's ...
[ "You're confusing the term device with the term volume--in this example (and in most real world situations) there would only be one device involved. \nThe state of most hardware falls under the purview of IOKit, and the only way you can possibly get to this information from Python is through careful parsing of the ...
[ 0 ]
[]
[]
[ "macos", "python", "usb" ]
stackoverflow_0001655927_macos_python_usb.txt
Q: Avoid C style comments while reading a file I am parsing a C file for LOC in a function using python. I am starting from first line of function definition and skipping all lines till i met first "{". The issue is that "{" can also come as a part of comment. I just want to skip all "{" present inside comments. e.g ...
Avoid C style comments while reading a file
I am parsing a C file for LOC in a function using python. I am starting from first line of function definition and skipping all lines till i met first "{". The issue is that "{" can also come as a part of comment. I just want to skip all "{" present inside comments. e.g 100: int func( 102: int i, // some commen...
[ "Here is a comment stripper that should also comprehend comment introducers within quoted strings:\nfrom pyparsing import cppStyleComment,dblQuotedString\n\ncppStyleComment.ignore(dblQuotedString)\nsrc = cppStyleComment.suppress().transformString(src)\n\nprint src\n\nWith your original snippet as src, this prints:\...
[ 7, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001654649_python.txt
Q: an auth method over HTTP(s) and/or REST with libraries for Python and/or C++ Because I don't exactly know how any auth method works I want to write my own. So, what I want to do is the following. A client sends over HTTPs username+password(or SHA1(username+password)) the server gets the username+password and gen...
an auth method over HTTP(s) and/or REST with libraries for Python and/or C++
Because I don't exactly know how any auth method works I want to write my own. So, what I want to do is the following. A client sends over HTTPs username+password(or SHA1(username+password)) the server gets the username+password and generates a big random number and stores it in a table called TOKENS(in some database...
[ "If you are implementing such authentication system over ordinary HTTP, you are vulnerable to replay attacks. Attacker could sniff out the SHA1(username+password) and just resend it every time he/she wants to log in. To make such authentication system work, you will need to use a nonce.\nYou might want to look at H...
[ 0, 0, 0 ]
[]
[]
[ "authentication", "c++", "http", "python", "rest" ]
stackoverflow_0001486056_authentication_c++_http_python_rest.txt
Q: appending successfully to a python list This may seem like the worlds simplest python question... But I'm going to give it a go of explaining it. Basically I have to loop through pages of json results from a query. the standard result is this {'result': [{result 1}, {result 2}], 'next_page': '2'} I need the loop ...
appending successfully to a python list
This may seem like the worlds simplest python question... But I'm going to give it a go of explaining it. Basically I have to loop through pages of json results from a query. the standard result is this {'result': [{result 1}, {result 2}], 'next_page': '2'} I need the loop to continue to loop, appending the list in th...
[ "Alternate (cleaner) approach, making one big list:\nresults = []\nres = { \"next_page\": \"magic_token_to_get_first_page\" }\nwhile \"next_page\" in res:\n fp = urllib2.urlopen(\"http://search.twitter.com/search.json\" + res[\"next_page\"])\n res = simplejson.load(fp)\n fp.close()\n results.extend(res[...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "append", "dictionary", "list", "python" ]
stackoverflow_0001656059_append_dictionary_list_python.txt
Q: Shortest total path among set of Latitude/Longitudes I have a set of 52 or so latitude/longitude pairs. I simply need to find the shortest path through all of them; it doesn't matter where staring point or ending point is. I've implemented Dijkstra's algorithm by hand multiple times before and don't really have t...
Shortest total path among set of Latitude/Longitudes
I have a set of 52 or so latitude/longitude pairs. I simply need to find the shortest path through all of them; it doesn't matter where staring point or ending point is. I've implemented Dijkstra's algorithm by hand multiple times before and don't really have the time to do it again. I've found a couple things that co...
[ "If this is a closed path, it is the Traveling Salesman Problem, and a sub-optimal but quite effective way to resolve it is to use Simulated Annealing\n", "In python, the best graph handling library I was able to put my hands on is networkx. It supports a broad range of different algos for short path search.\nGo ...
[ 3, 2, 0 ]
[]
[]
[ "clojure", "graph_theory", "mapping", "python" ]
stackoverflow_0001656112_clojure_graph_theory_mapping_python.txt
Q: Would it be possible to write a 3D game as large as World of Warcraft in pure Python? Would it be possible to write a 3D game as large as World of Warcraft in pure Python? Assuming the use of DirectX / D3D bindings or OpenGL bindings. If not, what would be the largest hold-up to doing such a project in Python? I k...
Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? Assuming the use of DirectX / D3D bindings or OpenGL bindings. If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of ha...
[ "Yes. How it will perform is another question.\nA good development pattern would be to develop it in pure python, and then profile it, and rewrite performance-critical bottlenecks, either in C/C++/Cython or even python itself but with more efficient code.\n", "While I don't know all the technical details of World...
[ 17, 14, 9, 7, 6, 6, 5, 5, 4, 2, 2, 0, 0 ]
[]
[]
[ "3d", "direct3d", "python" ]
stackoverflow_0000916663_3d_direct3d_python.txt
Q: Grab some ofx data with python I was trying to use http://www.jongsma.org/gc/scripts/ofx-ba.py to grab my bank account information from wachovia. Having no luck, I decided that I would just try to manually construct some request data using this example So, I have this file that I want to use as the request data. ...
Grab some ofx data with python
I was trying to use http://www.jongsma.org/gc/scripts/ofx-ba.py to grab my bank account information from wachovia. Having no luck, I decided that I would just try to manually construct some request data using this example So, I have this file that I want to use as the request data. Let's call it req.ofxsgml: FXHEADER:...
[ "The problem was that you were previously passing in the data from your file directly as the data parameter to the Request. The file you were reading in contains both the headers and the data that you should be sending. You needed to supply the headers and the data separately as you have now done.\nHTTP error 403 m...
[ 2, 0 ]
[]
[]
[ "ofx", "python", "sgml", "urllib2", "xml" ]
stackoverflow_0001656611_ofx_python_sgml_urllib2_xml.txt
Q: Python Scoping/Static Misunderstanding I'm really stuck on why the following code block 1 result in output 1 instead of output 2? Code block 1: class FruitContainer: def __init__(self,arr=[]): self.array = arr def addTo(self,something): self.array.append(something) def _...
Python Scoping/Static Misunderstanding
I'm really stuck on why the following code block 1 result in output 1 instead of output 2? Code block 1: class FruitContainer: def __init__(self,arr=[]): self.array = arr def addTo(self,something): self.array.append(something) def __str__(self): ret = "[" ...
[ "You should never use a mutable value (like []) for a default argument to a method. The value is computed once, and then used for every invocation. When you use an empty list as a default value, that same list is used every time the method is invoked without the argument, even as the value is modified by previous...
[ 8, 2, 1, 0 ]
[]
[]
[ "class", "iteration", "python", "scope", "static_members" ]
stackoverflow_0001654967_class_iteration_python_scope_static_members.txt
Q: Testing twisted application - Load client I've written a Twisted based server and I'd like to test it using twisted as well. But I'd like to write a load test starting a bunch of request at the same time. But I believe that I didn't get the concepts of Twisted, mainly client side, because I'm stucked with this pro...
Testing twisted application - Load client
I've written a Twisted based server and I'd like to test it using twisted as well. But I'd like to write a load test starting a bunch of request at the same time. But I believe that I didn't get the concepts of Twisted, mainly client side, because I'm stucked with this problem: from twisted.internet import reactor,...
[ "The direct cause for your failure is that you attemp to call run() on the reactor multiple times. You are supposed to ever only call run() once. I think you are expecting to have multiple reactors, each in its own thread, but actually you only have one. The bad thing is that having multiple reactors is difficult o...
[ 9 ]
[]
[]
[ "multithreading", "python", "twisted" ]
stackoverflow_0001654566_multithreading_python_twisted.txt
Q: how to open a URL with non utf-8 arguments Using Python I need to transfer non utf-8 encoded data (specifically shift-jis) to a URL via the query string. How should I transfer the data? Quote it? Encode in utf-8? Thanks A: Query string parameters are byte-based. Whilst IRI-to-URI and typed non-ASCII characters w...
how to open a URL with non utf-8 arguments
Using Python I need to transfer non utf-8 encoded data (specifically shift-jis) to a URL via the query string. How should I transfer the data? Quote it? Encode in utf-8? Thanks
[ "Query string parameters are byte-based. Whilst IRI-to-URI and typed non-ASCII characters will typically use UTF-8, there is nothing forcing you to send or receive your own parameters in that encoding.\nSo for Shift-JIS (actually typically cp932, the Windows extension of that encoding):\nfoo= u'\\u65E5\\u672C\\u8A9...
[ 4, 1, 0 ]
[]
[]
[ "python", "quotes", "shift_jis", "unicode", "urllib" ]
stackoverflow_0001657201_python_quotes_shift_jis_unicode_urllib.txt
Q: Help sorting: first by this, and then by that I have a list of tuples I am trying to sort and could use some help. The field I want to sort by in the tuples looks like "XXX_YYY". First, I want to group the XXX values in reverse order, and then, within those groups, I want to place the YYY values in normal sort...
Help sorting: first by this, and then by that
I have a list of tuples I am trying to sort and could use some help. The field I want to sort by in the tuples looks like "XXX_YYY". First, I want to group the XXX values in reverse order, and then, within those groups, I want to place the YYY values in normal sort order. (NOTE: I am just as happy, actually, sortin...
[ "def my_cmp(x, y):\n x1, x2 = x[0].split('_')\n y1, y2 = y[0].split('_')\n return -cmp(x1, y1) or cmp(x2, y2)\n\nmy_list = [\n (u'community_news', u'Community: News & Information'), \n (u'kf_video', u'KF: Video'), \n (u'community_video', u'Community: Video'), \n (u'kf_news', u'KF: News & Information'...
[ 10, 8, 2 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0001657242_python_sorting.txt
Q: Elegant structured text file parsing I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. I put elegant in the title as i've previously found that this type of task ...
Elegant structured text file parsing
I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain j...
[ "No and in fact, for the specific type of task you describe, I doubt there's a \"cleaner\" way to do it than regular expressions. It looks like your files have embedded line breaks so typically what we'll do here is make the line your unit of decomposition, applying per-line regexes. Meanwhile, you create a small s...
[ 12, 11, 8, 6, 5, 4, 2, 2, 0 ]
[]
[]
[ "perl", "python", "ruby", "text_parsing" ]
stackoverflow_0000223866_perl_python_ruby_text_parsing.txt
Q: Django syntax highlighting causing character escaping issues I've been working on my own django based blog (like everyone, I know) to sharpen up my python, and I thought added some syntax highlight would be pretty great. I looked at some of the snippets out there and decided to combine a few and write my own synta...
Django syntax highlighting causing character escaping issues
I've been working on my own django based blog (like everyone, I know) to sharpen up my python, and I thought added some syntax highlight would be pretty great. I looked at some of the snippets out there and decided to combine a few and write my own syntax highlighting template filter using Beautiful Soup and Pygments. ...
[ "I've finally found some time to figure it out. When beautiful soup pulls in the content and it contains a tag, the tag is listed as a sub node of a list. This line is the culprit:\nnew_content = pygments.highlight(code.contents[0], lexer, formatter)\n\nThe [0] cuts off the other part of the code, it isn't being de...
[ 1 ]
[]
[]
[ "django", "escaping", "pygments", "python" ]
stackoverflow_0001607979_django_escaping_pygments_python.txt
Q: Problems using PyQt's Resource System I am trying to use PyQt's Resource System but it appears I have no clue what I am doing! I already have to application created, along with its GUI I am just trying to import some images to use with the program. I used the QtDesigner to create the resource file and I compiled i...
Problems using PyQt's Resource System
I am trying to use PyQt's Resource System but it appears I have no clue what I am doing! I already have to application created, along with its GUI I am just trying to import some images to use with the program. I used the QtDesigner to create the resource file and I compiled it using pyrcc4.exe. But when I attempt to i...
[ "pyrcc generates Python 2.x code by default.\nTry regenerating your resource files using pyrcc with flag '-py3'\n" ]
[ 19 ]
[]
[]
[ "pyqt", "pyqt4", "python" ]
stackoverflow_0001619574_pyqt_pyqt4_python.txt
Q: Why is there a need to explicitly delete the sys.exc_info() traceback? I've seen in different code bases and just read on PyMOTW (see the first Note here). The explanation says that a cycle will be created in case the traceback is assigned to a variable from sys.exc_info()[2], but why is that? How big of a problem...
Why is there a need to explicitly delete the sys.exc_info() traceback?
I've seen in different code bases and just read on PyMOTW (see the first Note here). The explanation says that a cycle will be created in case the traceback is assigned to a variable from sys.exc_info()[2], but why is that? How big of a problem is this? Should I search for all uses of exc_info in my code base and make ...
[ "Python 3 (update to original answer):\nIn Python 3, the advice quoted in the question has been removed from the Python documentation. My original answer (which follows) applies only to versions of Python that include the quote in their documentation.\nPython 2:\nThe Python garbage collector will, eventually, find ...
[ 23, 12 ]
[]
[]
[ "python" ]
stackoverflow_0001658293_python.txt
Q: How to get the range of valid Numpy data types? I'm interested in finding for a particular Numpy type (e.g. np.int64, np.uint32, np.float32, etc.) what the range of all possible valid values is (e.g. np.int32 can store numbers up to 2**31-1). Of course, I guess one can theoretically figure this out for each type, ...
How to get the range of valid Numpy data types?
I'm interested in finding for a particular Numpy type (e.g. np.int64, np.uint32, np.float32, etc.) what the range of all possible valid values is (e.g. np.int32 can store numbers up to 2**31-1). Of course, I guess one can theoretically figure this out for each type, but is there a way to do this at run time to ensure m...
[ "Quoting from a numpy discussion list:\n\nThat information is available via numpy.finfo() and numpy.iinfo():\nIn [12]: finfo('d').max\nOut[12]: 1.7976931348623157e+308\n\nIn [13]: iinfo('i').max\nOut[13]: 2147483647\n\nIn [14]: iinfo('uint8').max\nOut[14]: 255\n\n\nLink here.\n", "You can use numpy.iinfo(arg).max...
[ 73, 59 ]
[]
[]
[ "numpy", "python", "types" ]
stackoverflow_0001658714_numpy_python_types.txt
Q: Python: how to make a function visible throughout a program I have two functions like the following: def fitnesscompare(x, y): if x.fitness>y.fitness: return 1 elif x.fitness==y.fitness: return 0 else: #x.fitness<y.fitness return -1 that are used with 'sort' to sort on dif...
Python: how to make a function visible throughout a program
I have two functions like the following: def fitnesscompare(x, y): if x.fitness>y.fitness: return 1 elif x.fitness==y.fitness: return 0 else: #x.fitness<y.fitness return -1 that are used with 'sort' to sort on different attributes of class instances. These are used from within ...
[ "The best approach (to get the visibility you ask about) is to put this def statement in a module (say fit.py), import fit from any other module that needs access to items defined in this one, and use fit.fitnesscompare in any of those modules as needed.\nWhat you ask, and what you really need, may actually be diff...
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001658722_python.txt
Q: searching within nested list in python I have a list: l = [['en', 60, 'command'],['sq', 34, 'komand']] I want to search for komand or sq and get l[1] returned. Can I somehow define my own matching function for list searches? A: An expression like: next(subl for subl in l if 'sq' in subl) will give you exactly ...
searching within nested list in python
I have a list: l = [['en', 60, 'command'],['sq', 34, 'komand']] I want to search for komand or sq and get l[1] returned. Can I somehow define my own matching function for list searches?
[ "An expression like:\nnext(subl for subl in l if 'sq' in subl)\n\nwill give you exactly the sublist you're searching for (or raise StopIteration if there is no such sublist; if the latter behavior is not what you want, pass next a second argument [[e.g, [] or None, depending on what exactly you want!]] to return in...
[ 11, 1, 0, 0 ]
[]
[]
[ "list", "nested", "python", "search" ]
stackoverflow_0001658505_list_nested_python_search.txt
Q: How can I generate a screenshot of a webpage using a server-side script? I need a server-side script (PHP, Python) to capture a webpage to a PNG, JPG, Tiff, GIF image and resize them to a thumbnail. What is the best way to accomplish this? See also: Web Page Screenshots with PHP? How can I take a screenshot of a ...
How can I generate a screenshot of a webpage using a server-side script?
I need a server-side script (PHP, Python) to capture a webpage to a PNG, JPG, Tiff, GIF image and resize them to a thumbnail. What is the best way to accomplish this? See also: Web Page Screenshots with PHP? How can I take a screenshot of a website with PHP and GD? How might I obtain a Snapshot or Thumbnail of a web ...
[ "You can probably write something similar to webkit2png, unless your server already runs Mac OS X.\nUPDATE: I just saw the link to its Linux equivalent: khtml2png\nSee also:\n\nCreate screenshots of a web page using Python and QtWebKit\nTaking automated webpage screenshots with embedded Mozilla\n\n", "What needs ...
[ 14, 7, 2, 0 ]
[]
[]
[ "php", "python", "screenshot", "server_side_scripting" ]
stackoverflow_0000713938_php_python_screenshot_server_side_scripting.txt