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: installing _imagingft Possible Duplicate: Python: The _imagingft C module is not installed It seem that some of my problems with working with fonts, are due to the luck of _imagingft module. how can I install it? what are the steps A: It's created by building PIL with the FreeType development files in place.
installing _imagingft
Possible Duplicate: Python: The _imagingft C module is not installed It seem that some of my problems with working with fonts, are due to the luck of _imagingft module. how can I install it? what are the steps
[ "It's created by building PIL with the FreeType development files in place.\n" ]
[ 0 ]
[]
[]
[ "fonts", "python" ]
stackoverflow_0002185538_fonts_python.txt
Q: Suggested GA operators for a TSP problem? I'm building a genetic algorithm to tackle the traveling salesman problem. Unfortunately, I hit peaks that can sustain for over a thousand generations before mutating out of them and getting better results. What crossover and mutation operators generally do well in this ...
Suggested GA operators for a TSP problem?
I'm building a genetic algorithm to tackle the traveling salesman problem. Unfortunately, I hit peaks that can sustain for over a thousand generations before mutating out of them and getting better results. What crossover and mutation operators generally do well in this case?
[ "Ordered mutation and ordered cross-over (see this article). Standard mutation and cross-over operations will usually result in invalid solutions (i.e. duplicate and/or missing cities in a route).\nThere was a similar question recently.\nI have a Java applet that implements the TSP using ordered cross-over and mut...
[ 3, 2, 1 ]
[]
[]
[ "algorithm", "evolutionary_algorithm", "genetic_algorithm", "python", "traveling_salesman" ]
stackoverflow_0002185177_algorithm_evolutionary_algorithm_genetic_algorithm_python_traveling_salesman.txt
Q: How to start a local port on user's computer (Edited question) sorry in the past I have not been able to formulate my question coherently. This will be my last try. =| Basically, I want to do something like this website is doing: http://www.ninjavideo.net/video/56388. They are rendering an iframe that points to a ...
How to start a local port on user's computer (Edited question)
sorry in the past I have not been able to formulate my question coherently. This will be my last try. =| Basically, I want to do something like this website is doing: http://www.ninjavideo.net/video/56388. They are rendering an iframe that points to a port on localhost. You will see nothing in the iframe if you dont ha...
[ "An Applet is basically a piece of Java code which is served by a webpage and is supposed to run at the client machine. You can learn more about Applets at Sun's own Applet tutorial. If you're green to Java as well, then I recommend to go through Trials Covering the Basics first. Opening sockets (ports) using Java ...
[ 2, 0 ]
[]
[]
[ "c", "java", "localhost", "php", "python" ]
stackoverflow_0002185823_c_java_localhost_php_python.txt
Q: Expanding elements in a list I'm looking for a "nice" way to process a list where some elements need to be expanded into more elements (only once, no expansion on the results). Standard iterative way would be to do: i=0 while i < len(l): if needs_expanding(l[i]): new_is = expand(l[i]) l[i:i] = new_i...
Expanding elements in a list
I'm looking for a "nice" way to process a list where some elements need to be expanded into more elements (only once, no expansion on the results). Standard iterative way would be to do: i=0 while i < len(l): if needs_expanding(l[i]): new_is = expand(l[i]) l[i:i] = new_is i += len(new_is) else: ...
[ "Your last two answers are what I would do. I'm not familiar with flatten() though, but if you have such a function then that looks ideal. You can also use the built-in sum():\nsum(expand(x) if needs_expanding(x) else [x] for x in l, [])\nsum(needs_expanding(x) and expand(x) or [x] for x in l, [])\n\n", "The last...
[ 3, 2, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002185822_list_python.txt
Q: Is there a Python module to access Advantage Database Server? As the title suggest, I was wondering if there is a Python module that can access an Advantage Database Server (Sybase) files such as ADT and DBF. I have searched the web and couldn't find what I'm looking for this is why I wanted to ask it here. A: I...
Is there a Python module to access Advantage Database Server?
As the title suggest, I was wondering if there is a Python module that can access an Advantage Database Server (Sybase) files such as ADT and DBF. I have searched the web and couldn't find what I'm looking for this is why I wanted to ask it here.
[ "I have used pyodbc with the Advantage ODBC driver, http://code.google.com/p/pyodbc/ and pywin32 http://sourceforge.net/projects/pywin32/ with the Advantage OLE DB provider successfully. My personal preference is the pyodbc driver.\nThere is now a native wrapper at http://code.google.com/p/adsdb/.\n", "dbfpy (a...
[ 3, 1 ]
[]
[]
[ "advantage_database_server", "database", "dbf", "module", "python" ]
stackoverflow_0001189146_advantage_database_server_database_dbf_module_python.txt
Q: Pointers to members in swig (or Boost::Python) I made some bindings from my C++ app for python. The problem is that I use pointers to members (It's for computing shortest path and giving the property to minimize as parameter). This is the C++ signature: std::vector<Path> martins(int start, int dest, MultimodalGrap...
Pointers to members in swig (or Boost::Python)
I made some bindings from my C++ app for python. The problem is that I use pointers to members (It's for computing shortest path and giving the property to minimize as parameter). This is the C++ signature: std::vector<Path> martins(int start, int dest, MultimodalGraph & g, float Edge::*) This is what I did (from what...
[ "Don't know about SWIG, but in boost::python you can write a wrapper:\nbool foo(int x, float* result);\n\nboost::python::tuple foo_wrapper(int x)\n{\n float v;\n bool result = foo(x, &v);\n return boost::python::make_tuple(result, v);\n}\n\nBOOST_PYTHON_MODULE(foomodule)\n{\n def(\"foo\", &foo_wrapper);...
[ 2 ]
[]
[]
[ "boost_python", "c++", "python", "swig" ]
stackoverflow_0001770725_boost_python_c++_python_swig.txt
Q: Google App Engine won't recognize facebook package unless I rename it I'm trying to intergrate Facebook Connect into an GAE app. I've got a basic folder structure like so: /gae-root /myapp /templates /etc app.yaml settings.py and I tried to add the PyFacebook library like so: /gae-roo...
Google App Engine won't recognize facebook package unless I rename it
I'm trying to intergrate Facebook Connect into an GAE app. I've got a basic folder structure like so: /gae-root /myapp /templates /etc app.yaml settings.py and I tried to add the PyFacebook library like so: /gae-root /myapp /templates /etc /facebook /djangof...
[ "It was a problem with an extra .pth file in my site-packages directory.\n" ]
[ 0 ]
[]
[]
[ "facebook", "google_app_engine", "python" ]
stackoverflow_0002062504_facebook_google_app_engine_python.txt
Q: wxPython GUI: migrating gnuplot to matplotlib I currently have a GUI built in wxPython with several sections, one of which displays a .png image of a plot: self.plot = wx.BitmapButton(self.pane_system, -1, wx.Bitmap("/home/myname/projects/newton/plot/src/graph.png", wx.BITMAP_TYPE_ANY)) In another part of the GUI...
wxPython GUI: migrating gnuplot to matplotlib
I currently have a GUI built in wxPython with several sections, one of which displays a .png image of a plot: self.plot = wx.BitmapButton(self.pane_system, -1, wx.Bitmap("/home/myname/projects/newton/plot/src/graph.png", wx.BITMAP_TYPE_ANY)) In another part of the GUI, there is a place where I can edit parameters. The...
[ "Taking your questions in order:\n1.) Yes matplotlib is a contained python module. It does have external dependancies but in Windows these dependencies are packaged with the matplotlib install. Do you need to worry about these when you install on other machines? That depends on how you are going to install. Are...
[ 2 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0002186240_matplotlib_python_wxpython.txt
Q: how to check if request is ajax in turbogears How do I go about checking if a request is an ajax request in a controller method in Turbogears? Further, is it possible to return a 'partial' much like in rails or symfony if the request is an ajax request. I know about the json decorator but I need a way to return a ...
how to check if request is ajax in turbogears
How do I go about checking if a request is an ajax request in a controller method in Turbogears? Further, is it possible to return a 'partial' much like in rails or symfony if the request is an ajax request. I know about the json decorator but I need a way to return a partial of a mako template (because I need to forma...
[ "jQuery, YUI, Prototype, Dojo, and MooTools all set the header X-Requested-With: XMLHttpRequest. You should be able to check for that header.\n" ]
[ 1 ]
[]
[]
[ "ajax", "mako", "python", "turbogears2" ]
stackoverflow_0002187115_ajax_mako_python_turbogears2.txt
Q: Manage Increasingly complex Django URL views efficiently? (urls.py) So, I have this Django application and I keep adding new features to provide ever more granular views of the data. To give a quick idea of the problem, here's a subset of urls.py: # Simple enough . . . (r'^$', 'index'), (r'^date/(?P<year>\d{4})$'...
Manage Increasingly complex Django URL views efficiently? (urls.py)
So, I have this Django application and I keep adding new features to provide ever more granular views of the data. To give a quick idea of the problem, here's a subset of urls.py: # Simple enough . . . (r'^$', 'index'), (r'^date/(?P<year>\d{4})$', 'index'), (r'^date/(?P<year>\d{4})-(?P<month>\d{2})$', 'index'), (r'^da...
[ "Why not use GET parameters, or django-filter, if all you do is just filter/group the results differently?\nThe reasons I see for using GET are that its easier to implement, and seems a little cleaner: in the URL solution /search/foo/user/bar/ and /user/bar/search/foo/ are 2 names for the exact same content. In the...
[ 3, 0 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0002187273_django_django_urls_python.txt
Q: Making a module global? I would like to know why >>> def func2(): ... global time ... import time ... >>> time Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'time' is not defined >>> func2() >>> time <module 'time' (built-in)> >>> works, but >>> def func(): ....
Making a module global?
I would like to know why >>> def func2(): ... global time ... import time ... >>> time Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'time' is not defined >>> func2() >>> time <module 'time' (built-in)> >>> works, but >>> def func(): ... global module ... ...
[ "Each of your exec() calls happens in a separate namespace. Abandon this path; it will only lead to ruin.\n", "Because exec uses its own scope by default. If you do exec \"global {0}; import {0}\".format(module) in globals(), then it'll work.\nYou shouldn't be doing that, unless you really need to.\n", "To impo...
[ 7, 1, 1, 0 ]
[]
[]
[ "global", "module", "python" ]
stackoverflow_0002187381_global_module_python.txt
Q: proxy-like python module Can a python module hand over other module in case of self being imported? A: You can sort of do it (in the normal CPython anyway): # uglyhack.py import sys import othermodule sys.modules[__name__]= othermodule then: >>> import uglyhack >>> uglyhack <module 'othermodule' from '...'> ...
proxy-like python module
Can a python module hand over other module in case of self being imported?
[ "You can sort of do it (in the normal CPython anyway):\n# uglyhack.py\n\nimport sys\nimport othermodule\n\nsys.modules[__name__]= othermodule\n\nthen:\n>>> import uglyhack\n>>> uglyhack\n<module 'othermodule' from '...'>\n\nThis relies on the assignment of the global for the module in the importing script/module ha...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002186977_python.txt
Q: python 2.6 cPickle.load results in EOFError I use cPickle to pickle a list of integers, using HIGHEST_PROTOCOL, cPickle.dump(l, f, HIGHEST_PROTOCOL) When I try to unpickle this using the following code, I get an EOFError. I tried 'seeking' to offset 0 before unpickling, but the error persists. l = cPickle.load(f)...
python 2.6 cPickle.load results in EOFError
I use cPickle to pickle a list of integers, using HIGHEST_PROTOCOL, cPickle.dump(l, f, HIGHEST_PROTOCOL) When I try to unpickle this using the following code, I get an EOFError. I tried 'seeking' to offset 0 before unpickling, but the error persists. l = cPickle.load(f) Any ideas?
[ "If you are on windows, make sure you \nopen(filename, 'wb') # for writing\nopen(filename, 'rb') # for reading\n\n" ]
[ 20 ]
[]
[]
[ "eoferror", "pickle", "python" ]
stackoverflow_0002187558_eoferror_pickle_python.txt
Q: How can I render a Django template that has UTF8 characters in it? I'm trying to send a django email with UTF-8 characters in the template, specifically: S'il vous plaît I get the error: UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in position 147: unexpected code byte When trying to encode the spec...
How can I render a Django template that has UTF8 characters in it?
I'm trying to send a django email with UTF-8 characters in the template, specifically: S'il vous plaît I get the error: UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in position 147: unexpected code byte When trying to encode the special "î" character (that is the character at that position.) Here is my c...
[ "The editor you're using has saved the file using Mac Roman encoding. Open the template, re-save it as UTF-8, and it should work fine.\n", "0x94 is not part of î in UTF-8. The UTF-8 encoding for î is 0xc3 0xae.\n" ]
[ 6, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002187561_django_django_templates_python.txt
Q: What's the python __all__ module level variable for? I've seen it a lot in python/Lib source code but I don't know what it is for. I thought it was used to limit accessible members of of a module. So only the elements at __all__ will show up when dir(module). I did a little example and saw it was not working as I ...
What's the python __all__ module level variable for?
I've seen it a lot in python/Lib source code but I don't know what it is for. I thought it was used to limit accessible members of of a module. So only the elements at __all__ will show up when dir(module). I did a little example and saw it was not working as I expected. So... What's the python __all__ module level var...
[ "It has two purposes:\n\nAnybody who reads the source will know what the exposed public API is. It doesn't prevent them from poking around in private declarations, but does provide a good warning not to.\nWhen using from mod import *, only names listed in __all__ will be imported. This is not as important, in my op...
[ 52, 8, 4 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0002187583_namespaces_python.txt
Q: Python Decorator 3.0 and arguments to the decorator I'm excited to see the latest version of the decorator python module (3.0). It looks a lot cleaner (e.g. the syntax is more sugary than ever) than previous iterations. However, it seems to have lousy support (e.g. "sour" syntax, to horribly stretch the metaphor)...
Python Decorator 3.0 and arguments to the decorator
I'm excited to see the latest version of the decorator python module (3.0). It looks a lot cleaner (e.g. the syntax is more sugary than ever) than previous iterations. However, it seems to have lousy support (e.g. "sour" syntax, to horribly stretch the metaphor) for decorators that take arguments themselves. Does any...
[ "In this case, you need to make your function return the decorator. (Anything can be solved by another level of indirection...)\nfrom decorator import decorator\ndef substitute_args(arg_sub_dict):\n @decorator\n def wrapper(fun, arg):\n new_arg = arg_sub_dict.get(arg, arg)\n return fun(new_arg)\n return wr...
[ 8 ]
[ "here is another way i have just discovered: check whether the first (and only) argument to your decorator is callable; if so, you are done and can return your behavior-modifying wrapper method (itself decorated with functools.wraps to preserve name and documentation string). \nin the other case, one or more named ...
[ -2 ]
[ "decorator", "python" ]
stackoverflow_0001060193_decorator_python.txt
Q: Python: how to inherit from two classes? First of all I'm a python newbie. I'm playing with Django and I'm trying to extend some classes. Now I'm in this situation: I have a new class customBaseModelAdmin(admin.options.BaseModelAdmin): #override a method of BaseModelAdmin and I want to write another class cu...
Python: how to inherit from two classes?
First of all I'm a python newbie. I'm playing with Django and I'm trying to extend some classes. Now I'm in this situation: I have a new class customBaseModelAdmin(admin.options.BaseModelAdmin): #override a method of BaseModelAdmin and I want to write another class customModelAdmin(customBaseModelAdmin): that ob...
[ "Why not just subclass ModelAdmin for customBaseModelAdmin?\n", "Just let customBaseModelAdmin inherit from ModelAdmin. You can still override the method from BaseModelAdmin.\nBut of course it could be that ModelAdmin also overrides this method. I would take a look at the source code of these classes to really kn...
[ 2, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002187899_django_python.txt
Q: Named arguments: C# vs Python Both C# and Python allow named arguments, so you can write something like: foo(bar:1). This is great, especially in combination with optional arguments. My question is: what are the differences between the C# and Python named arguments, if any? I'm not interested in which is the "best...
Named arguments: C# vs Python
Both C# and Python allow named arguments, so you can write something like: foo(bar:1). This is great, especially in combination with optional arguments. My question is: what are the differences between the C# and Python named arguments, if any? I'm not interested in which is the "best", but in whether there are differe...
[ "Python lets you \"catch\" unspecified named arguments into a dict, which is pretty handy\n>>> def f(**kw):\n... print kw\n... \n>>> f(size=3, sides=6, name=\"hexagon\")\n{'sides': 6, 'name': 'hexagon', 'size': 3}\n\n", "Python not only lets you catch unspecified named arguments into a dict, but also lets you...
[ 6, 5 ]
[]
[]
[ "c#", "keyword_argument", "python" ]
stackoverflow_0002187921_c#_keyword_argument_python.txt
Q: entropy in txt file I have a text file with numbers in it as follows: 1231313123123123 1432423432535345 3532523452345345 1231423432453455 3434535345345345 3452353453253453 all the lines are the same length, I want to calculate entropy on each line and have output as: 2.64234234 2.65464564 2.35355435 etc. Right n...
entropy in txt file
I have a text file with numbers in it as follows: 1231313123123123 1432423432535345 3532523452345345 1231423432453455 3434535345345345 3452353453253453 all the lines are the same length, I want to calculate entropy on each line and have output as: 2.64234234 2.65464564 2.35355435 etc. Right now with this piece of cod...
[ "failas = open('text.txt', 'r')\nfor row in failas:\n print H(row)\n\n", "Perhaps you meant print H(row).\n", "All of the above, plus you probably don't want to include the \\n at end of each line in the entropy calculation. Use H(row.rstrip('\\n'))\nYou can answer a lot of your own questions by examining th...
[ 10, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002185862_python.txt
Q: How can I view the contents of an array within controller directly for debugging? I'm just getting started with pylons, and am trying to figure out how to view the contents of variables for debugging without rendering the template. For example: class IndexController(BaseController): def index(self): # Retur...
How can I view the contents of an array within controller directly for debugging?
I'm just getting started with pylons, and am trying to figure out how to view the contents of variables for debugging without rendering the template. For example: class IndexController(BaseController): def index(self): # Return a rendered template #return render('/index.mako') # or, return a response ...
[ "You can use cgitb to debug web applications, it can output detailed tracebacks to files, including variables contents. Here is an article detailing how to use it.\nIf you can see the server stdout you can also simply print the variable, or else write it to a file: open(\"my-debug-log.txt\", \"w\").write(repr(varia...
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002188496_pylons_python.txt
Q: Getting invalid image error in Django, but PIL is installed and passes all tests So I've finally successfully installed PIL (after many difficulties) on RHEL5 with Django (development version) and Python 2.6 installed at /opt/python2.6. Running selftest.py shows that everything appears to be installed correctly: $...
Getting invalid image error in Django, but PIL is installed and passes all tests
So I've finally successfully installed PIL (after many difficulties) on RHEL5 with Django (development version) and Python 2.6 installed at /opt/python2.6. Running selftest.py shows that everything appears to be installed correctly: $ python2.6 selftest.py 57 tests passed. I can upload .png files and .gif files witho...
[ "See possible answer in:\nIs it possible to control which libraries apache uses?\nReferencing here so can still get bounty if awarded. :-)\n", "My impression of the PIL JPEG problem is that it's almost always a system configuration problem.\nYou built and configured PIL and tested with that version and it worked....
[ 2, 0 ]
[]
[]
[ "django", "django_models", "python", "python_imaging_library" ]
stackoverflow_0002110588_django_django_models_python_python_imaging_library.txt
Q: Integrating Python or Perl with PHP I'm going to help my friend in a improve of his phpBB board, but I want to make somethings there in Python or Perl. But it's possible to integrate these languages with PHP? A: You can always call the python or perl interpreter from within PHP! Minimalistic interchange is possi...
Integrating Python or Perl with PHP
I'm going to help my friend in a improve of his phpBB board, but I want to make somethings there in Python or Perl. But it's possible to integrate these languages with PHP?
[ "You can always call the python or perl interpreter from within PHP! Minimalistic interchange is possible by means of passing command line arguments and capturing stdout (exec or passthru are related php functions).\nHowever, I don't think its's a good idea - using two interpreters instead of one doubles the overal...
[ 8, 8, 3 ]
[]
[]
[ "integration", "perl", "php", "phpbb", "python" ]
stackoverflow_0002187998_integration_perl_php_phpbb_python.txt
Q: unicode class in Python help(unicode) prints something like: class unicode(basestring) | unicode(string [, encoding[, errors]]) -> object ... but you can use something different from a basestring as argument, you can do unicode(1) and get u'1'. What happens in that call? int don't have a __unicode__ method to b...
unicode class in Python
help(unicode) prints something like: class unicode(basestring) | unicode(string [, encoding[, errors]]) -> object ... but you can use something different from a basestring as argument, you can do unicode(1) and get u'1'. What happens in that call? int don't have a __unicode__ method to be called.
[ "Same as unicode(str(1)).\n\n>>> class thing(object):\n... def __str__(self):\n... print \"__str__ called on \" + repr(self)\n... return repr(self)\n...\n>>> a = thing()\n>>> a\n<__main__.thing object at 0x7f2f972795d0>\n>>> unicode(a)\n__str__ called on <__main__.thing object at 0x7f2f972795d0>...
[ 2, 2, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002189156_python_unicode.txt
Q: What is the elegant way to get the arguments to a playAudio call from this list I know this is the basic. I'm just wondering what is the elegant way to do it. For example: I want the the 'python01.wav' and 'py*thon' strings from this list The list is like this: [ [('name', 'entry')], [('class', 'entry')], [('type'...
What is the elegant way to get the arguments to a playAudio call from this list
I know this is the basic. I'm just wondering what is the elegant way to do it. For example: I want the the 'python01.wav' and 'py*thon' strings from this list The list is like this: [ [('name', 'entry')], [('class', 'entry')], [('type', 'text/javascript'), ('src', '/term_added.php?hw=python')], [('type', 'text/javascri...
[ "Perhaps not the greatest solution, but appears to do what you want:\nl = [huge list from your example]\nfor e in l: # for each list\n for t in e: # for each tuple\n for s in t: # each string\n if 'playAudio' in s:\n args = s[9:].split(',') #skip 'playAudio' split on comma\n ...
[ 2, 1 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0002189259_list_python_string.txt
Q: performance issue when import reactor module before os.fork() i got a performance issue when trying to do: from twisted.internet import reactor #some codes here pid = os.fork() if not pid: #some codes blahblahblah reactor.run() this caused very low performance and i didn't find useful informations from th...
performance issue when import reactor module before os.fork()
i got a performance issue when trying to do: from twisted.internet import reactor #some codes here pid = os.fork() if not pid: #some codes blahblahblah reactor.run() this caused very low performance and i didn't find useful informations from the official documentation, i believe it because i import reactor mod...
[ "Can't you use subprocess instead of os.fork?\n" ]
[ 0 ]
[]
[]
[ "performance", "python", "twisted" ]
stackoverflow_0002189332_performance_python_twisted.txt
Q: Django ORM's "related data" loading behavior In LINQ (I come from a C# background), you can manually load data for related tables via the Include("xxx") method from a in ctx.MainTable.Include("SubTable") select a; In the above code, every instance of MainTable is loaded and all the data for MainTable.SubTable is...
Django ORM's "related data" loading behavior
In LINQ (I come from a C# background), you can manually load data for related tables via the Include("xxx") method from a in ctx.MainTable.Include("SubTable") select a; In the above code, every instance of MainTable is loaded and all the data for MainTable.SubTable is also loaded. If "Include" is not called, every re...
[ "See this:\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#id4\nYou create a select_related query set to follow relationships and pre-fetch related rows.\nNormally, you don't waste much time doing this until you know that the individual fetches done automagically by the ORM are too slow.\nWhen you simpl...
[ 4 ]
[]
[]
[ "django", "django_models", "linq", "linq_to_sql", "python" ]
stackoverflow_0002189122_django_django_models_linq_linq_to_sql_python.txt
Q: What are the advantages, if any, to using mako's or pylon's form handlers instead of coding the form manually? Trying to decide if I should be using mako to handle the forms in my application or not. Thanks for the input. A: It'll save you a lot of time (even if you use them just during development) to use Pylo...
What are the advantages, if any, to using mako's or pylon's form handlers instead of coding the form manually?
Trying to decide if I should be using mako to handle the forms in my application or not. Thanks for the input.
[ "It'll save you a lot of time (even if you use them just during development) to use Pylons built-in form handling. Later if you want to strip them out and hard code a full form for each page, you can but I'd use the built-in one and find ways to customize within it before going completely manual about it.\n" ]
[ 1 ]
[]
[]
[ "mako", "pylons", "python" ]
stackoverflow_0002189432_mako_pylons_python.txt
Q: Writing good tests for Django applications I've never written any tests in my life, but I'd like to start writing tests for my Django projects. I've read some articles about tests and decided to try to write some tests for an extremely simple Django app or a start. The app has two views (a list view, and a detail ...
Writing good tests for Django applications
I've never written any tests in my life, but I'd like to start writing tests for my Django projects. I've read some articles about tests and decided to try to write some tests for an extremely simple Django app or a start. The app has two views (a list view, and a detail view) and a model with four fields: class News(m...
[ "I am not perfect in testing but a few thoughts:\n\nBasically you should test every function, method, class, whatever, that you have written by yourself.\n\nThis implies that you don't have to test functions, classes, etc. which the framework provides. \nThat said, a quick check of your test functions:\n\ntest_deta...
[ 18, 6 ]
[]
[]
[ "django", "django_testing", "python", "unit_testing" ]
stackoverflow_0002188551_django_django_testing_python_unit_testing.txt
Q: What is a good (fastest, least broken, etc) way to implement JSON in Python? There seems to be a handful of JSON libraries out there for Python even though Python has a built-in library. One even claims to be built according to http://www.json.org spec (which caused me to think 'hmmm, is Python's built in library ...
What is a good (fastest, least broken, etc) way to implement JSON in Python?
There seems to be a handful of JSON libraries out there for Python even though Python has a built-in library. One even claims to be built according to http://www.json.org spec (which caused me to think 'hmmm, is Python's built in library not built fully to spec?', so I find myself here to ask what others have found whe...
[ "The built in library is fine most of the time although occasionally you can get issues to do with character encoding.\nThere is cjson if you have performance issues to deal with.\nPersonally, I just use simplejson - for no particular reason.\n", "Python < 2.6 did not include json module. The presence of multiple...
[ 3, 3, 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0002189471_json_python.txt
Q: What do I do with a Concrete Syntax Tree? I'm using pyPEG to create a parse tree for a simple grammar. The tree is represented using lists and tuples. Here's an example: [('command', [('directives', [('directive', [('name', 'retrieve')]), ('directive', [('name', 'commit')])]), ('filename'...
What do I do with a Concrete Syntax Tree?
I'm using pyPEG to create a parse tree for a simple grammar. The tree is represented using lists and tuples. Here's an example: [('command', [('directives', [('directive', [('name', 'retrieve')]), ('directive', [('name', 'commit')])]), ('filename', [('name', 'f30502')])])] My question is ...
[ "CSTs (concrete syntax trees) are quite hard to work with for some reasons. Therefore they're commonly converted to ASTs (abstract syntax tree) for further processing (details in the same article). For instance, the Python compiler (the component that turns Python source code into Python VM bytecode) translates CST...
[ 4 ]
[]
[]
[ "concrete_syntax_tree", "parsing", "python" ]
stackoverflow_0002189330_concrete_syntax_tree_parsing_python.txt
Q: How do I reply to an email using the Python imaplib and include the original message? I'm currently using imaplib to fetch email messages from a server and process the contents and attachments. I'd like to reply to the messages with a status/error message and links to the resulting generated content on my site if ...
How do I reply to an email using the Python imaplib and include the original message?
I'm currently using imaplib to fetch email messages from a server and process the contents and attachments. I'd like to reply to the messages with a status/error message and links to the resulting generated content on my site if they can be processed. This should include the original message but should drop any attach...
[ "The original MIME tree structure of the incoming message is as follows (using email.iterators._structure(msg)):\nmultipart/mixed\n text/html (message)\n application/octet-stream (attachment 1)\n application/octet-stream (attachment 2)\n\nReplying via GMail results in the following structure...
[ 22 ]
[]
[]
[ "django", "email", "imaplib", "mime", "python" ]
stackoverflow_0002182196_django_email_imaplib_mime_python.txt
Q: getting the id of a created record in SQLAlchemy How can I get the id of the created record in SQLAlchemy? I'm doing: engine.execute("insert into users values (1,'john')") A: When you execute a plain text statement, you're at the mercy of the DBAPI you're using as to whether or not the new PK value is availabl...
getting the id of a created record in SQLAlchemy
How can I get the id of the created record in SQLAlchemy? I'm doing: engine.execute("insert into users values (1,'john')")
[ "When you execute a plain text statement, you're at the mercy of the DBAPI you're using as to whether or not the new PK value is available and via what means. With SQlite and MySQL DBAPIs you'll have it as result.lastrowid, which just gives you the value of .lastrowid for the cursor. With PG, Oracle, etc., ther...
[ 14, 3 ]
[]
[]
[ "insert", "python", "sqlalchemy" ]
stackoverflow_0002188844_insert_python_sqlalchemy.txt
Q: Making wxPython GUI launch on a different screen from Eclipse I currently have a dual-monitor setup with Eclipse on monitor 2. When I run the code that launches the wxPython GUI, I would like for this GUI to appear on monitor 1. Currently, the GUI consistently appears on monitor 2, covering Eclipse, and I have to ...
Making wxPython GUI launch on a different screen from Eclipse
I currently have a dual-monitor setup with Eclipse on monitor 2. When I run the code that launches the wxPython GUI, I would like for this GUI to appear on monitor 1. Currently, the GUI consistently appears on monitor 2, covering Eclipse, and I have to drag it to monitor 1 every time. Is there a solution to this proble...
[ "I'm not entirely sure, but I think I remember reading something about windows sticking to the same monitor as the process that spawned them. Therefore, it might be a worthwhile experiment to edit your code in eclipse (on monitor 2) and have a command prompt window open on monitor 1 from which you can run the pytho...
[ 1, 0, 0 ]
[]
[]
[ "eclipse", "python", "wxpython" ]
stackoverflow_0002174904_eclipse_python_wxpython.txt
Q: What is the python equivalent of the Perl pattern to track if something has already been seen? In Perl, one can do the following for (@foo) { # do something next if $seen{$_}++; } I would like to be able to do the equivalent in Python, that is to skip a block if it has been executed once. A: seen = se...
What is the python equivalent of the Perl pattern to track if something has already been seen?
In Perl, one can do the following for (@foo) { # do something next if $seen{$_}++; } I would like to be able to do the equivalent in Python, that is to skip a block if it has been executed once.
[ "seen = set()\nfor x in foo:\n if x in seen:\n continue\n seen.add(x)\n # do something\n\nSee the set documentation for more information.\nAlso, the examples at the bottom of the itertools module documentation contains a unique_everseen generator that you can use like this:\nfor x in unique_everseen...
[ 11, 1, 1 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0002188863_perl_python.txt
Q: python normalized path gets reset in a for loop I am trying to get a normalized path on windows. The paths are stored in a list and i am looping over those as follows: >>> lst = ['C:\\', 'C:\\Windows', 'C:\\Program Files'] >>> lst ['C:\\', 'C:\\Windows', 'C:\\Program Files'] >>> for pth in lst: ... print pth .....
python normalized path gets reset in a for loop
I am trying to get a normalized path on windows. The paths are stored in a list and i am looping over those as follows: >>> lst = ['C:\\', 'C:\\Windows', 'C:\\Program Files'] >>> lst ['C:\\', 'C:\\Windows', 'C:\\Program Files'] >>> for pth in lst: ... print pth ... C:\ C:\Windows C:\Program Files Notice that it has...
[ "The double slash is simply string escaping - you need to escape slashes in string literals. Printing lst[0] before the loop will print it without the slash. If you want to really include a double slash in your literal, use the raw string syntax:\n>>> lst = ['C:\\\\', 'C:\\\\Windows', 'C:\\\\Program Files']\n>>> ls...
[ 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002189863_python_string.txt
Q: Algorithm to detect similar documents in python script I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and Ger...
Algorithm to detect similar documents in python script
I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplis...
[ "Bayesian filters have exactly this purpose. That's the techno you'll find in most tools that identify spam.\nExample, to detect a language (from http://sebsauvage.net/python/snyppets/#bayesian) :\nfrom reverend.thomas import Bayes\nguesser = Bayes()\nguesser.train('french','La souris est rentrée dans son trou.')\n...
[ 20, 10, 8, 7, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "algorithm", "diff", "python" ]
stackoverflow_0000101569_algorithm_diff_python.txt
Q: Execution of python scripts like udev/rules.d, cron.d or /apt/source.d I use python to patch system settings of linux systems distributed with partimage. I want to have the following python script structure: /patch.d/ 10_patch_netwok.py 20_patch_hostname.py ... 50_patch_software_xyz.py InitSystem...
Execution of python scripts like udev/rules.d, cron.d or /apt/source.d
I use python to patch system settings of linux systems distributed with partimage. I want to have the following python script structure: /patch.d/ 10_patch_netwok.py 20_patch_hostname.py ... 50_patch_software_xyz.py InitSystem.py The InitSytem.py should run the python scripts in /patch.d folder. Foll...
[ "Python scripts are also python modules, so the best way to load and run them is to simply import them using\n__import__('some_module')\n\nThis will mean that they run in the same process though. If this is undesirable, then your options would be to use the multi-threading or multi-processing support in python to r...
[ 1 ]
[]
[]
[ "python", "sysadmin" ]
stackoverflow_0002190509_python_sysadmin.txt
Q: Multiple Try-Excepts followed by an Else in python Is there some way to have several consecutive Try-Except clauses that trigger a single Else only if all of them are successful? As an example: try: private.anodization_voltage_meter = Voltmeter(voltage_meter_address.value) #assign voltmeter location except(vi...
Multiple Try-Excepts followed by an Else in python
Is there some way to have several consecutive Try-Except clauses that trigger a single Else only if all of them are successful? As an example: try: private.anodization_voltage_meter = Voltmeter(voltage_meter_address.value) #assign voltmeter location except(visa.VisaIOError): #channel time out private.logger.wa...
[ "Consider breaking the try/except structure into a function that returns True if the call worked and False if it failed, then use e.g. all() to see that they all succeded:\ndef initfunc(structure, attrname, address, desc):\n try:\n var = Voltmeter(address.value)\n setattr(structure, attrname, var)\n retur...
[ 6, 6, 6, 3, 2 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0002188754_exception_handling_python.txt
Q: Rebuilding PIL with FreeType Previously I got a suggedtion to Install the FreeType dev files and rebuild PIL again. but I have no idea how to do it. any help will be thanked for A: You do it exactly the same way as you did before, but now with the FreeType-dev files installed.
Rebuilding PIL with FreeType
Previously I got a suggedtion to Install the FreeType dev files and rebuild PIL again. but I have no idea how to do it. any help will be thanked for
[ "You do it exactly the same way as you did before, but now with the FreeType-dev files installed.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002190711_python.txt
Q: Python: convert script from procedural to OOP style I wrote this simple Munin plugin to graph average fan speed and I want to redo it to OOP - strictly as a learning exercise. Don't have a clue where to start though. Anyone feel like offering some guidance or even an example of what this script should look like wh...
Python: convert script from procedural to OOP style
I wrote this simple Munin plugin to graph average fan speed and I want to redo it to OOP - strictly as a learning exercise. Don't have a clue where to start though. Anyone feel like offering some guidance or even an example of what this script should look like when done. I will use it to redo some other scripts into an...
[ "You remake it in OOP by identifying code and data that goes together. These you then merge into \"classes\".\nYou actual data above seems to be the output of a process.\nThe code is iterating over it. I guess you can make a class out of that if you want to, but it's a bit silly. :)\nSo, something like this (obviou...
[ 3 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002190880_oop_python.txt
Q: how to correct the misencoded string? i used mutagen to read the mp3 metadata, since the id3 tag is read in as unicode but in fact it is GBK encoded. how to correct this in python? audio = EasyID3(name) title = audio["title"][0] print title print repr(title) produces µ±Äã¹Âµ¥Äã»áÏëÆðË­ u'\xb5\xb1\xc4\xe3\xb9\xc2...
how to correct the misencoded string?
i used mutagen to read the mp3 metadata, since the id3 tag is read in as unicode but in fact it is GBK encoded. how to correct this in python? audio = EasyID3(name) title = audio["title"][0] print title print repr(title) produces µ±Äã¹Âµ¥Äã»áÏëÆðË­ u'\xb5\xb1\xc4\xe3\xb9\xc2\xb5\xa5\xc4\xe3\xbb\xe1\xcf\xeb\xc6\xf0\xc...
[ "It looks like the string has been decoded to unicode using the wrong encoding (latin-1).\nYou need to encode it to a byte string and then decode it back to unicode using the correct encoding.\ntitle = u'\\xb5\\xb1\\xc4\\xe3\\xb9\\xc2\\xb5\\xa5\\xc4\\xe3\\xbb\\xe1\\xcf\\xeb\\xc6\\xf0\\xcb\\xad'\nprint title.encode(...
[ 4, 2 ]
[]
[]
[ "encoding", "mp3", "mutagen", "python" ]
stackoverflow_0002190904_encoding_mp3_mutagen_python.txt
Q: Jquery and Django multiple checkbox I am a beginner in jquery so please bear with me. I have a jquery function that allows me to select multiple checkboxes and create a string as follows: function getSelectedVals(){ var tmp =[]; $("input[name='checks']").each(function() { if ($(this).attr('checked')...
Jquery and Django multiple checkbox
I am a beginner in jquery so please bear with me. I have a jquery function that allows me to select multiple checkboxes and create a string as follows: function getSelectedVals(){ var tmp =[]; $("input[name='checks']").each(function() { if ($(this).attr('checked')) { checked = ($(this).val()...
[ "From what I see, you do it the way around. You should set the same name on all checkboxes. I don't know why do you send it by GET, I'd suggest sending it by POST.\n<input type=\"checkbox\" name=\"vehicle\" value=\"Bike\" />\n<input type=\"checkbox\" name=\"vehicle\" value=\"Car\" />\n<input type=\"checkbox\" name=...
[ 9, 2 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0002190998_django_jquery_python.txt
Q: Using if-condition to check filename I'm doing a real silly mistake in Python but unable to find what it is I'm doing something like this in python filename="file1" if name == 'file1' print 1 I'm getting an invalid syntax error A: You are missing a colon filename="file1" if name == 'file1': print 1 A: ...
Using if-condition to check filename
I'm doing a real silly mistake in Python but unable to find what it is I'm doing something like this in python filename="file1" if name == 'file1' print 1 I'm getting an invalid syntax error
[ "You are missing a colon\nfilename=\"file1\"\nif name == 'file1':\n print 1\n\n", "You need to put a colon at the end of the if statment\nfilename=\"file1\"\nif name == 'file1':\n print 1\n\n", "what is name?? did you define it elsewhere?? I assume its \"filename\" instead, so\nfilename=\"file1\"\nif file...
[ 7, 4, 1 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0002191262_python_syntax_error.txt
Q: None in boost.python I am trying to translate the following code d = {} d[0] = None into C++ with boost.python boost::python::dict d; d[0] = ?None How can I get a None object in boost.python? A: There is no constructor of boost::python::object that takes a PyObject* (from my understanding, a ctor like that wo...
None in boost.python
I am trying to translate the following code d = {} d[0] = None into C++ with boost.python boost::python::dict d; d[0] = ?None How can I get a None object in boost.python?
[ "There is no constructor of boost::python::object that takes a PyObject* (from my understanding, a ctor like that would invalidate the whole idea if mapping Python types to C++ types anyway, because the PyObject* could be anything). According to the documentation:\n\nobject();\nEffects: Constructs an object managin...
[ 26, 3 ]
[]
[]
[ "boost", "c++", "python" ]
stackoverflow_0002190349_boost_c++_python.txt
Q: Python Creating Unwanted Folder in Directory Python is creating a folder in my directory every time I call this method. The method is in one of my Django applications that requires access to the server's local area. def filepath(filename, foldername='', envar='MYAPPDIR'): if envar is not None and envar is os...
Python Creating Unwanted Folder in Directory
Python is creating a folder in my directory every time I call this method. The method is in one of my Django applications that requires access to the server's local area. def filepath(filename, foldername='', envar='MYAPPDIR'): if envar is not None and envar is os.environ: dirpath = os.environ[envar] ...
[ "def filepath(filename, foldername=None, envar='MYAPPDIR'):\n default = '~/myFolder'\n if foldername:\n default = os.path.join(default, foldername)\n dirpath = os.path.expanduser(os.environ.get(envar, default))\n\n try:\n os.makedirs(dirpath)\n except OSError as e:\n if e.errno != errno.EEXIST:\n ...
[ 3, 0 ]
[]
[]
[ "file_access", "python" ]
stackoverflow_0002191402_file_access_python.txt
Q: How to match info from a string I have a string which has a version number. I want to read the version number from this code so I can compare it with other code I am using. I have code done below but cannot get it working, can anyone see the problem? print results r = re.compile(r'(version\s*\s*)(\S+)') ...
How to match info from a string
I have a string which has a version number. I want to read the version number from this code so I can compare it with other code I am using. I have code done below but cannot get it working, can anyone see the problem? print results r = re.compile(r'(version\s*\s*)(\S+)') for l in results: m1 = r.ma...
[ "Why regexp? I should use split(' ') and use value next to 'version', or simplier:\nprint results.split(' ')[5]\n\nIf you must use regexp then try:\nrx = re.compile('version\\s+([\\d.]+)\\s+')\nrxx = rx.search(results)\nif rxx:\n print rxx.group(1)\n\n", "here's a non regex way\n>>> s=\"Name Info Type Call ver...
[ 3, 2, 2, 0, 0, 0 ]
[]
[]
[ "python", "search", "string" ]
stackoverflow_0002191202_python_search_string.txt
Q: How can I load test data into AppEngine automatically? I'd like to automatically load some test data into the AppEngine datastore when a local copy is run by one of my team's developers. I know that the bulk uploader lets you do this from the command line, but I'm looking for something automatic. Inevitably we wil...
How can I load test data into AppEngine automatically?
I'd like to automatically load some test data into the AppEngine datastore when a local copy is run by one of my team's developers. I know that the bulk uploader lets you do this from the command line, but I'm looking for something automatic. Inevitably we will forget to load data when we clear our test copies of the d...
[ "Why not just automate the bulk loader? It's a command line tool, as you point out, so trivial to run from your build process (or whatever other trigger you want).\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0002190622_google_app_engine_python_web_applications.txt
Q: Python: feedback / corrections on first OOP style script I would like some feedback on my first Python script that makes use of OOP style. This is a Munin plugin that graphs average fan speed or average chassis temp depending on the name of the plugin (dell_fans, dell_temps). An hour or so ago I submitted a proced...
Python: feedback / corrections on first OOP style script
I would like some feedback on my first Python script that makes use of OOP style. This is a Munin plugin that graphs average fan speed or average chassis temp depending on the name of the plugin (dell_fans, dell_temps). An hour or so ago I submitted a procedural version of the fan speed plugin to stackoverflow to get h...
[ "Is Temps a FanSpeed? That's the litmus test for whether subclassing is appropriate (e.g. an elephant is an animal, a car is not an animal - so it might be appropriate to have a subclass of Animal which models an elephant, but not a subclass of Animal which models a car).\nIt sounds like they're modelling two diffe...
[ 2, 1, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002191639_oop_python.txt
Q: Verify if provided string corresponds to pattern on python could you please advice how to verify in python if provided string correspond to provided pattern and return result. For example the provided pattern is following: < [prefix]-[id]> separated by ','>|< log >" where prefix is any number of alphabetic charact...
Verify if provided string corresponds to pattern on python
could you please advice how to verify in python if provided string correspond to provided pattern and return result. For example the provided pattern is following: < [prefix]-[id]> separated by ','>|< log >" where prefix is any number of alphabetic characters, id is only numbers but not exceeding 5 digits, log is any n...
[ "(?:[a-z]+-\\d{1,5})(?:, [a-z]+-\\d{1,5})*\\|.*\n\nit's not clear what you want to capture, that's why I use non-capturing groups. If you need only boolean:\n>>> regex = '[a-z]+-\\d{1,5}(?:, [a-z]+-\\d{1,5})*\\|.*'\n>>> re.match(regex, 'proj-234, proj-345|log message') is not None\nTrue\n\nOf course, the same resul...
[ 2, 0, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0002191581_python_regex_string.txt
Q: How to get a reference to the current class from class body? I want to keep a dictionary of (all, non-immediate included) subclasses in a base class, so that I can instantiate them from a string. I'm doing this because the CLSID is sent through a web form, so I want to restrict the choices to the ones set from the...
How to get a reference to the current class from class body?
I want to keep a dictionary of (all, non-immediate included) subclasses in a base class, so that I can instantiate them from a string. I'm doing this because the CLSID is sent through a web form, so I want to restrict the choices to the ones set from the subclasses. (I don't want to eval()/globals() the classname). cl...
[ "Irrevocably tying this with the base class:\nclass AutoRegister(type):\n def __new__(mcs, name, bases, D):\n self = type.__new__(mcs, name, bases, D)\n if \"ID\" in D: # only register if has ID attribute directly\n if self.ID in self._by_id:\n raise ValueError(\"duplicate ID: %r\" % self.ID)\n ...
[ 7, 3 ]
[]
[]
[ "class", "inheritance", "python" ]
stackoverflow_0002191505_class_inheritance_python.txt
Q: Conditional operator in Python? do you know if Python supports some keyword or expression like in C++ to return values based on if condition, all in the same line (The C++ if expressed with the question mark ?) // C++ value = ( a > 10 ? b : c ) A: value = b if a > 10 else c For Python 2.4 and lower you would ha...
Conditional operator in Python?
do you know if Python supports some keyword or expression like in C++ to return values based on if condition, all in the same line (The C++ if expressed with the question mark ?) // C++ value = ( a > 10 ? b : c )
[ "value = b if a > 10 else c\n\nFor Python 2.4 and lower you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:\nvalue = [c, b][a > 10]\n\nThere's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behav...
[ 192, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002191890_python_syntax.txt
Q: jquery autocomplete tagging Can any one tell me how to use tagging auto-complete in django templates? I have done this in django admin interface but i am confused to how to do it in the template. Thanks in advance A: In my template i have this code: $(document).ready(function(){ $("#tags1").autocomplete("/tagl...
jquery autocomplete tagging
Can any one tell me how to use tagging auto-complete in django templates? I have done this in django admin interface but i am confused to how to do it in the template. Thanks in advance
[ "In my template i have this code:\n$(document).ready(function(){\n $(\"#tags1\").autocomplete(\"/taglookup/\", {\n width: 320,\n multiple: true,\n multipleSeparator: \" \"\n });\n }\n\nand on my url.py i have this on the urlparttern tuple, it can be anything depending on how you want...
[ 2, 2, 1 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0002191116_django_jquery_python.txt
Q: Using Jython with Django? I am planning to use Jython with Django. I want to know how stable the Jython project is, how easy to use it is, and how large its developer community is. A: Django is proven to work with Jython: Special focus in Jython 2.5 was to make it compatible with modern web frameworks like Djan...
Using Jython with Django?
I am planning to use Jython with Django. I want to know how stable the Jython project is, how easy to use it is, and how large its developer community is.
[ "Django is proven to work with Jython:\n\nSpecial focus in Jython 2.5 was to make it compatible with modern web frameworks like Django\nThere is also a special project, django-jython, that focuses on making database backends and extensions available for Jython development.\nThere is explicit documentation on how to...
[ 5, 3, 2 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0002179395_jython_python.txt
Q: Python: convert RTF file to unicode? I'm trying to convert lines in an RTF file to a series of unicode strings, and then do a regex match on the lines. (I need them to be unicode so that I can output them to another file.) However, my regex match isn't working - I think because they aren't being converted into uni...
Python: convert RTF file to unicode?
I'm trying to convert lines in an RTF file to a series of unicode strings, and then do a regex match on the lines. (I need them to be unicode so that I can output them to another file.) However, my regex match isn't working - I think because they aren't being converted into unicode properly. Here's my code: usefulLines...
[ "You did not even decode the RTF file. RTFs are not just simple text files. A file containing \"äöü\", for example, contains this:\n\n{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1031{\\fonttbl{\\f0\\fswiss\\fcharset0 Arial;}}\n{*\\generator Msftedit 5.41.15.1507;}\\viewkind4\\uc1\\pard\\f0\\fs20\\'e4\\'f6\\'fc\\par\n...
[ 4 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002192319_python_unicode.txt
Q: install ImageUtils python I am trying to install ImageUtils, I found the package but it doesn't have an installer with it. what is the procedure? A: The general approach to installing Python packages is to use easy_install, or pip; the choice between the two tends to get political, so I will just say I use pip. ...
install ImageUtils python
I am trying to install ImageUtils, I found the package but it doesn't have an installer with it. what is the procedure?
[ "The general approach to installing Python packages is to use easy_install, or pip; the choice between the two tends to get political, so I will just say I use pip. pip plays well with virtualenv, which is a tool that makes it much nicer to explore arbitrary Python packages.\nIn your case, (assuming you have instal...
[ 0 ]
[]
[]
[ "image", "python" ]
stackoverflow_0002192373_image_python.txt
Q: Preventing an Active Directory user from changing his/her password using DirectoryServices When creating Active Directory users from a script, I also need to set the option that they can't change their passwords. Via the administrative GUI this is easily accomplished, by checking "User cannot change password". Pro...
Preventing an Active Directory user from changing his/her password using DirectoryServices
When creating Active Directory users from a script, I also need to set the option that they can't change their passwords. Via the administrative GUI this is easily accomplished, by checking "User cannot change password". Programmatically however, it's another story. I've found a recipe which involves interacting with t...
[ "If you can use .NET 3.5 there's a new namespace in there called System.DirectoryServices.AccountManagment. The UserPrincipal class in that namespace will allow you to set \"Cannot Change Password\" simply by setting the boolean UserCannotChangePassword property to false.\n" ]
[ 0 ]
[]
[]
[ ".net", "active_directory", "python" ]
stackoverflow_0002191969_.net_active_directory_python.txt
Q: How can I capture iSight frames with Python in Snow Leopard? I have the following PyObjC script: from Foundation import NSObject import QTKit error = None capture_session = QTKit.QTCaptureSession.alloc().init() print 'capture_session', capture_session device = QTKit.QTCaptureDevice.defaultInputDeviceWithMediaType_...
How can I capture iSight frames with Python in Snow Leopard?
I have the following PyObjC script: from Foundation import NSObject import QTKit error = None capture_session = QTKit.QTCaptureSession.alloc().init() print 'capture_session', capture_session device = QTKit.QTCaptureDevice.defaultInputDeviceWithMediaType_(QTKit.QTMediaTypeVideo) print 'device', device, type(device) succ...
[ "Your problem here is that you don't have an event loop. If you want to do this as a standalone script, you'll have to figure out how to create one. The PyObjC XCode templates automatically set that up for you with:\nfrom PyObjCTools import AppHelper\nAppHelper.runEventLoop()\n\nTrying to insert that at the top of ...
[ 3, 2 ]
[]
[]
[ "isight", "osx_snow_leopard", "pyobjc", "python", "qtkit" ]
stackoverflow_0001576593_isight_osx_snow_leopard_pyobjc_python_qtkit.txt
Q: How do Python's class closures work? If I make a class against a local namespace, how exactly does it work? For instance: >>> def foo(): ... i = 1 ... class bar(object): ... j = i ... return bar ... >>> dis(foo) 2 0 LOAD_CONST 1 (1) 3 STORE_DEREF ...
How do Python's class closures work?
If I make a class against a local namespace, how exactly does it work? For instance: >>> def foo(): ... i = 1 ... class bar(object): ... j = i ... return bar ... >>> dis(foo) 2 0 LOAD_CONST 1 (1) 3 STORE_DEREF 0 (i) 3 6 LOAD_CON...
[ "The whole class body, i.e.\nj = i\n\nis a code object, which gets loaded at offset 21 and then invoked at offset 27 via CALL_FUNCTION. The result of the invocation (the local namespace) is then used together with the class name and the bases to create the class. BUILD_CLASS takes three arguments, similar to the ty...
[ 2 ]
[]
[]
[ "bytecode", "closures", "python" ]
stackoverflow_0002192822_bytecode_closures_python.txt
Q: Python: urllib2.urlopen(url, data) Why do you have to urllib.urlencode() the data? I thought that a post sent all the information in HTTP headers when you used post (I'm not well informed on this subject obviously), so I'm confused why you have to urlencode() the data to a key=value&key2=value2 format. How does th...
Python: urllib2.urlopen(url, data) Why do you have to urllib.urlencode() the data?
I thought that a post sent all the information in HTTP headers when you used post (I'm not well informed on this subject obviously), so I'm confused why you have to urlencode() the data to a key=value&key2=value2 format. How does that formatting come into play when using POST?: # Fail data = {'name': 'John Smith'} urll...
[ "It is related to the \"Content-Type\" header: the client must have an idea of how the POST data is encoded or else how would it know how to decode it?\nThe standard way of doing this is through application/x-www-form-urlencoded encoding format.\nNow, if the question is \"why do we need to encode?\", the answer is ...
[ 9, 2 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0002192987_python_urllib_urllib2.txt
Q: Creating a video file from a group of PGM files in python My python program generates a collection of binary files. I create pgm (portable bitmap files) using this binary data. I would like to create a video using each of the pgm files as a frame in my video. I have had a look an mencoder but I dont think it supp...
Creating a video file from a group of PGM files in python
My python program generates a collection of binary files. I create pgm (portable bitmap files) using this binary data. I would like to create a video using each of the pgm files as a frame in my video. I have had a look an mencoder but I dont think it supports pgm files Can anyone offer any advice.
[ "If \"PGM\" is identical with \"Portable GrayMap Files\", cross-browser command line video processing tool ffmpeg can decode them: List of FFMPeg Codecs on Wikipedia\nCheck out the FFMPEG FAQ: 3.2 How do I encode single pictures into movies?\nOn how to use FFMpeg with Python, check this SO question. There is a wrap...
[ 1 ]
[]
[]
[ "pgm", "python" ]
stackoverflow_0002193192_pgm_python.txt
Q: How to initialize a QT thread in python As per examples seen online, I've created a Worker thread. I'm looking for a thread to run my GUI while one thread executes my code. Worker thread is defined as: class Worker(QThread): def __init__(self, parent = None): QThread.__init__(self, parent) s...
How to initialize a QT thread in python
As per examples seen online, I've created a Worker thread. I'm looking for a thread to run my GUI while one thread executes my code. Worker thread is defined as: class Worker(QThread): def __init__(self, parent = None): QThread.__init__(self, parent) self.exiting = False self.size = QSize...
[ "I imagine you're looking at the example here? But that example does \"do something with that thread afterwards\" -- it hooks up methods to respond to the signals the thread sends when it starts and finishes, in the class Worker it defines a run method that draws random stars , etc etc. Not sure what you think is ...
[ 2 ]
[]
[]
[ "multithreading", "pyqt", "python", "qt" ]
stackoverflow_0002193182_multithreading_pyqt_python_qt.txt
Q: Why am I leaking memory with this python loop? I am writing a custom file system crawler, which gets passed millions of globs to process through sys.stdin. I'm finding that when running the script, its memory usage increases massively over time and the whole thing crawls practically to a halt. I've written a minim...
Why am I leaking memory with this python loop?
I am writing a custom file system crawler, which gets passed millions of globs to process through sys.stdin. I'm finding that when running the script, its memory usage increases massively over time and the whole thing crawls practically to a halt. I've written a minimal case below which shows the problem. Am I doing so...
[ "I tracked this down to the fnmatch module. glob.glob calls fnmatch to actually perform the globbing, and fnmatch has a cache of regular expressions which is never cleared. So in this usage, the cache was growing continuously and unchecked. I've filed a bug against the fnmatch library [1].\n[1]: http://bugs.python....
[ 7, 2 ]
[]
[]
[ "glob", "memory", "memory_leaks", "python" ]
stackoverflow_0002184063_glob_memory_memory_leaks_python.txt
Q: Django admin authentication failure logging into django admin fails when 'log in' button is pressed first time, but pressing "back" and "log in' again - logs the user in successfully. I am deploying Django app with zc.buildout here, with a setup similar to what is described here http://www.meppum.com/2009/jan/17/i...
Django admin authentication failure
logging into django admin fails when 'log in' button is pressed first time, but pressing "back" and "log in' again - logs the user in successfully. I am deploying Django app with zc.buildout here, with a setup similar to what is described here http://www.meppum.com/2009/jan/17/installing-django-ubuntu-intrepid/. Nginx ...
[ "Your settings are incorrect. Django believes that it runs on port 80. Look at this line in the first HTTP response:\nLocation: http://127.0.0.1/admin/\n\nUnfortunately, I can't understand right now why this happens. I prefer just to step throught the relevant Django code with a debugger in such cases.\n", "@Euge...
[ 1, 1, 1 ]
[]
[]
[ "apache", "buildout", "django", "nginx", "python" ]
stackoverflow_0002176172_apache_buildout_django_nginx_python.txt
Q: How can I catch server json response while uploading image using Ajax? I have a form which is loaded via jQuery from the external template file: $('#imguploadform').html('&nbsp;').load('{% url upload_form %}'); In template it looks like this: <img src="{{ MEDIA_URL }}img/misc/upload.png" alt="Illustration" title=...
How can I catch server json response while uploading image using Ajax?
I have a form which is loaded via jQuery from the external template file: $('#imguploadform').html('&nbsp;').load('{% url upload_form %}'); In template it looks like this: <img src="{{ MEDIA_URL }}img/misc/upload.png" alt="Illustration" title="myimage" /> <form id="uploadForm" enctype="multipart/form-data" method="pos...
[ "Have your success callback take a parameter. That will be the response.\n", "var submit_options = {\n target: '#picworks',\n dataType: 'json',\n success: function(response) { \n alert('It Works!');\n window.location.href = response.path;\n } \n};\n\n", "I solved the problem! The...
[ 0, 0, 0 ]
[]
[]
[ "django", "image", "python", "upload" ]
stackoverflow_0002187211_django_image_python_upload.txt
Q: How to launch a background process in Python with a delayed invocation? Ok, this is a bit of a thorny problem. I need to launch a backgrounded process that will (1) wait N secs, and then (2) execute some command. Additionally, I need to capture the pid of the background process itself, because when the parent proc...
How to launch a background process in Python with a delayed invocation?
Ok, this is a bit of a thorny problem. I need to launch a backgrounded process that will (1) wait N secs, and then (2) execute some command. Additionally, I need to capture the pid of the background process itself, because when the parent process finishes it will kill the backgrounded process if necessary. It looks a b...
[ "\nI can't use os.system() or os.fork(), since in each case the parent process does not have access to the pid of the child. \n\nEr, the parent gets the pid as a return value from fork().\nIn any case, I would suggest using the subprocess module. It gives you access to the pid via the pid attribute of the Popen obj...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002193551_python.txt
Q: Overcoming the "disadvantages" of string immutability I want to change the value of a particular string index, but unfortunately string[4] = "a" raises a TypeError, because strings are immutable ("item assignment is not supported"). So instead I use the rather clumsy string = string[:4] + "a" + string[4:] Is the...
Overcoming the "disadvantages" of string immutability
I want to change the value of a particular string index, but unfortunately string[4] = "a" raises a TypeError, because strings are immutable ("item assignment is not supported"). So instead I use the rather clumsy string = string[:4] + "a" + string[4:] Is there a better way of doing this?
[ "The strings in Python are immutable, just like numbers and tuples. This means that you can create them, move them around, but not change them. Why is this so ? For a few reasons (you can find a better discussion online):\n\nBy design, strings in Python are considered elemental and unchangeable. This spurs better, ...
[ 9, 3, 0 ]
[]
[]
[ "immutability", "python", "string" ]
stackoverflow_0002193705_immutability_python_string.txt
Q: How can I grap resident set size from Python on Solaris? Calling resource.getrusage() from Python returns a 0 value for resident set size on Solaris and Linux systems. On Linux you can pull the RSS From /proc//status instead. Does anybody have a good way to pull RSS on Solaris, either similar or not to the Linux w...
How can I grap resident set size from Python on Solaris?
Calling resource.getrusage() from Python returns a 0 value for resident set size on Solaris and Linux systems. On Linux you can pull the RSS From /proc//status instead. Does anybody have a good way to pull RSS on Solaris, either similar or not to the Linux workaround?
[ "Maybe use Solaris's psinfo under /proc? (solaris proc(4) docs)\n", "Well...you can pull it from the pmap application by calling pmap -x. But I was looking more for a way to access the info directly in /proc from my app. The only way to do it is to access the /proc/<pid>/xmap file. Unfortunately, the data is sto...
[ 0, 0 ]
[]
[]
[ "getrusage", "python", "solaris" ]
stackoverflow_0002180156_getrusage_python_solaris.txt
Q: M2Crypto: AttributeError for load_dynamic_engine() I am using M2Crypto-0.20.2. I want to use engine_pkcs11 from the OpenSC project and the Aladdin PKI client for token based authentication making xmlrpc calls over ssl. I am trying to load the PKCS#11 engine as well as the Aladdin module (see code below). But I g...
M2Crypto: AttributeError for load_dynamic_engine()
I am using M2Crypto-0.20.2. I want to use engine_pkcs11 from the OpenSC project and the Aladdin PKI client for token based authentication making xmlrpc calls over ssl. I am trying to load the PKCS#11 engine as well as the Aladdin module (see code below). But I get an error: AttributeError: 'module' object has no attr...
[ "I was reading the documentation wrong. The load_dynamic_engine() belong in the Engine module.\nI changed the command and now get a different error:\nEngine.load_dynamic_engine(\"dynamic\",\"/usr/local/ssl/lib/engines/engine_pkcs11.so\")\nbad engine id\nEngine.load_dynamic_engine(\"dynamic\",\"/usr/local/ssl/lib/e...
[ 0, 0 ]
[]
[]
[ "m2crypto", "openssl", "python" ]
stackoverflow_0002193181_m2crypto_openssl_python.txt
Q: Python underlying analysis books/articles? Does anyone know good books that discuss the underlying architectures, in-depth analysis of CPython implementation. Something like how list / tuple / dict implemented (and performance comparison...) OOP discussion in Python context Sorry if it sounds like a silly questi...
Python underlying analysis books/articles?
Does anyone know good books that discuss the underlying architectures, in-depth analysis of CPython implementation. Something like how list / tuple / dict implemented (and performance comparison...) OOP discussion in Python context Sorry if it sounds like a silly question :(
[ "Python features are described and discussed in Python Enhancement Proposals (\"PEPs\") These describe the implementation, also PEPs often contain working Python Code to help explain the algorithm though the final implementation may be in C. If you need more details than can be gotten from the PEPs then you should ...
[ 3, 3, 2, 2 ]
[]
[]
[ "architecture", "comparison", "performance", "python" ]
stackoverflow_0002193829_architecture_comparison_performance_python.txt
Q: How to start a "drawing loop" in PyQt? Often times when we're drawing a GUI, we want our GUI to update based on the data changing in our program. At the start of the program, let's say I've drawn my GUI based on my initial data. That data will be changing constantly, so how can I redraw my GUI constantly? A: T...
How to start a "drawing loop" in PyQt?
Often times when we're drawing a GUI, we want our GUI to update based on the data changing in our program. At the start of the program, let's say I've drawn my GUI based on my initial data. That data will be changing constantly, so how can I redraw my GUI constantly?
[ "The best way that I have found to do this is to run your core program in a QThread and use signals to communicate with your gui. Here is an example where I update a progress dialog as my main program does some stuff.\nHere is a code excerpt from a project that I was working on. The basic idea is that I am adding...
[ 1, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0002192993_pyqt_python.txt
Q: Checking for properties' validity in Python classes Where should I write codes for checking validity of class' properties? (For examples: "amount" should be a positive integer, "email" should be a string with correct e-mail formatting) At the setter methods, At somewhere I use that (using try/catch), or others. If...
Checking for properties' validity in Python classes
Where should I write codes for checking validity of class' properties? (For examples: "amount" should be a positive integer, "email" should be a string with correct e-mail formatting) At the setter methods, At somewhere I use that (using try/catch), or others. If I check validity at setter methods, it may be looked ugl...
[ "Definitely do it in the setter, if you need to do it at all.\nFirst, the setter is probably called less often than the getters, so you're doing less work. \nSecond, you catch the problem earlier.\nThird, it keeps the internal state of the object consistent. Keeping out bad data means you know that your object is...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002194479_python.txt
Q: Is there something similar to python's enumerate for linq In python I can easily get an index when iterating e.g. >>> letters = ['a', 'b', 'c'] >>> [(char, i) for i, char in enumerate(letters)] [('a', 0), ('b', 1), ('c', 2)] How can I do something similar with linq? A: Sure. There is an overload of Enumerable.S...
Is there something similar to python's enumerate for linq
In python I can easily get an index when iterating e.g. >>> letters = ['a', 'b', 'c'] >>> [(char, i) for i, char in enumerate(letters)] [('a', 0), ('b', 1), ('c', 2)] How can I do something similar with linq?
[ "Sure. There is an overload of Enumerable.Select that takes a Func<TSource, int, TResult> to project an element together with its index:\nFor example:\nchar[] letters = new[] { 'a', 'b', 'c' };\nvar enumerate = letters.Select((c, i) => new { Char = c, Index = i });\nforeach (var result in enumerate) {\n Console....
[ 9, 5 ]
[]
[]
[ ".net", "linq", "python" ]
stackoverflow_0002194684_.net_linq_python.txt
Q: Unit tests in Python Does Python have a unit testing framework compatible with the standard xUnit style of test framework? If so, what is it, where is it, and is it any good? A: Python has several testing frameworks, including unittest, doctest, and nose. The most xUnit-like is unittest, which is documented on P...
Unit tests in Python
Does Python have a unit testing framework compatible with the standard xUnit style of test framework? If so, what is it, where is it, and is it any good?
[ "Python has several testing frameworks, including unittest, doctest, and nose. The most xUnit-like is unittest, which is documented on Python.org.\n\nunittest documentation\ndoctest documentation\n\n", "I recommend nose.\nIt is the most Pythonic of the unit test frameworks. The test runner runs both doctests and ...
[ 25, 9, 3, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0000036647_python_unit_testing.txt
Q: How to swap the QGraphicsScene from a QGraphicsView? QGraphicsView is often hooked up to a QGraphicsScene. What if I want to swap that QGraphicsScene for a new one? How can I accomplish this? Doing it right now is just drawing over the old one. A: To swap the scene just call your view's setScene() again with ...
How to swap the QGraphicsScene from a QGraphicsView?
QGraphicsView is often hooked up to a QGraphicsScene. What if I want to swap that QGraphicsScene for a new one? How can I accomplish this? Doing it right now is just drawing over the old one.
[ "To swap the scene just call your view's setScene() again with a different QGraphicsScene object.\n" ]
[ 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0002194829_pyqt_python.txt
Q: setting script path in a buildout using one of the distutils recipes I am using buildout. I am using it to install openerp. I would like the scripts that openerp creates to run itself available in ${buildout:location}/bin I tried zerokspot.recipe.distutils and collective.recipe.distutils How would I get the...
setting script path in a buildout using one of the distutils recipes
I am using buildout. I am using it to install openerp. I would like the scripts that openerp creates to run itself available in ${buildout:location}/bin I tried zerokspot.recipe.distutils and collective.recipe.distutils How would I get the scripts built in bin?
[ "After some help and some research, it seems that openerp is hardly a standard distutils package. After some research and some help, I tracked down \nhttp://pypi.python.org/pypi/cns.recipe.symlink/0.1\nWhich I shall use to link the executables to the buildout. This will suffice. \n", "Did you successfuly insta...
[ 0, 0 ]
[]
[]
[ "buildout", "distutils", "python" ]
stackoverflow_0002031650_buildout_distutils_python.txt
Q: how to get to various attributes in the same order in python I have a file of lines and this in turn saves information, speed, timing and type of surfaces for each line. I want to do is sort this information in a np.array in the order shown below where the id is the number of the line. (id) 0 1 2 3 4 5...
how to get to various attributes in the same order in python
I have a file of lines and this in turn saves information, speed, timing and type of surfaces for each line. I want to do is sort this information in a np.array in the order shown below where the id is the number of the line. (id) 0 1 2 3 4 5 6 7 8 9 0 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 1 t1 t2 t...
[ "Your may find numpy.loadtxt useful.\nFor example, suppose you have a file with these contents:\ndatafile:\n(id) 0 1 \n0 1 smooth \n1 11 choppy\n2 20 turbulent\n3 2 smooth\n4 5 choppy\n5 7 bumpy\n\nThen you can load the data into a numpy structured array with\nimport numpy as np\narr=np.loadt...
[ 2, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002194357_numpy_python.txt
Q: Linux development/minimal smtp and pop3 server I use python based as well as rails applications on ubuntu linux. We have functionalities like register, forgot password, reset password, email alerts etc features based on emails. Since now a days, we go on offline development, we want to run a local smtp & pop3 serv...
Linux development/minimal smtp and pop3 server
I use python based as well as rails applications on ubuntu linux. We have functionalities like register, forgot password, reset password, email alerts etc features based on emails. Since now a days, we go on offline development, we want to run a local smtp & pop3 server to send and receive emails. Emails shall be send ...
[ "Why does it need to be a simple mail server?\nCan't you just use something like postfix which is very easy for simple configurations\n" ]
[ 2 ]
[]
[]
[ "email", "linux", "python", "ruby_on_rails" ]
stackoverflow_0002195203_email_linux_python_ruby_on_rails.txt
Q: Determining the unmatched portion of a string using a regex in Python Suppose I have a string "a foobar" and I use "^a\s*" to match "a ". Is there a way to easily get "foobar" returned? (What was NOT matched) I want to use a regex to look for a command word and also use the regex to remove the command word from th...
Determining the unmatched portion of a string using a regex in Python
Suppose I have a string "a foobar" and I use "^a\s*" to match "a ". Is there a way to easily get "foobar" returned? (What was NOT matched) I want to use a regex to look for a command word and also use the regex to remove the command word from the string. I know how to do this using something like: mystring[:regexobj.s...
[ "Use re.sub:\nimport re\ns = \"87 foo 87 bar\"\nr = re.compile(r\"87\\s*\")\ns = r.sub('', s)\nprint s\n\nResult:\nfoo bar\n\n", "from http://docs.python.org/library/re.html#re.split\n>>> re.split('(\\W+)', 'Words, words, words.')\n['Words', ', ', 'words', ', ', 'words', '.', '']\n\nso your example would be\n>>> ...
[ 8, 2, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002195340_python_regex.txt
Q: how do I know if a remote user is connected in django? how do I know if a remote user is connected in django?, like gmail chat, or facebook chat... I need that in the templates system. Sorry for my english A: If you need just a general idea of who is currently visiting your website, which includes anonymous visi...
how do I know if a remote user is connected in django?
how do I know if a remote user is connected in django?, like gmail chat, or facebook chat... I need that in the templates system. Sorry for my english
[ "If you need just a general idea of who is currently visiting your website, which includes anonymous visitors, use django-tracking app.\nIf you need a chat application, or need to know exactly who is logged in at any time, this is much more complicated and will require you to know a lot about chat protocols like XM...
[ 2, 1 ]
[]
[]
[ "django", "django_templates", "programming_languages", "python" ]
stackoverflow_0002195386_django_django_templates_programming_languages_python.txt
Q: Override all operators in python I have a wrapper class for an object. I want it to apply all operations applied to it on the wrapped object, e.g wrapper+=a would yield the same result as wrapped+=a, for instance. I want to apply this for all operators. Any simple way to override all operators without overriding e...
Override all operators in python
I have a wrapper class for an object. I want it to apply all operations applied to it on the wrapped object, e.g wrapper+=a would yield the same result as wrapped+=a, for instance. I want to apply this for all operators. Any simple way to override all operators without overriding each one explicitly?
[ "ActiveState Code: Recipe 496741: Object Proxying\n", "No, sorry. Though you could write an interface (probably as a decorator or base class) that makes this easy, if you need to do it more than once. Or use one provided already. (Guess I was 40s too late.)\n" ]
[ 6, 1 ]
[]
[]
[ "operators", "overriding", "python" ]
stackoverflow_0002195601_operators_overriding_python.txt
Q: How do I write a Django template custom tag that adds a slash before a single quote? Am I doing this right? (probably not...someone correct? thanks) @register.filter('addslashes') @stringfilter def addslashes(text, arg): return text.replace('\'','\\'') {{ query|addslashes }} A: There is a builtin filter wit...
How do I write a Django template custom tag that adds a slash before a single quote?
Am I doing this right? (probably not...someone correct? thanks) @register.filter('addslashes') @stringfilter def addslashes(text, arg): return text.replace('\'','\\'') {{ query|addslashes }}
[ "There is a builtin filter with the exact same name: addslashes\nIt also escapes double quotes, and double slashes. If you only want single quotes, you will have to adapt it and name it differently.\nHere is how the original works:\ndef addslashes(value):\n \"\"\"\n Adds slashes before quotes. Useful for esca...
[ 4 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0002195588_django_python_templates.txt
Q: How do I do "or" in Django template code? {% if is_loggedin OR is_anonymous %} test message {% endif %} A: {% if is_loggedin or is_anonymous %} test message {% endif %} Like that. A: if tags may use and, or or not to test a number of variables or to negate a given variable: http://docs.djangoproject.com/en/d...
How do I do "or" in Django template code?
{% if is_loggedin OR is_anonymous %} test message {% endif %}
[ "{% if is_loggedin or is_anonymous %}\ntest message\n{% endif %}\n\nLike that.\n", "\nif tags may use and, or or not to test a number of variables or to negate a given variable:\n\nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#if\nThe way you're doing it is fine. :-)\n" ]
[ 4, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002195726_django_python.txt
Q: Python conversion to ISO-8859-5 I'm facing problems when trying to convert a UTF-8 file (containing Russian characters) into an ISO-8859-5 file: 'charmap' codec can't encode character u'\ufeff' in position 0: character maps to . Has anyone got an idea of what's wrong(?) given the following: def convert(): try:...
Python conversion to ISO-8859-5
I'm facing problems when trying to convert a UTF-8 file (containing Russian characters) into an ISO-8859-5 file: 'charmap' codec can't encode character u'\ufeff' in position 0: character maps to . Has anyone got an idea of what's wrong(?) given the following: def convert(): try: import codecs data =...
[ "feff is a Byte-Order-Mark character. ISO-8859-5 won't have any representation for it.\nYou'll need to strip it off your data variable before encoding it into ISO-8859-5.\n", "Recent versions of Python have the utf-8-sig codec that will automatically strip the BOM off a UTF-8-encoded string or file when reading i...
[ 2, 2 ]
[]
[]
[ "character_encoding", "encoding", "python", "unicode" ]
stackoverflow_0002193611_character_encoding_encoding_python_unicode.txt
Q: Why isn't there a do while flow control statement in python? Is there a good reason why there isn't a do while flow control statement in python? Why do people have to write while and break explicitly? A: It has been proposed in PEP 315 but hasn't been implemented because nobody has come up with a syntax that's c...
Why isn't there a do while flow control statement in python?
Is there a good reason why there isn't a do while flow control statement in python? Why do people have to write while and break explicitly?
[ "It has been proposed in PEP 315 but hasn't been implemented because nobody has come up with a syntax that's clearer than the while True with an inner if-break.\n", "Probably because Guido didn't think it was necessary. There are a bunch of different flow-control statements you could support, but most of them are...
[ 11, 10, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002192344_python.txt
Q: Python class has method "set", how to reference builtin set type? If you have a method called "set" in a class and want to create a standard builtin "set" object somewhere else in the class, Python seems to reference the method when I do that. How can you be more specific to let Python know you mean the builtin "s...
Python class has method "set", how to reference builtin set type?
If you have a method called "set" in a class and want to create a standard builtin "set" object somewhere else in the class, Python seems to reference the method when I do that. How can you be more specific to let Python know you mean the builtin "set", not the method "set"? More specifically, set() is being created in...
[ "I think I know what's going on here. Are you doing something like this?\n>>> class A(object):\n... def set(self):\n... pass\n... def test(self, x=set):\n... return x\n... \n>>> set\n<type 'set'>\n>>> A().test()\n<function set at 0x64270>\n\nThis is a subtle problem due to the way m...
[ 10, 3, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002195755_python.txt
Q: django csv import threading Is it possible to use threading when importing data from csv files to django. A: Django is Python, so yeah you can use threads, processing etc. Look at python docs on this matter. But, spawning threads in web environment might be not be such a good idea, try searching here for "django...
django csv import threading
Is it possible to use threading when importing data from csv files to django.
[ "Django is Python, so yeah you can use threads, processing etc. Look at python docs on this matter.\nBut, spawning threads in web environment might be not be such a good idea, try searching here for \"django asynchronous\" - you'll get many ideas of how to this without threading.\n" ]
[ 2 ]
[]
[]
[ "csv", "django", "multithreading", "python" ]
stackoverflow_0002190075_csv_django_multithreading_python.txt
Q: VLC/Python bindings? Does anyone know how to implement the VLC Python bindings? I downloaded vlc.py and vlcwidget.py from the VLC wiki (http://wiki.videolan.org/Python_bindings) and tried to run vlcwidget. Other than having vlc installed, do I need to do anything else, or should I just be able to run 'python vlc...
VLC/Python bindings?
Does anyone know how to implement the VLC Python bindings? I downloaded vlc.py and vlcwidget.py from the VLC wiki (http://wiki.videolan.org/Python_bindings) and tried to run vlcwidget. Other than having vlc installed, do I need to do anything else, or should I just be able to run 'python vlcwidget.py '? Because that...
[ "\n$ git clone git://git.videolan.org/vlc.git && cd vlc\n$ git log -Slibvlc_media_player_new\n...\ncommit bf1292e44390c6469483cea3817d6c2a3dbd811c\nAuthor: Pierre d'Herbemont <pdherbemont@videolan.org>\nDate: Sun Mar 30 03:59:32 2008 +0200\n\n libvlc: rename libvlc_media_descriptor to libvlc_media and libvlc_m...
[ 2 ]
[]
[]
[ "binding", "libvlc", "python", "vlc" ]
stackoverflow_0002195631_binding_libvlc_python_vlc.txt
Q: Saving an image of what a device context drew, wxPython I need to be able to save an image (format doesn't matter) of the state of the device context canvas. I tried dc.GetAsBitmap but it returns invalid bitmaps. How can I do it? A: I believe this should do the trick: def saveSnapshot(dcSource): # based larg...
Saving an image of what a device context drew, wxPython
I need to be able to save an image (format doesn't matter) of the state of the device context canvas. I tried dc.GetAsBitmap but it returns invalid bitmaps. How can I do it?
[ "I believe this should do the trick:\ndef saveSnapshot(dcSource):\n # based largely on code posted to wxpython-users by Andrea Gavana 2006-11-08\n size = dcSource.Size\n\n # Create a Bitmap that will later on hold the screenshot image\n # Note that the Bitmap must have a size big enough to hold the scre...
[ 6, 1 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0002195792_python_wxpython_wxwidgets.txt
Q: Does PySVN need Subversion installed? I have python script that uses pysvn and checks out or updates a local copy obtained also from a local repo. client.checkout(url, path, revision=pysvn.Revision(pysvn.opt_revision_kind.number, RevNumber), ignore_externals=False) I am running this on a windows machine in which...
Does PySVN need Subversion installed?
I have python script that uses pysvn and checks out or updates a local copy obtained also from a local repo. client.checkout(url, path, revision=pysvn.Revision(pysvn.opt_revision_kind.number, RevNumber), ignore_externals=False) I am running this on a windows machine in which I haven't installed subversion. The svnsyn...
[ "This is because your Ubuntu is accessing the repo with too old a version of the SVN API.\nThe windows one is fine because it is obviously using a newer version.\nAccording the PySVN download page:\n\nWindows binary kits\nNote: These windows kits are all you\n need. It is not necessary to install\n any Subversion...
[ 1 ]
[]
[]
[ "pysvn", "python", "svn", "ubuntu_9.04", "windows" ]
stackoverflow_0002197156_pysvn_python_svn_ubuntu_9.04_windows.txt
Q: Python shelve OutOfMemory error I have some data stored in a DB that I want to process. DB access is painfully slow, so I decided to load all data in a dictionary before any processing. However, due to the huge size of the data stored, I get an out of memory error (I see more than 2 gigs being used). So I decided ...
Python shelve OutOfMemory error
I have some data stored in a DB that I want to process. DB access is painfully slow, so I decided to load all data in a dictionary before any processing. However, due to the huge size of the data stored, I get an out of memory error (I see more than 2 gigs being used). So I decided to use a disk data structure, and fou...
[ "writeback=True forces the shelf to keep in-memory any item ever fetched, and write them back when the shelf is closed. So, it consumes much more memory, and slows down closing.\nThe advantage of the parameter is that, with it, you don't need the contorted code you show in your comment for mutable items whose mutat...
[ 10, 0 ]
[]
[]
[ "dictionary", "out_of_memory", "persistence", "python", "shelve" ]
stackoverflow_0002196969_dictionary_out_of_memory_persistence_python_shelve.txt
Q: Convert Chrome history date/time stamp to readable format I originally posted this question looking for an answer with using python, got some good help, but have still not been able to find a solution. I have a script running on OS X 10.5 client machines that captures internet browsing history (required as part of...
Convert Chrome history date/time stamp to readable format
I originally posted this question looking for an answer with using python, got some good help, but have still not been able to find a solution. I have a script running on OS X 10.5 client machines that captures internet browsing history (required as part of my sys admin duties in a US public school). Firefox 3.x stores...
[ "Use the datetime module. For example, if the number of microseconds in questions is 10**16:\n>>> datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=1e16)\ndatetime.datetime(1917, 11, 21, 17, 46, 40)\n>>> _.isoformat()\n'1917-11-21T17:46:40'\n\nthis tells you it was just past a quarter to 6pm of Novem...
[ 9 ]
[]
[]
[ "datetime", "google_chrome", "macos", "python" ]
stackoverflow_0002193820_datetime_google_chrome_macos_python.txt
Q: New to Mac Platform, Trying to get back to default python install I've been trying to follow this blog post to get my python version back to the snow leopard default. I have followed the first two steps without a problem but am lost when it comes to 3 and 4. I installed Python 2.6.4 but I assume the instructions...
New to Mac Platform, Trying to get back to default python install
I've been trying to follow this blog post to get my python version back to the snow leopard default. I have followed the first two steps without a problem but am lost when it comes to 3 and 4. I installed Python 2.6.4 but I assume the instructions are pretty similar. Thanks for your help!
[ "Step 3:\nsudo rm /usr/local/bin/python\nStep 4:\nls ~/.bash_profile.pysave\nIf the file exists:\nrm ~/.bash_profile && mv ~/.bash_profile.pysave ~/.bash_profile\nYou will probably want to close your shell / Terminal and open a new one at this point. Run Python and see what it tells you.\n", "Please be aware that...
[ 2, 0 ]
[]
[]
[ "macos", "osx_snow_leopard", "python" ]
stackoverflow_0002196823_macos_osx_snow_leopard_python.txt
Q: Why doesn't super(Thread, self).__init__() work for a threading.Thread subclass? Every object I know of in Python can take care of its base class initialization by calling: super(BaseClass, self).__init__() This doesn't seem to be the case with a subclass of threading.Thread, since if I try this in SubClass.__ini...
Why doesn't super(Thread, self).__init__() work for a threading.Thread subclass?
Every object I know of in Python can take care of its base class initialization by calling: super(BaseClass, self).__init__() This doesn't seem to be the case with a subclass of threading.Thread, since if I try this in SubClass.__init__(), I get: RuntimeError: thread.__init__() not called What gives this error? I lo...
[ "This works fine:\n>>> class MyThread(threading.Thread):\n... def __init__(self):\n... super(MyThread, self).__init__()\n\nI think your code's bug is that you're passing the base class, rather than the current class, to super -- i.e. you're calling super(threading.Thread, ..., and that's just wrong. Hard to s...
[ 43 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002197563_multithreading_python.txt
Q: Complex SQL optimization vs. general-purpose language How might I optimize this query? The schema: mysql> show columns from transactionlog; +---------------+-------------------------------------------+------+-----+---------+----------------+ | Field | Type | Null | Key ...
Complex SQL optimization vs. general-purpose language
How might I optimize this query? The schema: mysql> show columns from transactionlog; +---------------+-------------------------------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+-------------...
[ "Use:\n SELECT CONCAT(x.weight, ' ', GROUP_CONCAT(t.id SEPARATOR ' '), '\\n')\n FROM TRANSACTIONLOG t\n JOIN (SELECT tl.tableid,\n tl.tupleid,\n COUNT(DISTINCT tl.transactionid) AS weight\n FROM TRANSACTIONLOG tl\n WHERE tl.querytype = 'update'\n GR...
[ 0 ]
[]
[]
[ "mysql", "optimization", "python", "sql" ]
stackoverflow_0002197579_mysql_optimization_python_sql.txt
Q: How to Handle EOFError for raw_input() in python in Mac OS X My python program has two calls to raw_input() The first raw_input() is to take multiline input from the user. The user can issue Ctrl+D (Ctrl+Z in windows) for the end of input. Second raw_input() should take another input from user with (y/n) type pro...
How to Handle EOFError for raw_input() in python in Mac OS X
My python program has two calls to raw_input() The first raw_input() is to take multiline input from the user. The user can issue Ctrl+D (Ctrl+Z in windows) for the end of input. Second raw_input() should take another input from user with (y/n) type prompt. Unfortunately (in Mac OS X only?), second raw_input() raises ...
[ "It's quite normal that when standard input is terminated (by hitting control-D, in Unix-derived systems -- I think it's control-Z in Windows), it stays terminated thereafter (unless you close and re-open it in the meantime, of course).\n" ]
[ 6 ]
[]
[]
[ "eof", "eoferror", "macos", "python" ]
stackoverflow_0002197891_eof_eoferror_macos_python.txt
Q: Convert "little endian" hex string to IP address in Python What's the best way to turn a string in this form into an IP address: "0200A8C0". The "octets" present in the string are in reverse order, i.e. the given example string should generate 192.168.0.2. A: Network address manipulation is provided by the socke...
Convert "little endian" hex string to IP address in Python
What's the best way to turn a string in this form into an IP address: "0200A8C0". The "octets" present in the string are in reverse order, i.e. the given example string should generate 192.168.0.2.
[ "Network address manipulation is provided by the socket module.\n\nsocket.inet_ntoa(packed_ip)\nConvert a 32-bit packed IPv4 address (a string four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the stand...
[ 35, 7, 3, 0 ]
[]
[]
[ "endianness", "ip_address", "python", "sockets" ]
stackoverflow_0002197974_endianness_ip_address_python_sockets.txt
Q: python file reading I have file /tmp/gs.pid with content client01: 25778 I would like retrieve the second word from it. ie. 25778. I have tried below code but it didn't work. >>> f=open ("/tmp/gs.pid","r") >>> for line in f: ... word=line.strip().lower() ... print "\n -->" , word A: Try this: >>> f ...
python file reading
I have file /tmp/gs.pid with content client01: 25778 I would like retrieve the second word from it. ie. 25778. I have tried below code but it didn't work. >>> f=open ("/tmp/gs.pid","r") >>> for line in f: ... word=line.strip().lower() ... print "\n -->" , word
[ "Try this:\n>>> f = open(\"/tmp/gs.pid\", \"r\")\n>>> for line in f:\n ... word = line.strip().split()[1].lower()\n ... print \" -->\", word\n>>> f.close()\n\nIt will print the second word of every line in lowercase. split() will take your line and split it on any whitespace and return a list, then indexi...
[ 7, 1, 1, 1 ]
[]
[]
[ "file", "python", "string" ]
stackoverflow_0002197958_file_python_string.txt
Q: Python's layout of low-value ints in memory My question is: where do these patterns (below) originate? I learned (somewhere) that Python has unique "copies", if that's the right word, for small integers. For example: >>> x = y = 0 >>> id(0) 4297074752 >>> id(x) 4297074752 >>> id(y) 4297074752 >>> x += 1 >>> id(x...
Python's layout of low-value ints in memory
My question is: where do these patterns (below) originate? I learned (somewhere) that Python has unique "copies", if that's the right word, for small integers. For example: >>> x = y = 0 >>> id(0) 4297074752 >>> id(x) 4297074752 >>> id(y) 4297074752 >>> x += 1 >>> id(x) 4297074728 >>> y 0 When I look at the memory l...
[ "Low-value integers are preallocated, high value integers are allocated whenever they are computed. Integers that appear in source code are the same object. On my system,\n>>> id(2) == id(1+1)\nTrue\n>>> id(1000) == id(1000+0)\nFalse\n>>> id(1000) == id(1000)\nTrue\n\nYou'll also notice that the ids depend on the...
[ 8, 2, 2, 2, 1, 0 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0002195964_memory_python.txt
Q: Importing globally and locally I created a module which is going to be used in several python scripts. The structure is as follows: Main file: import numpy as np from mymodule import newfunction f = np.arange(100,200,1) a = np.zeros(np.shape(f)) c = newfunction(f) mymodule.py: def newfunction(f): import numpy...
Importing globally and locally
I created a module which is going to be used in several python scripts. The structure is as follows: Main file: import numpy as np from mymodule import newfunction f = np.arange(100,200,1) a = np.zeros(np.shape(f)) c = newfunction(f) mymodule.py: def newfunction(f): import numpy as np b = np.zeros(np.shape(f))...
[ "mymodule.py doesn't see:\n import numpy as np\n\nstatement(s). \"import\" statement in Python doesn't work like #include in C++, it merely creates new dictionary of objects contained in imported module. If you want to use 'np' identifier within that dictionary, you have to explicitly import it there.\nRegarding\n...
[ 3 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0002198082_import_module_python.txt
Q: How do I update my version of Django? I currently have it installed and it's running a website. http://www.djangoproject.com/download/ This is the new version. How do I upgrade it? (How do I install the new version over my current one?) A: read about this in : http://docs.djangoproject.com/en/dev/topics/install/...
How do I update my version of Django?
I currently have it installed and it's running a website. http://www.djangoproject.com/download/ This is the new version. How do I upgrade it? (How do I install the new version over my current one?)
[ "read about this in :\nhttp://docs.djangoproject.com/en/dev/topics/install/\nFor installing Django to be able to update to the latest code in trunk:\n\nIf you'd like to be able to update\n your Django code occasionally with the\n latest bug fixes and improvements,\n follow these instructions:\n1.Make sure that y...
[ 5, 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002197919_django_python.txt