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:
Looking for production quality Hash table/ unordered map implementation to learn?
Looking for good source code either in C or C++ or Python to understand how a hash function is implemented and also how a hash table is implemented using it.
Very good material on how hash fn and hash table implementation works.
Tha... | Looking for production quality Hash table/ unordered map implementation to learn? |
Looking for good source code either in C or C++ or Python to understand how a hash function is implemented and also how a hash table is implemented using it.
Very good material on how hash fn and hash table implementation works.
Thanks in advance.
| [
"Hashtables are central to Python, both as the 'dict' type and for the implementation of classes and namespaces, so the implementation has been refined and optimised over the years. You can see the C source for the dict object here.\nEach Python type implements its own hash function - browse the source for the oth... | [
3,
1,
1
] | [] | [] | [
"c",
"c++",
"hash",
"hashtable",
"python"
] | stackoverflow_0003031358_c_c++_hash_hashtable_python.txt |
Q:
Python module being reloaded for each request with django and mod_wsgi
I have a variable in init of a module which get loaded from the database and takes about 15 seconds.
For django development server everything is working fine but looks like with apache2 and mod_wsgi the module is loaded with every request (tak... | Python module being reloaded for each request with django and mod_wsgi | I have a variable in init of a module which get loaded from the database and takes about 15 seconds.
For django development server everything is working fine but looks like with apache2 and mod_wsgi the module is loaded with every request (taking 15 seconds).
Any idea about this behavior?
Update: I have enabled daemo... | [
"You were likely ignoring the fact that in embedded mode of mod_wsgi or with mod_python, the application is multiprocess. Thus requests may go to different processes and you will see a delay the first time a process which hasn't been hit before is encountered. In mod_wsgi daemon mode the default has only a single p... | [
3,
1
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0003025378_apache_django_mod_wsgi_python.txt |
Q:
How do I make a defaultdict safe for unexpecting clients?
Several times (even several in a row) I've been bitten by the defaultdict bug: forgetting that something is actually a defaultdict and treating it like a regular dictionary.
d = defaultdict(list)
...
try:
v = d["key"]
except KeyError:
print "Sorry, no... | How do I make a defaultdict safe for unexpecting clients? | Several times (even several in a row) I've been bitten by the defaultdict bug: forgetting that something is actually a defaultdict and treating it like a regular dictionary.
d = defaultdict(list)
...
try:
v = d["key"]
except KeyError:
print "Sorry, no dice!"
For those who have been bitten too, the problem is evi... | [
"You may still convert it to an normal dict.\nd = collections.defaultdict(list)\nd = dict(d)\n\n",
"use different idiom:\nif 'key' not in d:\n print \"Sorry, no dice!\"\n\n",
"You can prevent creation of default values by assigning d.default_factory = None. However, I don't quite like the idea of object sudd... | [
14,
7,
5,
2,
1
] | [] | [] | [
"default_value",
"python"
] | stackoverflow_0003031817_default_value_python.txt |
Q:
Best way in Python to determine all possible intersections in a matrix?
So if I have a matrix (list of lists) where each column represents a unique word, each row represents a distinct document, and every entry is a 1 or 0, indicating whether or not the word for a given column exists in the document for a given ro... | Best way in Python to determine all possible intersections in a matrix? | So if I have a matrix (list of lists) where each column represents a unique word, each row represents a distinct document, and every entry is a 1 or 0, indicating whether or not the word for a given column exists in the document for a given row.
What I'd like to know is how to determine all the possible combinations of... | [
"\nNormalize the text. You only want strings made of string.lowercase. Split/strip on everything else.\nMake sets out of this.\nUse something like this to get all possible groupings of all sizes:\ndef get_all_lengths_combinations_of(elements):\n for no_of_items in range(2, len(elements)+1):\n for items in itert... | [
3,
3,
1,
0
] | [] | [] | [
"matrix",
"numpy",
"python",
"vector"
] | stackoverflow_0003027925_matrix_numpy_python_vector.txt |
Q:
Detecting and interacting with long running process
I want a script to start and interact with a long running process. The process is started first time the script is executed, after that the script can be executed repeatedly, but will detect that the process is already running. The script should be able to intera... | Detecting and interacting with long running process | I want a script to start and interact with a long running process. The process is started first time the script is executed, after that the script can be executed repeatedly, but will detect that the process is already running. The script should be able to interact with the process. I would like this to work on Unix an... | [
"Sockets are easier to make portable between Windows and any other OS, so that's what I would recommend it over named pipes (that's why e.g. IDLE uses sockets rather than named pipes -- the latter require platform-dependent code on Windows, e.g. via ctypes [[or third-party win32all or cython &c]], while sockets jus... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003032378_python.txt |
Q:
Strip text except from the contents of a tag
The opposite may be achieved using pyparsing as follows:
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
removeText = replaceWith("")
scriptOpen, scriptClose = makeHTMLTags("script")
scriptBody = scriptOpen + SkipTo(scriptClose) + scriptClose
scri... | Strip text except from the contents of a tag | The opposite may be achieved using pyparsing as follows:
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
removeText = replaceWith("")
scriptOpen, scriptClose = makeHTMLTags("script")
scriptBody = scriptOpen + SkipTo(scriptClose) + scriptClose
scriptBody.setParseAction(removeText)
data = (scriptBo... | [
"You could first extract the table (similarly to the way you're now extracting the script but without the removal of course;-), obtaining a thetable string; then, you extract the script, replaceWith(thetable) instead of replaceWith(''). Alternatively, you could prepare a more elaborate parse action, but the simple... | [
1
] | [] | [] | [
"parsing",
"pyparsing",
"python"
] | stackoverflow_0003032532_parsing_pyparsing_python.txt |
Q:
How to access non-first matches with xpath in Selenium RC?
I have 20 labels in my page:
In [85]: sel.get_xpath_count("//label")
Out[85]: u'20'
And I can get the first one be default:
In [86]: sel.get_text("xpath=//label")
Out[86]: u'First label:'
But, unlike the xpath docs I've found, I'm getting an error trying... | How to access non-first matches with xpath in Selenium RC? | I have 20 labels in my page:
In [85]: sel.get_xpath_count("//label")
Out[85]: u'20'
And I can get the first one be default:
In [86]: sel.get_text("xpath=//label")
Out[86]: u'First label:'
But, unlike the xpath docs I've found, I'm getting an error trying to subscript the xpath to get to the second label's text:
In [8... | [
"Use:\n(//label)[2]\nThe XPath expression you are currently using:\n\n//label[2]\n\nmeans:\nSelect every label element in the document that is the second label child of its parent. Chances are that every label in the document is just the first and only label child of its parent. In such a case the above expression ... | [
2
] | [] | [] | [
"python",
"selenium",
"selenium_rc",
"xpath"
] | stackoverflow_0003031299_python_selenium_selenium_rc_xpath.txt |
Q:
Named keywords in decorators?
I've been playing around in depth with attempting to write my own version of a memoizing decorator before I go looking at other people's code. It's more of an exercise in fun, honestly. However, in the course of playing around I've found I can't do something I want with decorators.
... | Named keywords in decorators? | I've been playing around in depth with attempting to write my own version of a memoizing decorator before I go looking at other people's code. It's more of an exercise in fun, honestly. However, in the course of playing around I've found I can't do something I want with decorators.
def addValue( func, val ):
def ... | [
"You need to define a function that returns a decorator:\ndef addValue(val):\n def decorator(func):\n def add(x):\n return func(x) + val\n return add\n return decorator\n\nWhen you write @addTwo, the value of addTwo is directly used as a decorator. However, when you write @addValue(4)... | [
5,
5,
3
] | [] | [] | [
"decorator",
"keyword",
"named_parameters",
"python"
] | stackoverflow_0003032579_decorator_keyword_named_parameters_python.txt |
Q:
wsgi-served page does not refresh
I recently got my first app to work in uWSGI with Cherokee. I used the following code taken from the uWSGI docs:
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
yield 'Hello World\n'
The page correctly reads Hello World. Wh... | wsgi-served page does not refresh | I recently got my first app to work in uWSGI with Cherokee. I used the following code taken from the uWSGI docs:
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
yield 'Hello World\n'
The page correctly reads Hello World. When I change that text to New Thing and ... | [
"So the way this works is that Cherokee is managing a running uwsgi instance in the back ground for you. What I've noticed so far, and I've not finished looking at, is that if you shut down Cherokee it doesn't seem to also shut down running uwsgi instances. \nTry this:\nsudo service cherokee start\nps aux | grep uw... | [
2
] | [] | [] | [
"cherokee",
"python",
"uwsgi",
"wsgi"
] | stackoverflow_0003031265_cherokee_python_uwsgi_wsgi.txt |
Q:
Is a python dictionary the best data structure to solve this problem?
I have a number of processes running which are controlled by remote clients. A tcp server controls access to these processes, only one client per process. The processes are given an id number in the range of 0 -> n-1. Were 'n' is the number of p... | Is a python dictionary the best data structure to solve this problem? | I have a number of processes running which are controlled by remote clients. A tcp server controls access to these processes, only one client per process. The processes are given an id number in the range of 0 -> n-1. Were 'n' is the number of processes. I use a dictionary to map this id to the client sockets file desc... | [
"You can keep that idea but add a list or whatever to hold unused socked fd, so that you have no to iterate the dictionary to find the first usable \"None\". When you pick the first (or last) free process from the \"not busy\" list, you remove from it. E.g.\n# d is the dictionary\n# notbusy is a list\nd[ notbusy.po... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003032207_dictionary_python.txt |
Q:
Custom Django tag & jQuery
I'm new to Django. Today I created some Django custom tags which is not that hard. But now I wonder what is the best way to include some jQuery or some Javascript code packed into my custom tag definition. What is the regular way to include a custom library into my code? For example:
{% ... | Custom Django tag & jQuery | I'm new to Django. Today I created some Django custom tags which is not that hard. But now I wonder what is the best way to include some jQuery or some Javascript code packed into my custom tag definition. What is the regular way to include a custom library into my code? For example:
{% faceboxify item %}
So assume th... | [
"From the documentation you can see that writing template tags involves writing a target function and a renderer. So I'm assuming your current code looks like this:\ndef my_tag(parser, token):\n # ... some code\n return MyNode(...)\n\nclass MyNode(template.Node):\n def render(self, context):\n # here is wher... | [
2,
0
] | [] | [] | [
"django",
"django_custom_tags",
"jquery",
"python"
] | stackoverflow_0003032783_django_django_custom_tags_jquery_python.txt |
Q:
I need a dictionary text file with meanings
I need a text file in the form:
aardvark : animal
atlas : collection of maps
.
.
.
.
.
and so on.
I want to use this text file to create my own dictionary like Artha or Wordweb.It will be Python based with Tkinter for GUI.
Where can I obtain such a file.
A:
Project Gut... | I need a dictionary text file with meanings | I need a text file in the form:
aardvark : animal
atlas : collection of maps
.
.
.
.
.
and so on.
I want to use this text file to create my own dictionary like Artha or Wordweb.It will be Python based with Tkinter for GUI.
Where can I obtain such a file.
| [
"Project Gutenberg has a few variants (including the unabridged Webster's). Not exactly the format you're looking for, but you should be able to parse it to remove parts of speech, etc.\n",
"Natural Language Toolkit. \nYes, this is a large complex library because the task is actually complex. aardvark: animal is ... | [
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003032955_dictionary_python.txt |
Q:
Python execute a function for X seconds
I'm looking for a way for a function to take actions based on how long it has been executing. For example, my function would loop continuously until 5 seconds has elapsed, in which case it returns immediately. Any suggestions?
A:
Have you looked at time.clock() ?
time.clo... | Python execute a function for X seconds | I'm looking for a way for a function to take actions based on how long it has been executing. For example, my function would loop continuously until 5 seconds has elapsed, in which case it returns immediately. Any suggestions?
| [
"Have you looked at time.clock() ?\n\ntime.clock()\nOn Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function... | [
5,
4
] | [] | [] | [
"python"
] | stackoverflow_0003033005_python.txt |
Q:
Need help understanding some Python code with @, *args and **kwargs
I'm new to Python, and stumped by this piece of code from the Boto project:
class SubdomainCallingFormat(_CallingFormat):
@assert_case_insensitive
def get_bucket_server(self, server, bucket):
return '%s.%s' % (bucket, server)
def ... | Need help understanding some Python code with @, *args and **kwargs | I'm new to Python, and stumped by this piece of code from the Boto project:
class SubdomainCallingFormat(_CallingFormat):
@assert_case_insensitive
def get_bucket_server(self, server, bucket):
return '%s.%s' % (bucket, server)
def assert_case_insensitive(f):
def wrapper(*args, **kwargs):
if ... | [
"The @ symbol is used to indicate the application of a decorator.\nAnd those asterisks indicate the parameters are excess positional/keyword arguments put into a list/dictionary.\nThe \"f\" represents the function passed in, as a first-class object, into the decorator. When someone writes\n@decorate\ndef whizbang()... | [
6,
4,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003033133_python.txt |
Q:
Python sorting problem
Possible Duplicate:
Python analog of natsort function (sort a list using a “natural order” algorithm)
I'm sure this is simple but I can't figure it out. I have a list of strings like this(after using sorted on it):
Season 2, Episode 1: A Flight to Remember
Season 2, Episode 20: Anthology o... | Python sorting problem |
Possible Duplicate:
Python analog of natsort function (sort a list using a “natural order” algorithm)
I'm sure this is simple but I can't figure it out. I have a list of strings like this(after using sorted on it):
Season 2, Episode 1: A Flight to Remember
Season 2, Episode 20: Anthology of Interest I
Season 2, Epis... | [
"Use the key parameter to the sort function to specify the key you would like to use for sorting.\ndef get_sort_key(s):\n m = re.match('Season ([0-9]+), Episode ([0-9]+): .*', s)\n return (int(m.group(1)), int(m.group(2)))\n\nmy_list.sort(key=get_sort_key)\n\n",
"There are two ways to approach this:\n\nDefi... | [
3,
1,
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0003033271_python_sorting.txt |
Q:
What is the best way to implement a 'last seen' function in a django web app?
I have a running django/apache2 + memcached app (ubuntu) and would like to keep track of logged in users that are online.
What would be the best way to track this?
I would prefer not writing to the database each time a logged in user lo... | What is the best way to implement a 'last seen' function in a django web app? | I have a running django/apache2 + memcached app (ubuntu) and would like to keep track of logged in users that are online.
What would be the best way to track this?
I would prefer not writing to the database each time a logged in user loads a page; but what other options are there?
| [
"An approach might be:\nyou create a middleware that does the following on process_response:\n\ncheck for a cookie called 'online', but only if the user is authenticated\nif the cookie is not there,\n\n\nset a cookie called 'online' with value '1'\nset the lifespan of the cookie to 10 minutes\nupdate the 'last_logi... | [
4,
1,
1,
0
] | [] | [] | [
"apache2",
"django",
"python"
] | stackoverflow_0003027973_apache2_django_python.txt |
Q:
Script to install and compile Python, Django, Virtualenv, Mercurial, Git, LessCSS, etc... on Dreamhost
The Story
After cleaning up my Dreamhost shared server's home folder from all the cruft accumulated over time, I decided to start afresh and compile/reinstall Python.
All tutorials and snippets I found seemed ove... | Script to install and compile Python, Django, Virtualenv, Mercurial, Git, LessCSS, etc... on Dreamhost | The Story
After cleaning up my Dreamhost shared server's home folder from all the cruft accumulated over time, I decided to start afresh and compile/reinstall Python.
All tutorials and snippets I found seemed overly simplistic, assuming (or ignoring) a bunch of dependencies needed by Python to compile all modules corre... | [
"One way to streamline this would be to make it work with one of: capistrano/fabric, puppet/chef, jhbuild, or buildout+minitage (and a lot of cmmi tasks). There are some opportunities for factoring in common code, especially with something more high-level than bash. You will run into bootstrapping issues, however, ... | [
2,
1
] | [] | [] | [
"dreamhost",
"git",
"installation",
"mercurial",
"python"
] | stackoverflow_0002913913_dreamhost_git_installation_mercurial_python.txt |
Q:
In plain English, what are Django generic views?
The first two paragraphs of this page explain that generic views are supposed to make my life easier, less monotonous, and make me more attractive to women (I made up that last one):
https://docs.djangoproject.com/en/1.4/topics/generic-views/
I'm all for improving m... | In plain English, what are Django generic views? | The first two paragraphs of this page explain that generic views are supposed to make my life easier, less monotonous, and make me more attractive to women (I made up that last one):
https://docs.djangoproject.com/en/1.4/topics/generic-views/
I'm all for improving my life, but what do generic views actually do? It seem... | [
"Django generic views are just view functions (regular old python functions) that do things that are very common in web applications.\nDepending on the type of app you are building, they can save you from writing a lot of very simple views.\nFor example, the direct_to_template generic view simply renders a template... | [
20,
5,
2
] | [] | [] | [
"django",
"django_generic_views",
"python"
] | stackoverflow_0002437468_django_django_generic_views_python.txt |
Q:
How to build 64-bit Python on OS X 10.6 -- ONLY 64 bit, no Universal nonsense
I just want to build this on my development machine -- the binary install from Python.org is still 32 bits and installing extensions (MySQLdb, for example) is driving me nuts with trying to figure out the proper flags for each and every ... | How to build 64-bit Python on OS X 10.6 -- ONLY 64 bit, no Universal nonsense | I just want to build this on my development machine -- the binary install from Python.org is still 32 bits and installing extensions (MySQLdb, for example) is driving me nuts with trying to figure out the proper flags for each and every extension.
Clarification: I did NOT replace the system Python, I just installed the... | [
"If you happen to be using MacPorts, it's as simple as specifying the variant that tells it not to compile Universal, like so:\nsudo port install python26 -universal\n\nYou can view available variants using the variants command:\n% port variants python26 \npyth... | [
11,
5,
5,
3
] | [] | [] | [
"64_bit",
"macos",
"osx_snow_leopard",
"python",
"x86_64"
] | stackoverflow_0002111283_64_bit_macos_osx_snow_leopard_python_x86_64.txt |
Q:
SQLAlchemy automatically converts str to unicode on commit
When inserting an object into a database with SQLAlchemy, all it's properties that correspond to String() columns are automatically transformed from <type 'str'> to <type 'unicode'>. Is there a way to prevent this behavior?
Here is the code:
from sqlalchem... | SQLAlchemy automatically converts str to unicode on commit | When inserting an object into a database with SQLAlchemy, all it's properties that correspond to String() columns are automatically transformed from <type 'str'> to <type 'unicode'>. Is there a way to prevent this behavior?
Here is the code:
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData... | [
"Actually, there is a way to do that. Just execute this line of code after creating engine:\nengine.raw_connection().connection.text_factory = str\n",
"Unfortunately, you are out of luck and this does not seem to work with sqlite. A quote from SQLAlchemy 0.6.2 Documentation - SQLite - Unicode:\n\nIn contrast to S... | [
12,
6
] | [] | [] | [
"python",
"sqlalchemy",
"unicode"
] | stackoverflow_0003033741_python_sqlalchemy_unicode.txt |
Q:
Interpreter more strict
Today, i lost a lot of time fixing a stupid error in my code. Very simplified, the problem was this:
def f():
return 2
2 == f
I forgot to write the parenthesis in the sentence, so I compared a pointer function with a number.
Ok, my question:
Is there any way to change the interpreter ... | Interpreter more strict | Today, i lost a lot of time fixing a stupid error in my code. Very simplified, the problem was this:
def f():
return 2
2 == f
I forgot to write the parenthesis in the sentence, so I compared a pointer function with a number.
Ok, my question:
Is there any way to change the interpreter to be more stricted with the ... | [
"Python is a dynamic language, and the construct you have shown is completely valid (a function is not equal to 2). There is no strict mode.\n",
"The interpreter shouldn't issue a warning. f could be reassigned to an integer and then the check would totally makes sense:\nPython 2.6.2 (release26-maint, Apr 19 2009... | [
5,
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003034008_python.txt |
Q:
Convert Python to Haskell / Lambda calculus
What is the Python code in Haskell and Lambda calculus?
def f1():
x = 77
def f2():
print x
f2
f1
My attempt in lambda calculus
\x. 77 (\x.x)
A:
In Haskell:
f1 = f2
where x = 77
f2 = print x
Refactoring, since IO just confuses the issue:
... | Convert Python to Haskell / Lambda calculus | What is the Python code in Haskell and Lambda calculus?
def f1():
x = 77
def f2():
print x
f2
f1
My attempt in lambda calculus
\x. 77 (\x.x)
| [
"In Haskell:\nf1 = f2\n where x = 77\n f2 = print x\n\nRefactoring, since IO just confuses the issue:\nf1 = f2\n where x = 77\n f2 = x\n\nRefactoring:\nf1 = x\n where x = 77\n\nRefactoring, since you want the variable?\nf1 = (\\x -> x) 77\n\nBeta reduce:\nf1 = 77\n\nAnd you have your pr... | [
8,
3,
1,
1
] | [] | [] | [
"haskell",
"lambda",
"lambda_calculus",
"python"
] | stackoverflow_0001814061_haskell_lambda_lambda_calculus_python.txt |
Q:
Rapid spectral analysis of audio file using Python 2.6?
What I want to do is to have a subroutine that analyses every 200 milliseconds of a sound file which it is given and spits out the frequency intensity value (from 0 to 1 as a float) of a specific frequency range into an array which I later save. This value th... | Rapid spectral analysis of audio file using Python 2.6? | What I want to do is to have a subroutine that analyses every 200 milliseconds of a sound file which it is given and spits out the frequency intensity value (from 0 to 1 as a float) of a specific frequency range into an array which I later save. This value then goes on to be used as the opacity value for a graphic whic... | [
"You will first need to understand how sampling works, then you should use Scipy FFT routines (they are pretty fast) in order spit out frequency intensity values, then you can use Matplotlib to plot such graphics.\nSee here for an article about using Python to analyze sound files and here is a similar question abou... | [
3
] | [] | [] | [
"audio_analysis",
"fft",
"python"
] | stackoverflow_0003032472_audio_analysis_fft_python.txt |
Q:
Accessing an image from a webpage in PyQt4 QtWebkit
If a page has fully loaded on a QWebView, how can I get the data for a certain image (probably through the dom?)
A:
I'll try taking a stab at this:
If you want to get the url of an image using jQuery you could use an approach like this:
import sys
from PyQt4.Qt... | Accessing an image from a webpage in PyQt4 QtWebkit | If a page has fully loaded on a QWebView, how can I get the data for a certain image (probably through the dom?)
| [
"I'll try taking a stab at this:\nIf you want to get the url of an image using jQuery you could use an approach like this:\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtWebKit import *\napp = QApplication(sys.argv)\nweb = QWebView()\nweb.load(QUrl(\"http://google.com\"))\nframe = ... | [
1
] | [] | [] | [
"pyqt4",
"python",
"qtwebkit"
] | stackoverflow_0002793641_pyqt4_python_qtwebkit.txt |
Q:
Can a python view template be made to be 'safe/secure' if I make it user editable?
Say I need to have a templating system where a user can edit it online using an online editor.
So they can put if tags, looping tags etc., but ONLY for specific objects that I want to inject into the template.
Can this be made to be... | Can a python view template be made to be 'safe/secure' if I make it user editable? | Say I need to have a templating system where a user can edit it online using an online editor.
So they can put if tags, looping tags etc., but ONLY for specific objects that I want to inject into the template.
Can this be made to be safe from security issues?
i.e. them somehow outputing sql connection string informatio... | [
"Yes, use a template engine that has sandboxing features, like jinja2\n"
] | [
3
] | [] | [] | [
"django",
"python",
"security",
"templating"
] | stackoverflow_0003034133_django_python_security_templating.txt |
Q:
PyQt4 plugin in c++ application
How is it posible to load python script as plugin in qt based application?
The basic idea would be to make a class in c++
class b
{
virtual void method1();
virtual void method2();
}
and 'somehow' inherit it in python like
class c(b):
def method1:
#do something... | PyQt4 plugin in c++ application | How is it posible to load python script as plugin in qt based application?
The basic idea would be to make a class in c++
class b
{
virtual void method1();
virtual void method2();
}
and 'somehow' inherit it in python like
class c(b):
def method1:
#do something
def method2:
#do somethi... | [
"I think you'll first need to expose your C++ methods using Python C API or by using Boost::Python or Swig and then embed Python into your application in order to execute customized Python scripts.\n"
] | [
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0003026309_c++_python.txt |
Q:
Python/YACC: Resolving a shift/reduce conflict
I'm using PLY. Here is one of my states from parser.out:
state 3
(5) course_data -> course .
(6) course_data -> course . course_list_tail
(3) or_phrase -> course . OR_CONJ COURSE_NUMBER
(7) course_list_tail -> . , COURSE_NUMBER
(8) course_list_tai... | Python/YACC: Resolving a shift/reduce conflict | I'm using PLY. Here is one of my states from parser.out:
state 3
(5) course_data -> course .
(6) course_data -> course . course_list_tail
(3) or_phrase -> course . OR_CONJ COURSE_NUMBER
(7) course_list_tail -> . , COURSE_NUMBER
(8) course_list_tail -> . , COURSE_NUMBER course_list_tail
! shift/r... | [
"Your basic problem is that you need two tokens of lookahead to do what you want -- when the input seen so far is a course and the lookahead is a OR_CONJ you don't know whether to reduce the course to a course_data or shift without looking ahead two tokens to the token after the OR_CONJ. There are a number of ways... | [
4
] | [] | [] | [
"parsing",
"ply",
"python",
"yacc"
] | stackoverflow_0002939888_parsing_ply_python_yacc.txt |
Q:
Fastest python/C++ multimedia library
I'm using pyglet for my OpenGL based game but is it the fastest library out there which has a python wrapper? I could create a C++ extension and use any C++ multimedia library. Are there any C++ libraries that are worth investing time into or is it not worth the extra work?
Th... | Fastest python/C++ multimedia library | I'm using pyglet for my OpenGL based game but is it the fastest library out there which has a python wrapper? I could create a C++ extension and use any C++ multimedia library. Are there any C++ libraries that are worth investing time into or is it not worth the extra work?
Thank you.
| [
"Pygame is a python wrapper for the SDL library, which is widely used in game developing and provides OpenGL, sound and input management. To my knowledge at least SDL is quite fast, and the wrapper just encapsulates the binary functionality for python usage. Depending on your usage you can accomplish high speed.\n"... | [
1,
0
] | [] | [] | [
"c++",
"multimedia",
"opengl",
"python"
] | stackoverflow_0003033969_c++_multimedia_opengl_python.txt |
Q:
What's going on here? Repeating rows in random list of lists
I expected to get a grid of unique random numbers. Instead each row is the same sequence of numbers. What's going on here?
from pprint import pprint
from random import random
nrows, ncols = 5, 5
grid = [[0] * ncols] * nrows
for r in range(nrows):
... | What's going on here? Repeating rows in random list of lists | I expected to get a grid of unique random numbers. Instead each row is the same sequence of numbers. What's going on here?
from pprint import pprint
from random import random
nrows, ncols = 5, 5
grid = [[0] * ncols] * nrows
for r in range(nrows):
for c in range(ncols):
grid[r][c] = int(random() * 100)
pp... | [
"I think that this is because python uses a weak copy of the list when you call\ngrid = [...] * nrows\n\nI tried hard coding the list and it worked correctly:\n>>> grid = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]\n>>> for r in range(nrows):\n... for c in range(ncols):\n... grid[r... | [
2
] | [] | [] | [
"multidimensional_array",
"python",
"random"
] | stackoverflow_0003034469_multidimensional_array_python_random.txt |
Q:
how to set a fixed color bar for pcolor in python matplotlib?
I am using pcolor with a custom color map to plot a matrix of values. I set my color map so that low values are white and high values are red, as shown below. All of my matrices have values between 0 and 20 (inclusive) and I'd like 20 to always be pur... | how to set a fixed color bar for pcolor in python matplotlib? | I am using pcolor with a custom color map to plot a matrix of values. I set my color map so that low values are white and high values are red, as shown below. All of my matrices have values between 0 and 20 (inclusive) and I'd like 20 to always be pure red and 0 to always be pure white, even if the matrix has values ... | [
"A guess: Your colormap is probably fine. Try to adjust the vmin and vmax when plotting.\npylab.imshow(im, vmin=0, vmax=20)\n\n"
] | [
2
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0003034525_matplotlib_numpy_python_scipy.txt |
Q:
Set a script to automatically detect character encoding in a plain-text-file in Python?
I've set up a script that basically does a large-scale find-and-replace on a plain text document.
At the moment it works fine with ASCII, UTF-8, and UTF-16 (and possibly others, but I've only tested these three) encoded docume... | Set a script to automatically detect character encoding in a plain-text-file in Python? | I've set up a script that basically does a large-scale find-and-replace on a plain text document.
At the moment it works fine with ASCII, UTF-8, and UTF-16 (and possibly others, but I've only tested these three) encoded documents so long as the encoding is specified inside the script (the example code below specifies ... | [
"From the link J.F. Sebastian posted: try chardet.\nKeep in mind that in general it's impossible to detect the character encoding of every input file 100% reliably - in other words, there are possible input files which could be interpreted equally well as any of several character encodings, and there may be no way ... | [
4,
3,
1
] | [] | [] | [
"character_encoding",
"python",
"replace"
] | stackoverflow_0003034714_character_encoding_python_replace.txt |
Q:
Handling TclErrors in Python
In the following code I'll get the following error if I right click the window that pops up. Then go down to the very bottom entry widget then delete it's contents. It seems to be giving me a TclError. How do I go about handeling such an error?
The Error
Exception in Tkinter callback
... | Handling TclErrors in Python | In the following code I'll get the following error if I right click the window that pops up. Then go down to the very bottom entry widget then delete it's contents. It seems to be giving me a TclError. How do I go about handeling such an error?
The Error
Exception in Tkinter callback
Traceback (most recent call last):... | [
"def I (self,event):\n S1 = TL.entryVariableS.get()\n TL.sclS.set(S1)\n TL.sclS.set(TL.sclS.get())\n S1 = TL.entryVariableS.get()\n TL.sclS.set(S1)\n\nTL.entryVariableS.get() is returning \"\" (empty string); you will need to check for that and handle them appropriately (either gives default value or... | [
0
] | [] | [] | [
"error_handling",
"python",
"tkinter"
] | stackoverflow_0003033749_error_handling_python_tkinter.txt |
Q:
How to make django test framework read from live database?
I realize there's a similar question here, but this one has a different approach: I have a django app that does queries over data indexed with djapian ; I'd like to write unit tests for this app's search component, and, obviously, I'd need the django setti... | How to make django test framework read from live database? | I realize there's a similar question here, but this one has a different approach: I have a django app that does queries over data indexed with djapian ; I'd like to write unit tests for this app's search component, and, obviously, I'd need the django settings module and all connections with the database active, so the ... | [
"Reading the test cases for djapian I found something really interesting: what those guys do is use the setUp method for the TestCase class: they create an object and then use the update method for the indexer, so they effectively have a document to search for and a way to write controlled query tests!\nFor the cur... | [
2
] | [] | [] | [
"django",
"python",
"xapian"
] | stackoverflow_0003034509_django_python_xapian.txt |
Q:
How to return a value when destroying/cleaning-up an object instance
When I initiate a class in Python, I give it some values. I then call method in the class which does something. Here's a snippet:
class TestClass():
def __init__(self):
self.counter = 0
def doSomething(self):
self.counter ... | How to return a value when destroying/cleaning-up an object instance | When I initiate a class in Python, I give it some values. I then call method in the class which does something. Here's a snippet:
class TestClass():
def __init__(self):
self.counter = 0
def doSomething(self):
self.counter = self.counter + 1
print 'Hiya'
if __name__ == "__main__":
ob... | [
"Doing actions upon object destruction is generally frowned upon. Python offers a __del__ function, but it may not be called in certain instances.\nIf you were to do something with the counter variable, what would it be? Where would the data go?\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003035284_python.txt |
Q:
How to print string in this way
For every string, I need to print # each 6 characters.
For example:
example_string = "this is an example string. ok ????"
myfunction(example_string)
"this i#s an e#xample# strin#g. ok #????"
What is the most efficient way to do that ?
A:
How about this?
'#'.join( [example_strin... | How to print string in this way | For every string, I need to print # each 6 characters.
For example:
example_string = "this is an example string. ok ????"
myfunction(example_string)
"this i#s an e#xample# strin#g. ok #????"
What is the most efficient way to do that ?
| [
"How about this?\n'#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)])\n\nIt runs pretty quickly, too. On my machine, five microseconds per 100-character string:\n>>> import timeit\n>>> timeit.Timer( \"'#'.join([s[a:a+6] for a in range(0,len(s),6)])\", \"s='x'*100\").timeit()\n4.9556539058685... | [
9,
4,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003035239_python_regex.txt |
Q:
Keep history in django to draw graphs
I am looking for the best way to have an history of my models (interger & float fields) in Django.
I read Keeping a history of data changes in database and it seems that triggers are the best option.
My idea is to stay database agnostic if possible.
How do you approach this is... | Keep history in django to draw graphs | I am looking for the best way to have an history of my models (interger & float fields) in Django.
I read Keeping a history of data changes in database and it seems that triggers are the best option.
My idea is to stay database agnostic if possible.
How do you approach this issues in your django code ?
TIA.
| [
"If you're not going to go with Triggers, Signals do a similar job — it'll (probably) be less efficient than using a trigger, but you can attach a post_save signal to your models you want to track and do all the processing you need there.\n",
"You should check out Django Reversion app. It's probably the easiest w... | [
0,
0
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0003032337_django_python_sql.txt |
Q:
Plotting a cumulative graph of python datetimes
Say I have a list of datetimes, and we know each datetime to be the recorded time of an event happening.
Is it possible in matplotlib to graph the frequency of this event occurring over time, showing this data in a cumulative graph (so that each point is greater or e... | Plotting a cumulative graph of python datetimes | Say I have a list of datetimes, and we know each datetime to be the recorded time of an event happening.
Is it possible in matplotlib to graph the frequency of this event occurring over time, showing this data in a cumulative graph (so that each point is greater or equal to all of the points that went before it), witho... | [
"This should work for you:\ncounts = arange(0, len(list_of_dates))\nplot(list_of_dates, counts)\n\nYou can of course give any of the usual options to the plot call to make the graph look the way you want it. (I'll point out that matplotlib is very adept at handling dates and times.)\nAnother option would be the his... | [
13,
6
] | [
"I just use chart director from advanced software engineering. Really easy to deal with especially with dates. They have lots of examples too in python.\n"
] | [
-2
] | [
"datetime",
"graph",
"matplotlib",
"python"
] | stackoverflow_0003034162_datetime_graph_matplotlib_python.txt |
Q:
how to send F2 key to remote host using python
I have to send F2 key to telnet host. How do I send it using python...using getch() I found that the character < used for the F2 key but when sending >, its not working. I think there is a way to send special function keys but I am not able to find it. If somebody kno... | how to send F2 key to remote host using python | I have to send F2 key to telnet host. How do I send it using python...using getch() I found that the character < used for the F2 key but when sending >, its not working. I think there is a way to send special function keys but I am not able to find it. If somebody knows please help me. Thanks in advance
| [
"Extended keys (non-alphanumeric or symbol) are composed of a sequence of single characters, with the sequence depending on the terminal you have told the telnet server you are using. You will need to send all characters in the sequence in order to make it work. Here, using od -c <<< 'CtrlVF2' I was able to see a s... | [
4,
3
] | [] | [] | [
"python",
"telnet"
] | stackoverflow_0003035390_python_telnet.txt |
Q:
Which programming language for compute-intensive trading portfolio simulation?
I am building a trading portfolio management system that is responsible for production, optimization, and simulation of non-high frequency trading portfolios (dealing with 1min or 3min bars of data, not tick data).
I plan on employing ... | Which programming language for compute-intensive trading portfolio simulation? | I am building a trading portfolio management system that is responsible for production, optimization, and simulation of non-high frequency trading portfolios (dealing with 1min or 3min bars of data, not tick data).
I plan on employing Amazon web services to take on the entire load of the application.
I have four choic... | [
"Pick the language you are most familiar with. If you know them all equally and speed is a real concern, pick C. \n",
"While I am a huge fan of Python and personaly I'm not a great lover of Java, in this case I have to concede that Java is the right way to go.\nFor many projects Python's performance just isn't a ... | [
6,
5,
4,
4,
4,
0
] | [
"I would go with pypy. If not, http://lolcode.com/.\n"
] | [
-1
] | [
"java",
"python",
"trading"
] | stackoverflow_0003031225_java_python_trading.txt |
Q:
python global variable not working in apache
I am facing issue with the global variable, when i run in the django development server it works fine, but in apache it doesn't work
here is the code below:
red= "/project3/test/"
def showAddRecipe(request):
#global objc
if "userid" in request.session:
... | python global variable not working in apache | I am facing issue with the global variable, when i run in the django development server it works fine, but in apache it doesn't work
here is the code below:
red= "/project3/test/"
def showAddRecipe(request):
#global objc
if "userid" in request.session:
objc["ErrorMsgURL"]= ""
try:
... | [
"I would guess that you use Apache's CGI capabilities. That means that with each request the script is started anew. Which means that the global variable is initialized with each call.\nApart from that it isn't really a good idea to use globals to store what is in essence session data (with a session, and thus stat... | [
3,
0,
0
] | [] | [] | [
"apache",
"django",
"global_variables",
"python"
] | stackoverflow_0003035776_apache_django_global_variables_python.txt |
Q:
Storing task state between multiple django processes
I am building a logging-bridge between rabbitmq messages and Django application to store background task state in the database for further investigation/review, also to make it possible to re-publish tasks via the Django admin interface.
I guess it's nothing fan... | Storing task state between multiple django processes | I am building a logging-bridge between rabbitmq messages and Django application to store background task state in the database for further investigation/review, also to make it possible to re-publish tasks via the Django admin interface.
I guess it's nothing fancy, just a standard Producer-Consumer pattern.
Web applic... | [
"This sounds brittle to me: You have a web app which posts to a queue and then inserts the initial state into the database. What happens if the consumer processes the message before the web app can commit the initial state?\nWhat happens if the web app tries to insert the new state while the DB is locked by the con... | [
0,
0
] | [] | [] | [
"django",
"multiprocessing",
"python",
"rabbitmq",
"transactions"
] | stackoverflow_0003036049_django_multiprocessing_python_rabbitmq_transactions.txt |
Q:
Emacs 23 hangs on python mode when typing string block """
My Emacs hangs (Ubuntu 9 + Emacs 23 + Pyflakes) when I type """ quotes for string blocks.
Anybody experienced the same problem? I think, it may not be an Emacs problem but some Python mode or Pyflakes which I use it for error checking.
Anybody got around t... | Emacs 23 hangs on python mode when typing string block """ | My Emacs hangs (Ubuntu 9 + Emacs 23 + Pyflakes) when I type """ quotes for string blocks.
Anybody experienced the same problem? I think, it may not be an Emacs problem but some Python mode or Pyflakes which I use it for error checking.
Anybody got around the issue? It is a really frustrating experience.
| [
"latest pyflakes in development mode fixed this problem for me. Thanks all\nsudo easy_install -U pyflakes\n",
"are you using the external python-mode (from package python-mode) or the internal python mode ? I use pyflakes with the internal emacs python mode without any problems and this is my configuration :\n(... | [
3,
1,
0
] | [] | [] | [
"emacs",
"pyflakes",
"python"
] | stackoverflow_0001406213_emacs_pyflakes_python.txt |
Q:
python unit testing os.remove fails file system
Am doing a bit of unit testing on a function which attempts to open a new file, but should fail if the file already exists. when the function runs sucessfully, the new file is created, so i want to delete it after every test run, but it doesn't seem to be working:
c... | python unit testing os.remove fails file system | Am doing a bit of unit testing on a function which attempts to open a new file, but should fail if the file already exists. when the function runs sucessfully, the new file is created, so i want to delete it after every test run, but it doesn't seem to be working:
class MyObject_Initialisation(unittest.TestCase):
... | [
"If you're just looking for a temporary file, have a look at tempfile - this should handle the clean-up all on its own. \n",
"Do you remember to explicitly close file handler that operates on TEMPORARY_FILE_NAME?\nFrom Python Documentation:\n\nOn Windows, attempting to remove a\n file that is in use causes an\n ... | [
2,
2
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0003036487_python_unit_testing.txt |
Q:
Mailboxes with Stackless
In my stackless application I'd like to have Erlang style message box queues. Instead of mandating that sending tasklets are blocked until the receiving tasklet is ready to receive, I'd like to have the sending tasklet to queue up the message in the receiver's message box, and be able to w... | Mailboxes with Stackless | In my stackless application I'd like to have Erlang style message box queues. Instead of mandating that sending tasklets are blocked until the receiving tasklet is ready to receive, I'd like to have the sending tasklet to queue up the message in the receiver's message box, and be able to wake the receiver if it's sleep... | [
"This may not be exactly what you are looking for, but still worth a shot:\ngevent is a Python library that provides high-level APIs over greenlets, which are similar to tasklets (actually, it's a spin-off of Stackless Python. There are some differences, though: you don't need a special interpreter and a few more).... | [
2
] | [] | [] | [
"python",
"stackless"
] | stackoverflow_0002976049_python_stackless.txt |
Q:
Regular expressions in a Python find-and-replace script? Update
I'm new to Python scripting, so please forgive me in advance if the answer to this question seems inherently obvious.
I'm trying to put together a large-scale find-and-replace script using Python. I'm using code similar to the following:
infile = sys.... | Regular expressions in a Python find-and-replace script? Update | I'm new to Python scripting, so please forgive me in advance if the answer to this question seems inherently obvious.
I'm trying to put together a large-scale find-and-replace script using Python. I'm using code similar to the following:
infile = sys.argv[1]
charenc = sys.argv[2]
outFile=infile+'.output'
findreplace =... | [
">>> import re\n>>> s = \"\"\"Title: This is the title\n... Author: This is the author\n... Date: This is the date\"\"\"\n>>> p = re.compile(r'^(\\w+):\\s*(.+)$', re.M)\n>>> print p.sub(r'\\\\\\1{\\2}', s)\n\\Title{This is the title}\n\\Author{This is the author}\n\\Date{This is the date}\n\nTo change the case, use... | [
5,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003036706_python_regex.txt |
Q:
Using popen, but text looks weird - Python
I'm using os.popen() in order to run a few commands.
This is what "man ls" looks like:
Any ideas why the text is displayed as such. I tried both Arial and Consolas fonts.
Help would be amazing! Thanks
A:
Those are backspace characters: man is trying to backspace and re... | Using popen, but text looks weird - Python | I'm using os.popen() in order to run a few commands.
This is what "man ls" looks like:
Any ideas why the text is displayed as such. I tried both Arial and Consolas fonts.
Help would be amazing! Thanks
| [
"Those are backspace characters: man is trying to backspace and reprint characters to get bolding, or underscores plus backspaces to get underlining.\nThe man man page says:\n\nTo get a plain text version of a man page, without backspaces and underscores, try\n# man foo | col -b > foo.mantxt \n\nYou could also do a... | [
3
] | [] | [] | [
"command_line",
"popen",
"python"
] | stackoverflow_0003036822_command_line_popen_python.txt |
Q:
Magic Methods in Python
I'm kind of new to Python and I wonder if there is a way to create something like the magic methods in PHP (http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods)
My aim is to ease the access of child classes in my model. I basically have a parent clas... | Magic Methods in Python | I'm kind of new to Python and I wonder if there is a way to create something like the magic methods in PHP (http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods)
My aim is to ease the access of child classes in my model. I basically have a parent class that has n child classes. T... | [
"Return an object for parent_class.title which has a __getitem__ method.\nclass parent_class:\n def __init__(self):\n self.title = multilang(\"hello world\");\n\nclass multilang:\n def __init__(self, text):\n pass\n def __getitem__(self, key):\n if key == 'en':\n return \"he... | [
4,
1
] | [] | [] | [
"magic_methods",
"python"
] | stackoverflow_0003036895_magic_methods_python.txt |
Q:
problem installing mysqldb for python2.6
My mysql database is located on a remote machine... So i dont have any local copy of mysql on my local machine.. i get the registry key error... (file not found)...
serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['registry_key'])
WindowsError: [Error 2] The ... | problem installing mysqldb for python2.6 | My mysql database is located on a remote machine... So i dont have any local copy of mysql on my local machine.. i get the registry key error... (file not found)...
serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['registry_key'])
WindowsError: [Error 2] The system cannot find the file specified
I think... | [
"You will indeed need a local copy of MySQL in order to compile the MySQL extension for Python. This page seems to contain a step-by-step guide for Windows.\nHowever, you might have some luck with a pre-compiled MySQL module. This should work for Python 2.6.\n"
] | [
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003036845_mysql_python.txt |
Q:
syntax error in python:
I'm learning python. It gives syntax error in this script. I'm unable to figure out.
import exceptions
class FOUND(Exception): pass
x = [1,2,3,4,56,73,29,35,12,32,63,12,76,75,89]
while True:
try:
test = int(raw_input('Enter integer to be checked in list:'))
count = -1... | syntax error in python: | I'm learning python. It gives syntax error in this script. I'm unable to figure out.
import exceptions
class FOUND(Exception): pass
x = [1,2,3,4,56,73,29,35,12,32,63,12,76,75,89]
while True:
try:
test = int(raw_input('Enter integer to be checked in list:'))
count = -1
for y in x:
... | [
"print without brackets is from python 2, if you are using python 3, you need to use print().\nYou can't format an exception as %d - %d is for integers.\n",
"Try except ValueError as e:, the older syntax you use is invalid in Python 3.\n",
"You need an empty line between the class ... and x = ...\n",
"Your co... | [
5,
2,
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003037014_python_python_3.x.txt |
Q:
Please help me optimize my Python code
Beginner here! Forgive me in advance for raising what is probably an incredibly simple problem.
I've been trying to put together a Python script that runs multiple find-and-replace actions and a few similar things on a specified plain-text file. It works, but from a programmi... | Please help me optimize my Python code | Beginner here! Forgive me in advance for raising what is probably an incredibly simple problem.
I've been trying to put together a Python script that runs multiple find-and-replace actions and a few similar things on a specified plain-text file. It works, but from a programming perspective I doubt it works well. How wo... | [
"For the last three replacements, the for-loop seems to be unnecessary, since the loop body doesn't use the loop variable. Also it is not necessary to assign the result to a temporary outtext variable, it can be directly assigned to s.\nThese changes make the code much more concise:\nfor couple in findreplace:\n ... | [
4,
2,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0003037112_optimization_python.txt |
Q:
Python Threading, loading one thread after another
I'm working on a media player and am able to load in a single .wav and play it. As seen in the code below.
foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE)
foo.ShowModal()
queue = foo.Get... | Python Threading, loading one thread after another | I'm working on a media player and am able to load in a single .wav and play it. As seen in the code below.
foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE)
foo.ShowModal()
queue = foo.GetPaths()
self.playing_thread = threading.Thread(target... | [
"Since is using wx.python, use a Delayedresult, look at wx demos for a complete example.\nFull minimal example:\nimport wx\nimport wx.lib.delayedresult as inbg\nimport time\n\nclass Player(wx.Frame):\n def __init__(self):\n\n\n self.titulo = \"Music Player\"\n wx.Frame.__init__(self, None, -1, self.titulo... | [
0
] | [] | [] | [
"multithreading",
"python",
"wxpython"
] | stackoverflow_0003037150_multithreading_python_wxpython.txt |
Q:
Run a shell command from Django
I'm developing a web page in Django (using apache server) that needs to call a shell command to enable/dissable some daemons. I'm try to do it with
os.system(service httpd restart 1>$HOME/out 2>$HOME/error)
and this command doesn't return anything. Any idea how can i fix this?
A:
... | Run a shell command from Django | I'm developing a web page in Django (using apache server) that needs to call a shell command to enable/dissable some daemons. I'm try to do it with
os.system(service httpd restart 1>$HOME/out 2>$HOME/error)
and this command doesn't return anything. Any idea how can i fix this?
| [
"I'll skip the part where I strongly advise you about the implications of having a web application starting and stopping system processes and try to answer the question.\nYour django application shouldn't run with root user, which should probably be needed to start and stop services. You can probably overcome this ... | [
10,
4,
3
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0003037068_apache_django_python.txt |
Q:
Python - calculate multinomial probability density functions on large dataset?
I originally intended to use MATLAB to tackle this problem but the in-built function has limitations that do not suit my goal. The same limitation occurs in NumPy.
I have two tab-delimited files. The first is a file showing amino acid r... | Python - calculate multinomial probability density functions on large dataset? | I originally intended to use MATLAB to tackle this problem but the in-built function has limitations that do not suit my goal. The same limitation occurs in NumPy.
I have two tab-delimited files. The first is a file showing amino acid residue, frequency and count for an in-house database of protein structures, i.e.
A ... | [
"This might be tangential to your original question, but I strongly advise against calculating factorials explicitly due to overflows. Instead, make use of the fact that factorial(n) = gamma(n+1), use the logarithm of the gamma function and use additions instead of multiplications, subtractions instead of divisions... | [
9
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0003037113_data_structures_python.txt |
Q:
sorting words in python
Is it possible in python to sort a list of words not according to the english alphabet but according to a self created alphabet.
A:
You can normally define custom comparison methods so the sort is performed within your restrictions. I've never coded a line of Python in my life, but it's s... | sorting words in python | Is it possible in python to sort a list of words not according to the english alphabet but according to a self created alphabet.
| [
"You can normally define custom comparison methods so the sort is performed within your restrictions. I've never coded a line of Python in my life, but it's similar enough to Ruby for me to notice that the following excerpt from this page might help you:\nalphabet = \"zyxwvutsrqpomnlkjihgfedcba\"\n\ninputWords = [\... | [
13
] | [] | [] | [
"python"
] | stackoverflow_0003037407_python.txt |
Q:
How do I escape % from python mysql query
How do I escape the % from a mysql query in python.
For example
query = """SELECT DATE_FORMAT(date_time,'%Y-%m') AS dd
FROM some_table
WHERE some_col = %s
AND other_col = %s;"""
cur.execute(query, (pram1, pram2))
gives me a "ValueError: unsupported format character 'Y'" ... | How do I escape % from python mysql query | How do I escape the % from a mysql query in python.
For example
query = """SELECT DATE_FORMAT(date_time,'%Y-%m') AS dd
FROM some_table
WHERE some_col = %s
AND other_col = %s;"""
cur.execute(query, (pram1, pram2))
gives me a "ValueError: unsupported format character 'Y'" exception.
How do I get mysqldb to ignore the %... | [
"Literal escaping is recommended by the docs:\n\nNote that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%.\n\n"
] | [
45
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003037581_mysql_python.txt |
Q:
Convert sets to frozensets as values of a dictionary
I have dictionary that is built as part of the initialization of my object. I know that it will not change during the lifetime of the object. The dictionary maps keys to sets. I want to convert all the values from sets to frozensets, to make sure they do not get... | Convert sets to frozensets as values of a dictionary | I have dictionary that is built as part of the initialization of my object. I know that it will not change during the lifetime of the object. The dictionary maps keys to sets. I want to convert all the values from sets to frozensets, to make sure they do not get changed. Currently I do that like this:
for key in self.m... | [
"Given, for instance,\n>>> d = {'a': set([1, 2]), 'b': set([3, 4])}\n>>> d\n{'a': set([1, 2]), 'b': set([3, 4])}\n\nYou can do the conversion in place as\n>>> d.update((k, frozenset(v)) for k, v in d.iteritems())\n\nWith the result\n>>> d\n{'a': frozenset([1, 2]), 'b': frozenset([3, 4])}\n\n",
"If you have to do ... | [
6,
1,
1
] | [] | [] | [
"dictionary",
"python",
"set"
] | stackoverflow_0003037500_dictionary_python_set.txt |
Q:
Parsing logs using regex
I need to find all invocations of some logging macros in the code. The macro invocation is of the form:
DEBUG[1-5] ( "methodName: the logged message", arguments)
But the new versions of the macros are prepending the name of the method automatically, so my task is to write a Python script ... | Parsing logs using regex | I need to find all invocations of some logging macros in the code. The macro invocation is of the form:
DEBUG[1-5] ( "methodName: the logged message", arguments)
But the new versions of the macros are prepending the name of the method automatically, so my task is to write a Python script that will remove the duplicate... | [
"try this, written in java, but you can transform it to python\nreplaceAll(\"(DEBUG[1-5]\\s*\\\\(\\\")\\\"[^:]+:\\\\s+([^;]+)\", \"$1$2\");\n\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003037932_python_regex.txt |
Q:
How to add wsse:Security, UsernameToken header to a SOAP request in ZSI, Python?
Is there a way to add the wsse:Security, UsernameToken header to the SOAP requests in ZSI, Python? I searched on the web, but couldn't find an answer.
A:
After searching further, I'm convinced and planning to use suds, https://fedor... | How to add wsse:Security, UsernameToken header to a SOAP request in ZSI, Python? | Is there a way to add the wsse:Security, UsernameToken header to the SOAP requests in ZSI, Python? I searched on the web, but couldn't find an answer.
| [
"After searching further, I'm convinced and planning to use suds, https://fedorahosted.org/suds/, which seems to be user-friendly, feature-rich, and provides classes and methods to add the UsernameToken to the SOAP header.\nSuds Documentation on WS-Security: https://fedorahosted.org/suds/wiki/Documentation#WS-SECUR... | [
4
] | [] | [] | [
"python",
"usernametoken",
"ws_security",
"zsi"
] | stackoverflow_0003036881_python_usernametoken_ws_security_zsi.txt |
Q:
Command line tool in python in a fixed root directory
I would like to install my python application as a command line tool that should work entirelly inside the install directory (for example C:\Python26\Lib\site-packages\application)
The problem is I would like to reffer in runtime to the submodules and resource... | Command line tool in python in a fixed root directory | I would like to install my python application as a command line tool that should work entirelly inside the install directory (for example C:\Python26\Lib\site-packages\application)
The problem is I would like to reffer in runtime to the submodules and resources from within the application directory three. If I install ... | [
"Not sure if this is what you're after but doing this might work.\nimport os\ndir_of_current_module = os.path.dirname(__file__)\n\nOnce you know the dir, you can chdir() to it or do what you want. Remember: You might not always have permissions to do stuff there.\n"
] | [
1
] | [] | [] | [
"command_line",
"installation",
"python"
] | stackoverflow_0003038338_command_line_installation_python.txt |
Q:
Environment variables
I use the module mechanize in order to log in a site. When I import twill.commands without any other apparent use, some debug messages [0] are displayed [1]. When I delete it, these messages disappear.
How can I see what is changed in the environment in order to emulate it and remove this dep... | Environment variables | I use the module mechanize in order to log in a site. When I import twill.commands without any other apparent use, some debug messages [0] are displayed [1]. When I delete it, these messages disappear.
How can I see what is changed in the environment in order to emulate it and remove this dependency?
[0] Using the logg... | [
"My guess - without digging in the libraries - is that twill is instantiating a logger, and mechanize is doing the Right Thing for a library, logging if logging has been turned on, not if not.\nTo enable the logging of mechanize configure a logging.basicConfig root in your application code.\n",
"twill uses mechan... | [
1,
1
] | [] | [] | [
"logging",
"mechanize",
"python",
"twill"
] | stackoverflow_0003038483_logging_mechanize_python_twill.txt |
Q:
Python + Expat: Error on entities
I have written a small function, which uses ElementTree and xpath to extract the text contents of certain elements in an xml file:
#!/usr/bin/env python2.5
import doctest
from xml.etree import ElementTree
from StringIO import StringIO
def parse_xml_etree(sin, xpath):
"""
Tak... | Python + Expat: Error on entities | I have written a small function, which uses ElementTree and xpath to extract the text contents of certain elements in an xml file:
#!/usr/bin/env python2.5
import doctest
from xml.etree import ElementTree
from StringIO import StringIO
def parse_xml_etree(sin, xpath):
"""
Takes as input a stream containing XML and a... | [
"� is not in the legal character range defined by the XML spec. Alas, my Python skills are pretty rudimentary, so I'm not much help there.\n",
"� is not a valid XML character. Ideally, you'd be able to get the creator of the file to change their process so that the file was not invalid like this.\nIf you m... | [
6,
4
] | [] | [] | [
"elementtree",
"expat_parser",
"parsing",
"python",
"xml"
] | stackoverflow_0003038798_elementtree_expat_parser_parsing_python_xml.txt |
Q:
Download Videos from Youtube with Python
I am hoping to write a script that will allow for the detection of video on a url and provide a download link to a *flv for google chrome.
Anyone have any suggestions were to start and get a footing?
A:
if you don't want to reinvent the wheel: http://bitbucket.org/rg3/you... | Download Videos from Youtube with Python | I am hoping to write a script that will allow for the detection of video on a url and provide a download link to a *flv for google chrome.
Anyone have any suggestions were to start and get a footing?
| [
"if you don't want to reinvent the wheel: http://bitbucket.org/rg3/youtube-dl\n"
] | [
4
] | [] | [] | [
"google_chrome",
"python",
"youtube"
] | stackoverflow_0003038979_google_chrome_python_youtube.txt |
Q:
unevenly centered subplots in matplotlib in Python?
I am plotting a simple pair of subplots in matplotlib that are for some reason unevenly centered. I plot them as follows:
plt.figure()
# first subplot
s1 = plt.subplot(2, 1, 1)
plt.bar([1, 2, 3], [4, 5, 6])
# second subplot
s2 = plt.subplot(2, 1, 2)
plt.pcolor(ra... | unevenly centered subplots in matplotlib in Python? | I am plotting a simple pair of subplots in matplotlib that are for some reason unevenly centered. I plot them as follows:
plt.figure()
# first subplot
s1 = plt.subplot(2, 1, 1)
plt.bar([1, 2, 3], [4, 5, 6])
# second subplot
s2 = plt.subplot(2, 1, 2)
plt.pcolor(rand(5,5))
# add colorbar
plt.colorbar()
# square axes
ax... | [
"Well, this probably isn't exactly what you want, but it'll work:\nfrom numpy.random import rand\nimport matplotlib.pyplot as plt\n\nplt.figure()\n# first subplot\ns1 = plt.subplot(2, 2, 2)\nplt.bar([1, 2, 3], [4, 5, 6])\n# second subplot\ns2 = plt.subplot(2, 2, 4)\nplt.pcolor(rand(5,5))\n\n# square axes\naxes_squa... | [
2,
0
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0003034858_matplotlib_numpy_python_scipy.txt |
Q:
displaying a colored 2d array in matplotlib in Python
I'd like to plot a 2-d matrix from numpy as a colored matrix in Matplotlib. I have the following 9-by-9 array:
my_array = diag(ones(9))
# plot the array
pcolor(my_array)
I'd like to set the first three elements of the diagonal to be a certain color, the next... | displaying a colored 2d array in matplotlib in Python | I'd like to plot a 2-d matrix from numpy as a colored matrix in Matplotlib. I have the following 9-by-9 array:
my_array = diag(ones(9))
# plot the array
pcolor(my_array)
I'd like to set the first three elements of the diagonal to be a certain color, the next three to be a different color, and the last three a differ... | [
"To have the elements be different colors, assign them different values:\nmy_array = diag([1,1,1,2,2,2,3,3,3])\n\nTo specify the colors, try:\nfrom matplotlib.colors import ListedColormap, NoNorm\ncmap = ListedColormap(['#E0E0E0', '#FF8C00', '#8c00FF', '#00FF8C'])\npcolor(my_array,cmap=cmap,norm=NoNorm())\n\nThe no... | [
2
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0003034363_matplotlib_numpy_python_scipy.txt |
Q:
drawing just half of a matrix in matplotlib with python
How can I draw only half of a matrix, e.g. the upper / lower part of a matrix, with pcolor for example?
Suppose I have a n x n matrix and I draw it using pcolor(my_matrix). I want only the lower half to be shown since other values are redundant. How can t... | drawing just half of a matrix in matplotlib with python | How can I draw only half of a matrix, e.g. the upper / lower part of a matrix, with pcolor for example?
Suppose I have a n x n matrix and I draw it using pcolor(my_matrix). I want only the lower half to be shown since other values are redundant. How can this be done?
thanks.
| [
"Is it OK to plot zeros in the other half?\npcolor(mat*tri(*shape(mat)))\n\n",
"Use set_ylim:\nX = scipy.rand(10,10)\nf = pylab.figure()\nax = f.add_subplot(1,1,1)\nax.pcolor(X)\nax.set_ylim([0,5])\nf.show()\n\n"
] | [
1,
0
] | [] | [] | [
"matplotlib",
"python",
"scipy"
] | stackoverflow_0003039088_matplotlib_python_scipy.txt |
Q:
Convert url for crawler
I'm working on a crawler. Usually, when i type url1 in my browser, browser converts it to url2.
How can i do this in Python?
url1: www.odevsitesi.com/ara.asp?kelime=doğanın dengesinin bozulması
url2: www.odevsitesi.com/ara.asp?kelime=do%F0an%FDn%20dengesinin%20bozulmas%FD
A:
You need to p... | Convert url for crawler | I'm working on a crawler. Usually, when i type url1 in my browser, browser converts it to url2.
How can i do this in Python?
url1: www.odevsitesi.com/ara.asp?kelime=doğanın dengesinin bozulması
url2: www.odevsitesi.com/ara.asp?kelime=do%F0an%FDn%20dengesinin%20bozulmas%FD
| [
"You need to properly encode the URL (iso-8859-9 in your case), separate it into parts, urllib.quote the query part, and put it together again. I.e.:\n>>> import urlparse\n>>> import urllib\n>>> x = u'http://www.odevsitesi.com/ara.asp?kelime=doğanın dengesinin bozulması' \n>>> y = x.encode('iso-8859-9')\n>>> # jus... | [
5,
4
] | [] | [] | [
"python",
"url"
] | stackoverflow_0003039355_python_url.txt |
Q:
How can you print a string using raw_unicode_escape encoding in python 3?
The following code with fail in Python 3.x with TypeError: must be str, not bytes because now encode() returns bytes and print() expects only str.
#!/usr/bin/python
from __future__ import print_function
str2 = "some unicode text"
print(str2.... | How can you print a string using raw_unicode_escape encoding in python 3? | The following code with fail in Python 3.x with TypeError: must be str, not bytes because now encode() returns bytes and print() expects only str.
#!/usr/bin/python
from __future__ import print_function
str2 = "some unicode text"
print(str2.encode('raw_unicode_escape'))
How can you print a Unicode string escaped repre... | [
"I'd just use:\nprint(str2.encode('raw_unicode_escape').decode('ascii'))\n\nif you want identical code in Python 3 and Python 2.6 (otherwise you could use repr in 2.6 and ascii in Python 3, but that's not really \"identical\";-).\n",
"I can't reproduce your issue, please see previous revisions of this answer for ... | [
5,
1,
0
] | [] | [] | [
"python",
"python_3.x",
"unicode"
] | stackoverflow_0003038618_python_python_3.x_unicode.txt |
Q:
How does Vista Recycle bin work?
I am trying to write a python module to move files to the 'Recycle Bin' on both Mac and PC.
Is there a way, only from the commandline (and yes, I mean using absloutly no C#/C++/etc) to move a file into the Recycle Bin, and have it appear as a file trashed by drag and drop (or dele... | How does Vista Recycle bin work? | I am trying to write a python module to move files to the 'Recycle Bin' on both Mac and PC.
Is there a way, only from the commandline (and yes, I mean using absloutly no C#/C++/etc) to move a file into the Recycle Bin, and have it appear as a file trashed by drag and drop (or deleted via SHFileOperation, etc).
| [
"You should use the SHFileOperation function or, on Vista, the IFileOperation interface (as pointed out by gix below).\nFrom the remarks on SHFileOperation:\n\nWhen used to delete a file, SHFileOperation permanently deletes the file unless you set the FOF_ALLOWUNDO flag in the fFlags member of the SHFILEOPSTRUCT st... | [
5,
5,
3
] | [
"It looks like this mailing list entry might help you.\n"
] | [
-1
] | [
"python",
"recycle_bin",
"windows_vista"
] | stackoverflow_0000613246_python_recycle_bin_windows_vista.txt |
Q:
can't use appcfg.py update gae
recently i want to upload GAppProxy to GAE.
but when i use the appcfg.py to update the files,there comes an error,it was:
urllib2.URLError: urlopen error [Errno 8] _ssl.c:480: EOF occurred in
violation of protocol
i don't know why
PS:i live in china,and may be because of the GFW.
... | can't use appcfg.py update gae | recently i want to upload GAppProxy to GAE.
but when i use the appcfg.py to update the files,there comes an error,it was:
urllib2.URLError: urlopen error [Errno 8] _ssl.c:480: EOF occurred in
violation of protocol
i don't know why
PS:i live in china,and may be because of the GFW.
and when i use the type :appengine.g... | [
"As per this SO question, the issue is discussed here and the solution is to set proxies, e.g. in Windows on the command line:\nset HTTP_PROXY=http://google.cn:80 \nset HTTPS_PROXY=http://google.cn:80 \n\n(or however you set proxies for http and https on your platform, which you don't mention).\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003038518_python.txt |
Q:
Python encoding for pipe.communicate
I'm calling pipe.communicate from Python's subprocess module from Python 2.6. I get the following error from this code:
from subprocess import Popen
pipe = Popen(cwd)
pipe.communicate( data )
For an arbitrary cwd, and where data that contains unicode (specifically 0xE9):
Exe... | Python encoding for pipe.communicate | I'm calling pipe.communicate from Python's subprocess module from Python 2.6. I get the following error from this code:
from subprocess import Popen
pipe = Popen(cwd)
pipe.communicate( data )
For an arbitrary cwd, and where data that contains unicode (specifically 0xE9):
Exec. exception: 'ascii' codec can't encode c... | [
"I may have solved this by changing:\npipe.communicate( data )\n\nto \npipe.communicate( data.encode('utf8') )\n\nThough I stand to be corrected!\nBrian\n"
] | [
14
] | [] | [] | [
"encoding",
"popen",
"python",
"subprocess",
"unicode"
] | stackoverflow_0003040101_encoding_popen_python_subprocess_unicode.txt |
Q:
Cannot get variable.replace working properly
I am trying to replace a string with a new string in a python file and write the new string permanently to it. When I run the below script it removes part of the string and not all of it. The string in the file is:
self.id = "027FC8EBC2D1"
And the script I have to repl... | Cannot get variable.replace working properly | I am trying to replace a string with a new string in a python file and write the new string permanently to it. When I run the below script it removes part of the string and not all of it. The string in the file is:
self.id = "027FC8EBC2D1"
And the script I have to replace the string is:
def edit():
o = open("test... | [
"You cannot safely do what you intend to do, unless the replacement value and the original value have exactly the same length. Unless this is guaranteed, I'd copy the file:\nwith open('input.txt', 'r') as in_file:\n with open('output.txt', 'w') as out_file:\n for line in in_file:\n line = line.r... | [
5,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003038706_python.txt |
Q:
Python timed file upload
I have a python script that accepts a file from the user and saves it.
Is it possible to not upload the file immediately but to que it up and when the server has less load to upload it then.
Can this be done by transferring the file to the browsers storage area or taking the file from the ... | Python timed file upload | I have a python script that accepts a file from the user and saves it.
Is it possible to not upload the file immediately but to que it up and when the server has less load to upload it then.
Can this be done by transferring the file to the browsers storage area or taking the file from the Harddrive and transferring to ... | [
"There is no reliable way to do what you're asking, because fundamentally, your server has no control over the user's browser, computer, or internet connection. If you don't care about reliability, you might try writing a bunch of javascript to trigger the upload at a scheduled time, but it just wouldn't work if t... | [
3
] | [] | [] | [
"architecture",
"file",
"file_upload",
"python"
] | stackoverflow_0003040290_architecture_file_file_upload_python.txt |
Q:
rename keys in a dictionary
i want to rename the keys of a dictionary are which are ints, and i need them to be ints with leading zeros's so that they sort correctly.
for example my keys are like:
'1','101','11'
and i need them to be:
'001','101','011'
this is what im doing now, but i know there is a better wa... | rename keys in a dictionary | i want to rename the keys of a dictionary are which are ints, and i need them to be ints with leading zeros's so that they sort correctly.
for example my keys are like:
'1','101','11'
and i need them to be:
'001','101','011'
this is what im doing now, but i know there is a better way
tmpDict = {}
for oldKey in aD... | [
"You're going about it the wrong way. If you want to pull the entries from the dict in a sorted manner then you need to sort upon extraction.\nfor k in sorted(D, key=int):\n print '%s: %r' % (k, D[k])\n\n",
"You can sort with whatever key you want.\nSo, for example: sorted(mydict, key=int)\n",
"aDict = dict(((... | [
7,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003040727_dictionary_python.txt |
Q:
Union on ValuesQuerySet in django
I've been searching for a way to take the union of querysets in django. From what I read you can use query1 | query2 to take the union... This doesn't seem to work when using values() though. I'd skip using values until after taking the union but I need to use annotate to take the... | Union on ValuesQuerySet in django | I've been searching for a way to take the union of querysets in django. From what I read you can use query1 | query2 to take the union... This doesn't seem to work when using values() though. I'd skip using values until after taking the union but I need to use annotate to take the sum of a field and filter on it and si... | [
"QuerySet.values() does not return a QuerySet, but rather a ValuesQuerySet, which does not support this operation. Convert them to lists then add them.\nquery = list(q1) + list(q2)\n\n"
] | [
2
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0003041020_django_python_sql.txt |
Q:
Could random.randint(1,10) ever return 11?
When researching for this question and reading the sourcecode in random.py, I started wondering whether randrange and randint really behave as "advertised". I am very much inclined to believe so, but the way I read it, randrange is essentially implemented as
start + int(r... | Could random.randint(1,10) ever return 11? | When researching for this question and reading the sourcecode in random.py, I started wondering whether randrange and randint really behave as "advertised". I am very much inclined to believe so, but the way I read it, randrange is essentially implemented as
start + int(random.random()*(stop-start))
(assuming integer ... | [
"From random.py and the docs:\n\"\"\"Get the next random number in the range [0.0, 1.0).\"\"\"\n\nThe ) indicates that the interval is exclusive 1.0. That is, it will never return 1.0.\nThis is a general convention in mathematics, [ and ] is inclusive, while ( and ) is exclusive, and the two types of parenthesis ca... | [
27,
12,
3
] | [] | [] | [
"bounds",
"python",
"random"
] | stackoverflow_0003037952_bounds_python_random.txt |
Q:
IDL-like parser that turns a document definition into powerful classes?
I am looking for an IDL-like (or whatever) translator which turns a DOM- or JSON-like document definition into classes which
are accessible from both C++ and Python, within the same application
expose document properties as ints, floats, stri... | IDL-like parser that turns a document definition into powerful classes? | I am looking for an IDL-like (or whatever) translator which turns a DOM- or JSON-like document definition into classes which
are accessible from both C++ and Python, within the same application
expose document properties as ints, floats, strings, binary blobs and compounds: array, string dict (both nestable) (basicall... | [
"ICE is the closest product I could think of. I don't know if you can do serialization to disk with ICE, but I can't think of a reason why it wouldn't. Problem is it costs $$$. I haven't personally negotiated a license with them, but ICE is the biggest player I know of in this domain.\nThen you have Pyro for pyt... | [
1,
0
] | [] | [] | [
"c++",
"data_binding",
"json",
"python",
"serialization"
] | stackoverflow_0003040708_c++_data_binding_json_python_serialization.txt |
Q:
SyntaxError using gdata-python-client to access Google Book Search Data API
>>> import gdata.books.service
>>> service = gdata.books.service.BookService()
>>> results = service.search_by_keyword(isbn='0434003484')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
results = service.search... | SyntaxError using gdata-python-client to access Google Book Search Data API | >>> import gdata.books.service
>>> service = gdata.books.service.BookService()
>>> results = service.search_by_keyword(isbn='0434003484')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
results = service.search_by_keyword(isbn='0434003484')
... snip ...
File "C:\Python26\lib\site-packages\a... | [
"I found I needed to disable SSL in the gdata client for it to work:\n...\ngd_client.ProgrammaticLogin()\ngd_client.ssl = False\n...\n\n",
"sje397's answer is the correct one; in your example above, if you do:\nservice.ssl = False\n\nbefore running the search_by_keyword method, the result is properly returned. If... | [
3,
2,
1
] | [] | [] | [
"elementtree",
"gdata",
"gdata_python_client",
"google_books",
"python"
] | stackoverflow_0002925985_elementtree_gdata_gdata_python_client_google_books_python.txt |
Q:
How to take advantage of subprocess within Django? - Django
I'm currently using os.popen() but have been recommended to use subprocess.popen() instead.
Any ideas on how I can integrate this?
It would be cool and fun to have a Python shell accessible on a Django app. But I reckon that it might be a bit complex to i... | How to take advantage of subprocess within Django? - Django | I'm currently using os.popen() but have been recommended to use subprocess.popen() instead.
Any ideas on how I can integrate this?
It would be cool and fun to have a Python shell accessible on a Django app. But I reckon that it might be a bit complex to implement.
I guess I would have to retrieve the subprocess, as a n... | [
"Try:\nhttp://www.datamech.com/devan/trypython/trypythonx.py\nand then ask him for the source. That's the route I'd go and then just restrict access to the page within Django's auth system.\n"
] | [
1
] | [] | [] | [
"command_line",
"django",
"popen",
"python"
] | stackoverflow_0003036878_command_line_django_popen_python.txt |
Q:
Django colon syntax in template tags: only in newer versions?
I just deployed an application to a new server, and although I'm using virtualenv, I had to install a new environment on the production server, which has a different architecture.
Anyway, I received no TemplateSytaxErrors in development, but on the prod... | Django colon syntax in template tags: only in newer versions? | I just deployed an application to a new server, and although I'm using virtualenv, I had to install a new environment on the production server, which has a different architecture.
Anyway, I received no TemplateSytaxErrors in development, but on the production server, I get:
Exception Type: TemplateSyntaxError
Excep... | [
"On closer inspection, I realized this wasn't the offending line, even though it was highlighted in the traceback:\n{% url admin:password_change as password_change_url %}\n\nThe line was actually in my views.py, where I used the ternary operator (\"this\" if condition else \"that\"). Little did I know, this syntax ... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003040356_django_python.txt |
Q:
Gstreamer of python's gst.LinkError problem
I am wiring a gstreamer application with Python. And I get a LinkError with following code:
import pygst
pygst.require('0.10')
import gst
import pygtk
pygtk.require('2.0')
import gtk
# this is very important, without this, callbacks from gstreamer thread
# will messed... | Gstreamer of python's gst.LinkError problem | I am wiring a gstreamer application with Python. And I get a LinkError with following code:
import pygst
pygst.require('0.10')
import gst
import pygtk
pygtk.require('2.0')
import gtk
# this is very important, without this, callbacks from gstreamer thread
# will messed our program up
gtk.gdk.threads_init()
def main(... | [
"your problem is here:\ngst.element_link_many(filesrc, decode, convert, sink)\n\nthe reason is that not all elements have simple, static inputs and outputs. at this point in your program, your decodebin does not have any source pads (that is: no outputs).\na pad is like a nipple - it's an input / output to an eleme... | [
20
] | [] | [] | [
"gstreamer",
"python"
] | stackoverflow_0002993777_gstreamer_python.txt |
Q:
finding elements in python association lists efficiently
I have a set of lists that look like this:
conditions = [
["condition1", ["sample1", "sample2", "sample3"]],
["condition2", ["sample4", "sample5", "sample6"],
...]
how can I do the following things efficiently and elegantly in Python?
Find all the elements... | finding elements in python association lists efficiently | I have a set of lists that look like this:
conditions = [
["condition1", ["sample1", "sample2", "sample3"]],
["condition2", ["sample4", "sample5", "sample6"],
...]
how can I do the following things efficiently and elegantly in Python?
Find all the elements in a certain condition?
e.g. get all the samples in condition... | [
"This looks more like a job for a dict:\nconditions = {\n\"condition1\": [\"sample1\", \"sample2\", \"sample3\"],\n\"condition2\": [\"sample4\", \"sample5\", \"sample6\"],\n...}\n\nYou could then get the \"ordered union\" using\n>>> conditions[\"condition1\"]+conditions[\"condition2\"]\n['sample1', 'sample2', 'samp... | [
6,
5,
2,
2
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0003040335_list_list_comprehension_python.txt |
Q:
How can I receive percent encoded slashes with Django on App Engine?
I'm using Django with Google's App Engine.
I want to send information to the server with percent encoded slashes. A request like http:/localhost/turtle/waxy%2Fsmooth that would match against a URL like r'^/turtle/(?P<type>([A-Za-z]|%2F)+)$'. Th... | How can I receive percent encoded slashes with Django on App Engine? | I'm using Django with Google's App Engine.
I want to send information to the server with percent encoded slashes. A request like http:/localhost/turtle/waxy%2Fsmooth that would match against a URL like r'^/turtle/(?P<type>([A-Za-z]|%2F)+)$'. The request gets to the server intact, but sometime before it is compared ag... | [
"os.environ['PATH_INFO'] is decoded, so you lose that information. Probably os.environ['REQUEST_URI'] is available, and if it is available it is not decoded. Django only reads PATH_INFO. You could probably do something like:\nrequest_uri = environ['REQUEST_URI']\nrequest_uri = re.sub(r'%2f', '****', request_uri,... | [
4
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003040659_django_google_app_engine_python.txt |
Q:
FileIO out of order when using subprocesses in Python
I am trying to generate a log file with information in order. This is what I have:
class ExecThread(threading.Thread):
def __init__(self, command):
self.command = command
self._lock = threading.Lock()
threading.Thread.__init__ ( self )
def run ( self )... | FileIO out of order when using subprocesses in Python | I am trying to generate a log file with information in order. This is what I have:
class ExecThread(threading.Thread):
def __init__(self, command):
self.command = command
self._lock = threading.Lock()
threading.Thread.__init__ ( self )
def run ( self ):
self._lock.acquire()
sys.stdout.write(''.join(["Execu... | [
"I/O is buffered by default. Try sys.stdout.flush() after sys.stdout.write().\n"
] | [
0
] | [] | [] | [
"multithreading",
"python",
"redirect"
] | stackoverflow_0003041686_multithreading_python_redirect.txt |
Q:
Django/jQuery - read file and pass to browser as file download prompt
I've previously asked a question regarding passing files to the browser so a user receives a download prompt. However these files were really just strings creatd at the end of a function and it was simple to pass them to an iframe's src attribu... | Django/jQuery - read file and pass to browser as file download prompt | I've previously asked a question regarding passing files to the browser so a user receives a download prompt. However these files were really just strings creatd at the end of a function and it was simple to pass them to an iframe's src attribute for the desired effect.
Now I have a more ambitious requirement, I need ... | [
"Why not just use bob.read() the same way you previously used a differently-constructed string? Seems simplest!\n"
] | [
2
] | [] | [] | [
"django",
"html",
"jquery",
"python"
] | stackoverflow_0003041603_django_html_jquery_python.txt |
Q:
"Passing Go" in a (python) date range
Updated to remove extraneous text and ambiguity.
The Rules:
An employee accrues 8 hours of Paid Time Off on the day after each quarter. Quarters, specifically being:
Jan 1 - Mar 31
Apr 1 - Jun 30
Jul 1 - Sep 30
Oct 1 - Dec 31
The Problem
Using python, I need to define the... | "Passing Go" in a (python) date range | Updated to remove extraneous text and ambiguity.
The Rules:
An employee accrues 8 hours of Paid Time Off on the day after each quarter. Quarters, specifically being:
Jan 1 - Mar 31
Apr 1 - Jun 30
Jul 1 - Sep 30
Oct 1 - Dec 31
The Problem
Using python, I need to define the guts of the following function:
def acru... | [
"The OP's edit mentions the real underlying problem is:\n\n\"How many hours of Paid Time Off are\n accrued from X-date to Y-date?\"\n\nI agree, and I'd compute that in the most direct and straightforward way, e.g.:\nimport datetime\nimport itertools\n\naccrual_months_days = (1,1), (4,1), (7,1), (10,1)\n\ndef accru... | [
5,
1,
1,
0,
0
] | [] | [] | [
"calendar",
"date",
"datetime",
"python",
"python_dateutil"
] | stackoverflow_0003041167_calendar_date_datetime_python_python_dateutil.txt |
Q:
Best practice- How to team-split a django project while still allowing code reusal
I know this sounds kind of vague, but please let me explain-
I'm starting work on a brand new project, it will have two main components: "ACME PRODUCT" (think Gmail, Meebo, etc), and "THE SITE" (help, information, marketing stuff, ... | Best practice- How to team-split a django project while still allowing code reusal | I know this sounds kind of vague, but please let me explain-
I'm starting work on a brand new project, it will have two main components: "ACME PRODUCT" (think Gmail, Meebo, etc), and "THE SITE" (help, information, marketing stuff, promotional landing pages, etc lots of marketing-induced cruft).
So basically the url /a... | [
"Django's componentization of apps means that you can have independent teams working on the various apps, with template tags and filters (and of course, normal Python functions) used for cross-app coupling.\n",
"I doubt the amount of code reuse you can get between the two projects, given your organizational situa... | [
3,
2
] | [] | [] | [
"deployment",
"django",
"python"
] | stackoverflow_0003041077_deployment_django_python.txt |
Q:
Does OOP make sense for small scripts?
I mostly write small scripts in python, about 50 - 250 lines of code. I usually don't use any objects, just straightforward procedural programming.
I know OOP basics and I have used object in other programming languages before, but for small scripts I don't see how objects w... | Does OOP make sense for small scripts? | I mostly write small scripts in python, about 50 - 250 lines of code. I usually don't use any objects, just straightforward procedural programming.
I know OOP basics and I have used object in other programming languages before, but for small scripts I don't see how objects would improve them. But maybe that is just my... | [
"I use whatever paradigm best suits the issue at hand -- be it procedural, OOP, functional, ... program size is not a criterion, though (by a little margin) a larger program may be more likely to take advantage of OOP's strengths -- multiple instances of a class, subclassing and overriding, special method overloads... | [
33,
27,
9,
8,
6,
4,
4,
4,
2,
2,
2,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"oop",
"python",
"scripting"
] | stackoverflow_0003039889_oop_python_scripting.txt |
Q:
In python, is there a simple way to connect to a mysql database that doesn't require root access?
I'm writing a script to parse some text files, and insert the data that they contain into a mysql database. I don't have root access on the server that this script will run on. I've been looking at mysql-python, but i... | In python, is there a simple way to connect to a mysql database that doesn't require root access? | I'm writing a script to parse some text files, and insert the data that they contain into a mysql database. I don't have root access on the server that this script will run on. I've been looking at mysql-python, but it requires a bunch of dependencies that I don't have available. Is there a simpler way to do this?
| [
"I would recommend the MySQL Python Connector, a MySQL DB-API adapter that does not use the C client library but rather reimplements the MySQL protocol completely in pure Python (compatible with Python 2.5 to 2.7, as well a 3.1).\nTo install C-coded extensions to Python you generally need root access (though the se... | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003042051_mysql_python.txt |
Q:
I keep Getting KeyError: 'tried' Whenever I Tried to Run Django Dev Server from Remote Machine
I am running django 1.1.1 on python2.6.1, and did start the django web server like this
manage.py runserver 192.0.0.1:8000
then tried to connect to the django dev web server on http://192.0.0.1:8000/
keep getting this... | I keep Getting KeyError: 'tried' Whenever I Tried to Run Django Dev Server from Remote Machine | I am running django 1.1.1 on python2.6.1, and did start the django web server like this
manage.py runserver 192.0.0.1:8000
then tried to connect to the django dev web server on http://192.0.0.1:8000/
keep getting this message on the remote computer
Traceback (most recent call last):
File "C:\Python26\Lib\site-pa... | [
"If you look at the revision logs of that file you'll see that django has recently started catching the KeyError that is raised in that try block. \nThe log message reads \"Ensured generating debug 404 page won't raise a key error. Thanks pigletto.\"\nSee the ticket http://code.djangoproject.com/ticket/12083 and th... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003041973_django_python.txt |
Q:
converting hexadecimal , octal numbers into decimal form using python script
There are many inbulit functions like int(octal) which can be used to convert octal numbers into decimal numbers on command line but these doesn't work out in script .
int(0671) returns 0671 in script, where as it represent decimal form o... | converting hexadecimal , octal numbers into decimal form using python script | There are many inbulit functions like int(octal) which can be used to convert octal numbers into decimal numbers on command line but these doesn't work out in script .
int(0671) returns 0671 in script, where as it represent decimal form of octal number on python command line.
Help???
Thank You
| [
"There's some confusion here -- pedantically (and with computers it's always best to be pedantic;-), there are no \"octal numbers\", there are strings which are octal representations of numbers (and other strings, more commonly encountered, which are their decimal representations, hexadecimal representations). The... | [
12,
2
] | [] | [] | [
"hex",
"octal",
"python"
] | stackoverflow_0003042135_hex_octal_python.txt |
Q:
Easy_install of wxpython has "setup script" error
I have an install of python 2.5 that fink placed in /sw/bin/. I use the easy install command
sudo /sw/bin/easy_install wxPython
to try to install wxpython and I get an error while trying to process wxPython-src-2.8.9.1.tab.bz2 that there is not setup script. Easy-... | Easy_install of wxpython has "setup script" error | I have an install of python 2.5 that fink placed in /sw/bin/. I use the easy install command
sudo /sw/bin/easy_install wxPython
to try to install wxpython and I get an error while trying to process wxPython-src-2.8.9.1.tab.bz2 that there is not setup script. Easy-install has worked for several other installations unti... | [
"There is a simple reason why it's busting: there just is no setup.py in wxPython; wxPython does not use distutils for installation.\nInstead, read the file README.1st.txt in source distribution for instruction on how to install wxPython.\n",
"wxPython 2.8.9.1 does use distutils\nUnder 'wxPython-src-2.8.9.1/wxPyt... | [
9,
3
] | [] | [] | [
"easy_install",
"python",
"wxpython"
] | stackoverflow_0000477573_easy_install_python_wxpython.txt |
Q:
Is this __import__ functionality correct?
I have a package named jiva_tasks, which I'm trying to import via celery (using the CELERY_IMPORTS attribute of celeryconfig. The import statement that celery is using is this:
__import__(module, [], [], [''])
Oddly enough, when this syntax is used, the module gets impor... | Is this __import__ functionality correct? | I have a package named jiva_tasks, which I'm trying to import via celery (using the CELERY_IMPORTS attribute of celeryconfig. The import statement that celery is using is this:
__import__(module, [], [], [''])
Oddly enough, when this syntax is used, the module gets imported twice, once as jiva_tasks and another time ... | [
"Creating an empty file \"foo.py\" and then creating a \"bar.py\" that says:\n__import__('foo', [], [], [''])\nimport sys\nprint sorted(sys.modules)\n\nprints out a list that only includes foo once, and not foo. or anything else with a trailing dot — so it's not simply the fact that celery is using __import__ that ... | [
1
] | [] | [] | [
"celery",
"global",
"import",
"python"
] | stackoverflow_0003017219_celery_global_import_python.txt |
Q:
"IronPython + .NET" vs "Python + PyQt". Which one is better for Windows App development?
I'm new in using Python. I would like to develop Windows GUI Application using Python. After some research, I found that I have 2 options:-
IronPython + .NET Framework
Python + PyQt
May I know which one is better for Windows... | "IronPython + .NET" vs "Python + PyQt". Which one is better for Windows App development? | I'm new in using Python. I would like to develop Windows GUI Application using Python. After some research, I found that I have 2 options:-
IronPython + .NET Framework
Python + PyQt
May I know which one is better for Windows Application development? Which option has more features (e.g. database support, etc)?
Other t... | [
"I faced the same issue and have, with misgivings, decided to go with IronPython/C#/.Net. I liked Qt but got cold feet when it was sold to Nokia because I just wasn't sure Nokia's goals in owning Qt were consistent with my needs for a windows UI. That said, Nokia has made some positive moves by combining separate... | [
5,
4,
3,
3,
1
] | [] | [] | [
".net",
"ironpython",
"pyqt",
"python",
"user_interface"
] | stackoverflow_0002657036_.net_ironpython_pyqt_python_user_interface.txt |
Q:
Easy ways to investigate unknown Python APIs
When studying a snippet of unknown Python code, I occasionally bump into the
varName.methodName()
pattern.
To figure out what's this, I shall study the code more, find where varName was instantiated, find its type. So if varName proves to be an instance of ClassName cl... | Easy ways to investigate unknown Python APIs | When studying a snippet of unknown Python code, I occasionally bump into the
varName.methodName()
pattern.
To figure out what's this, I shall study the code more, find where varName was instantiated, find its type. So if varName proves to be an instance of ClassName class, I would knew that methodName() is a method of... | [
"I sometimes inserted help(varName) into my code, so that when that particular function is run, the help file will show up instead. For example, if I have this code:\ndef foo(bar):\n bar.baz()\n\nand I want to figure out what class bar is and what .baz does, I just insert this\ndef foo(bar):\n help(bar)\n ... | [
3,
3,
1,
0,
0,
0
] | [] | [] | [
"api",
"python"
] | stackoverflow_0003038606_api_python.txt |
Q:
Can I treat IronPython as a Pythonic replacement to C#?
I do understand that this topic has been covered in some way at StackOverflow but I'm still not able to figure out the exact answer: can I treat IronPython as a Pythonic replacement to C#?
I use CPython every day, I love the Zen :) but my current task is a Wi... | Can I treat IronPython as a Pythonic replacement to C#? | I do understand that this topic has been covered in some way at StackOverflow but I'm still not able to figure out the exact answer: can I treat IronPython as a Pythonic replacement to C#?
I use CPython every day, I love the Zen :) but my current task is a Windows-only application with a complex GUI and some other feat... | [
"IronPython is NOT equivalent to \"other languages that run on .NET\", as the language has support for substantially fewer CLR runtime features.\nIronPython classes are not \"real\" .NET classes, and DLR APIs need to be used when calling IronPython code from traditional CLR-based languages; this means that if you w... | [
13,
10,
2,
1,
0,
0
] | [] | [] | [
".net",
"cpython",
"ironpython",
"python",
"python.net"
] | stackoverflow_0002617007_.net_cpython_ironpython_python_python.net.txt |
Q:
Which style of return is "better" for a method that might return None?
I have a method that will either return an object or None if the lookup fails. Which style of the following is better?
def get_foo(needle):
haystack = object_dict()
if needle not in haystack: return None
return haystack[needle]
or,... | Which style of return is "better" for a method that might return None? | I have a method that will either return an object or None if the lookup fails. Which style of the following is better?
def get_foo(needle):
haystack = object_dict()
if needle not in haystack: return None
return haystack[needle]
or,
def get_foo(needle):
haystack = object_dict()
try:
return h... | [
"For this particular example, it looks like the dict method get is the most concise:\ndef get_foo(needle):\n haystack = object_dict()\n return haystack.get(needle)\n\nIn general, in Python, people tend to prefer try/except than checking something first - see the EAFP entry in the glossary. Note that many \"te... | [
10,
2
] | [
"In every language I've used the first version is perferable. Exceptions are basically goto's in disguise with many of the same problems, so I don't use them if I can avoid it.\nThere is also a possible performance cost. I don't know about Python, but in many other languages there is a heavy cost for creating the e... | [
-2
] | [
"coding_style",
"python"
] | stackoverflow_0003042627_coding_style_python.txt |
Q:
Model inheritance and RSS Feed framework
I'm using model inheritance to manage a multiple models queryset:
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from imagekit.models import ImageModel
import datetime
class Entry(models.Model):
dat... | Model inheritance and RSS Feed framework | I'm using model inheritance to manage a multiple models queryset:
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from imagekit.models import ImageModel
import datetime
class Entry(models.Model):
date_pub = models.DateTimeField(default=datetime.... | [
"You have two options:\n\nuse the title_template and description_template attributes on the Feed class to point to templates that can handle a very generic input variable.\nRecreate your template logic in the feed class' methods so that your template variable gets a normalized piece of data.\n\nEither one will get... | [
2
] | [] | [] | [
"django",
"feed",
"inheritance",
"python",
"rss"
] | stackoverflow_0003040818_django_feed_inheritance_python_rss.txt |
Q:
Python script to remove lines from file containing words in array
I have the following script which identifies lines in a file which I want to remove, based on an array but does not remove them.
What should I change?
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = [... | Python script to remove lines from file containing words in array | I have the following script which identifies lines in a file which I want to remove, based on an array but does not remove them.
What should I change?
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
... | [
"sourcefile = \"C:\\\\Python25\\\\PC_New.txt\" \nfilename2 = \"C:\\\\Python25\\\\PC_reduced.txt\"\n\noffending = [\"Exception\",\"Integer\",\"RuntimeException\"]\n\ndef fixup( filename ): \n fin = open( filename ) \n fout = open( filename2 , \"w\") \n for line in fin: \n if True in [item in line for... | [
5,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003042856_python.txt |
Q:
Use Regular expression with fileinput
I am trying to replace a variable stored in another file using regular expression. The code I have tried is:
r = re.compile(r"self\.uid\s*=\s*('\w{12})'")
for line in fileinput.input(['file.py'], inplace=True):
print line.replace(r.match(line), sys.argv[1]),
The format ... | Use Regular expression with fileinput | I am trying to replace a variable stored in another file using regular expression. The code I have tried is:
r = re.compile(r"self\.uid\s*=\s*('\w{12})'")
for line in fileinput.input(['file.py'], inplace=True):
print line.replace(r.match(line), sys.argv[1]),
The format of the variable in the file is:
self.uid = ... | [
"You can use re.sub which will match the regular expression and do the substitution in one go:\nr = re.compile(r\"(self\\.uid\\s*=\\s*)'\\w{12}'\")\nfor line in fileinput.input(['file.py'], inplace=True):\n print r.sub(r\"\\1'%s'\" %sys.argv[1],line),\n\n",
"You need to use re.sub(), not str.replace():\n\nre.s... | [
6,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003043849_python_regex.txt |
Q:
Problem with Django styling
Hi new to django but I'm having issues with the stylesheets (CSS) of pages.
my settings.py contains
MEDIA_ROOT = ''
MEDIA_URL = ''
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
please can someone help me shed some light on what I need to do to get the CSS s... | Problem with Django styling | Hi new to django but I'm having issues with the stylesheets (CSS) of pages.
my settings.py contains
MEDIA_ROOT = ''
MEDIA_URL = ''
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
please can someone help me shed some light on what I need to do to get the CSS styles working in my templates
Tha... | [
"The templates setting is just for aiding when you're selecting a template file for rendering in your view handler.\nIf you want to serve files, such as CSS, see how to serve static files with Django, which is the easiest way. The best way, however, is to configure your server to, for the CSS (and other static file... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003043868_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.