content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
passing information to mod_wsgi and returning to div tag
long time reader first time poster.
I've recently been tasked with incorporating some python into a webpage for my employer. After doing some research it seemed that mod_wsgi and Django were the way to go, and it seemed to work great. However, my employer wo... | passing information to mod_wsgi and returning to div tag | long time reader first time poster.
I've recently been tasked with incorporating some python into a webpage for my employer. After doing some research it seemed that mod_wsgi and Django were the way to go, and it seemed to work great. However, my employer would like to maintain the site in Drupal and incorporate python... | [
"Drupal is a PHP-language framework, and wsgi/Django are waay too heavy for you IMHO. They're kinda designed to be used for the whole website.\nHow about passthru in php?\n\npassthru — Execute an external program and display raw output\n\nYou could execute the python script (maybe even with command line arguments f... | [
0,
0
] | [] | [] | [
"drupal",
"mod_wsgi",
"python"
] | stackoverflow_0004391487_drupal_mod_wsgi_python.txt |
Q:
Does PyPy work with Py2Exe?
Does PyPy work with Py2Exe? If it doesn't, are there any similar solutions?
A:
The answer is no (would be possible to get it running, but hard)
A:
I'm pretty sure the answer is "no". py2exe appears to depend on CPython's C API, which I'm pretty sure PyPy doesn't support. (That is, ... | Does PyPy work with Py2Exe? | Does PyPy work with Py2Exe? If it doesn't, are there any similar solutions?
| [
"The answer is no (would be possible to get it running, but hard)\n",
"I'm pretty sure the answer is \"no\". py2exe appears to depend on CPython's C API, which I'm pretty sure PyPy doesn't support. (That is, I can't see why PyPy would support the CPython API, nor did I see any mention it in any of the obvious pla... | [
5,
1
] | [] | [] | [
"py2exe",
"pypy",
"python"
] | stackoverflow_0004360582_py2exe_pypy_python.txt |
Q:
Escape for str in Python
Wow, this should be so simple, but it' just not working.
I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work.
>>> a = 'testing'
>>> b = a[:3] + '\' + a[3:]
>>> File "<stdin>", line 1
>>> b = a[:3] + '\' + a[3:]
^
... | Escape for str in Python | Wow, this should be so simple, but it' just not working.
I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work.
>>> a = 'testing'
>>> b = a[:3] + '\' + a[3:]
>>> File "<stdin>", line 1
>>> b = a[:3] + '\' + a[3:]
^
>>>SyntaxError: EOL while sca... | [
"You are being misled by Python's output. Try:\n>>> a = \"test\\\\ing\"\n>>> print(a)\ntest\\ing\n>>> print(repr(a))\n'test\\\\ing'\n>>> a\n'test\\\\ing'\n\n",
"If you want double slashes because the shell will escape \\ again, use a raw string:\nb = a[:3] + r'\\\\' + a[3:]\n\n",
"'tes\\\\ting' is correct, but ... | [
7,
1,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004392176_python.txt |
Q:
How to access REMOTE_ADDR in a model's save() method
I have a model (UserProfile) with which I want to record a user's IP address when new user accounts are created.
I've begin the process of overriding the Django model's save() method, but I am totally uncertain how to properly access HttpRequest attributes from ... | How to access REMOTE_ADDR in a model's save() method | I have a model (UserProfile) with which I want to record a user's IP address when new user accounts are created.
I've begin the process of overriding the Django model's save() method, but I am totally uncertain how to properly access HttpRequest attributes from within a model. Can any of you guys help? Google was unabl... | [
"You can get to the request from within the admin, but you can't do it in general code. If you need it then you'll have to assign it manually in the view.\n",
"You always need to pass on request information from the view to your save-method.\nConsider that saving an instance doesn't always have to be invoked from... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004392061_django_django_models_python.txt |
Q:
How can an image be retrieved from an excel worksheet using python xlrd
I am using the xlrd python excel library python-excel. I can read my excel workbook allright (I must say their tutorials are pretty good). BUT I can't retrieve an image stored in a worksheet and thats killing me.
ANY Python method on retrievin... | How can an image be retrieved from an excel worksheet using python xlrd | I am using the xlrd python excel library python-excel. I can read my excel workbook allright (I must say their tutorials are pretty good). BUT I can't retrieve an image stored in a worksheet and thats killing me.
ANY Python method on retrieving an image from a worksheet would be appreciated
Thanks
| [
"Sorry, I don't think xlrd is able to do so. You can embed an image with xlwt, but can't retrieve objects like charts, images and so on in xlrd...\nYou will have to confirm on the python-excel list, ask there.\n"
] | [
1
] | [] | [] | [
"excel",
"python",
"xlrd",
"xlwt"
] | stackoverflow_0004391470_excel_python_xlrd_xlwt.txt |
Q:
What is the best way to simplify the following code?
if report == True:
print ("\tActive parts:\t%s")%(len(pact)) # TOTAL P Part and Active
print ("\tDiscontinued parts:\t%s")%(len(pdisc)) # TOTAL P Part and Discontinued
print ("\tSlow-moving parts:\t%s")%(len(pslow)) # TOTAL P Part and Slow-moving
... | What is the best way to simplify the following code? | if report == True:
print ("\tActive parts:\t%s")%(len(pact)) # TOTAL P Part and Active
print ("\tDiscontinued parts:\t%s")%(len(pdisc)) # TOTAL P Part and Discontinued
print ("\tSlow-moving parts:\t%s")%(len(pslow)) # TOTAL P Part and Slow-moving
print ("\tObsolete parts:\t%s")%(len(pobs)) # P TOTAL P... | [
"Write a template as a \"constant\" and then print( template % dictionary_of_values)\nTo clarify:\ntemplate = \"\"\"\\tActive parts:\\t%(pactlen)d\n\\tDiscontinued parts:\\t%(pdisclen)d\n...\"\"\"\n...\nvalues = {'pactlen':len(pact), 'pdisclen':len(pdics) }\nprint(template % values)\n\n",
"You could make a list o... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"spring"
] | stackoverflow_0004392366_python_spring.txt |
Q:
How can I duplicate this simple matlab plot functionality with mathplotlib?
Here is a simple matlab script to read a csv file, and generate a plot (with which I can zoom in with the mouse as I desire). I would like to see an example of how this is done in python and mathplotlib.
data = csvread('foo.csv'); % re... | How can I duplicate this simple matlab plot functionality with mathplotlib? | Here is a simple matlab script to read a csv file, and generate a plot (with which I can zoom in with the mouse as I desire). I would like to see an example of how this is done in python and mathplotlib.
data = csvread('foo.csv'); % read csv data into vector 'data'
figure; % create figure
plot... | [
"import matplotlib.pyplot as plt\nimport numpy as np\n\narr=np.genfromtxt('foo.csv',delimiter=',')\nplt.plot(arr[:,0],arr[:,1],'b-')\nplt.show()\n\non this data (foo.csv):\n1,2\n2,4\n3,9\n\nproduces\n\nWhen you setup the matplotlibrc, one of the key parameters you need to set is the backend. Which backend you choos... | [
6,
1
] | [] | [] | [
"matlab",
"python"
] | stackoverflow_0004392254_matlab_python.txt |
Q:
Is there a consistent way to enumerate days/weeks/months between two dates?
I have two datetime objects; a start date and an end date. I need to enumerate the days, weeks and months between the two, inclusive.
Ideally the results would be in datetime form, though any compatible form is fine. Weeks and months are... | Is there a consistent way to enumerate days/weeks/months between two dates? | I have two datetime objects; a start date and an end date. I need to enumerate the days, weeks and months between the two, inclusive.
Ideally the results would be in datetime form, though any compatible form is fine. Weeks and months are represented by a date corresponding to the first day of the week/month, where Mo... | [
"Using dateutil:\nimport datetime\nimport dateutil.rrule as drrule\nimport dateutil.relativedelta as drel\nimport pprint\n\ndef dt2d(date):\n '''\n Convert a datetime.datetime to datetime.date object\n '''\n return datetime.date(date.year,date.month,date.day)\n\ndef enumerate_dates(start,end):\n days... | [
4
] | [] | [] | [
"date",
"python"
] | stackoverflow_0004392594_date_python.txt |
Q:
trouble populating a numpy array
My code below is not populating the numpy/pylab array called RRmeanArray. Can anyone show me how to fix the code so that it populates the array?
import pylab as p
RRmeanArray = p.array([])
startBeatIndex = 0
endBeatIndex = 10
for k in range(int(p.floor(len(QRSa... | trouble populating a numpy array | My code below is not populating the numpy/pylab array called RRmeanArray. Can anyone show me how to fix the code so that it populates the array?
import pylab as p
RRmeanArray = p.array([])
startBeatIndex = 0
endBeatIndex = 10
for k in range(int(p.floor(len(QRSandRRarray[0])/10))-1):
print '... | [
"Apparently += operator (which calls the method array.extend) doesn't exist for numpy arrays. If you're using a numpy array, you should preallocate it by making it the full size of what you're going to need. \nRRmeanArray = p.zeros(len(range(int(p.floor(len(QRSandRRarray[0])/10))-1)))\nfor i,k in enumerate(range(i... | [
1
] | [] | [] | [
"arrays",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0004392724_arrays_matplotlib_numpy_python.txt |
Q:
Algorithm to implement a SQL-like group-by with aggregation functions over a collection?
Let's say you have an array like this:
[
{'id' : 1, 'closed' : 1 },
{'id' : 2, 'closed' : 1 },
{'id' : 5, 'closed' : 1 },
{'id' : 7, 'closed' : 0 },
{'id' : 8, 'closed' : 0 },
{'id' : 9, 'closed' : 1 }
]
I'd like ... | Algorithm to implement a SQL-like group-by with aggregation functions over a collection? | Let's say you have an array like this:
[
{'id' : 1, 'closed' : 1 },
{'id' : 2, 'closed' : 1 },
{'id' : 5, 'closed' : 1 },
{'id' : 7, 'closed' : 0 },
{'id' : 8, 'closed' : 0 },
{'id' : 9, 'closed' : 1 }
]
I'd like to summarize this dataset (not using SQL!), and grabbing the min and max id for each group def... | [
"The key argument to itertools.groupby() allows you to pass your own aggregation function.\n",
"Ruby code:\ndef summarise array_of_hashes\n #first sort the list by id\n arr = array_of_hashes.sort {|a, b| a['id'] <=> b['id'] }\n #create a hash with id_min and id_max set to the id of the first\n #array ... | [
2,
1,
0,
0
] | [] | [] | [
"algorithm",
"collections",
"javascript",
"php",
"python"
] | stackoverflow_0004392336_algorithm_collections_javascript_php_python.txt |
Q:
Parsing and processing XML in Ruby
So I have a little XML document, foobar.xml
<?xml version="1.0" standalone="no"?>
<!DOCTYPE foo SYSTEM "bar.dtd">
<title _FORMAT="XXX.XXX" _QUANTITY="1" _DEVICENAME="XXX" _JOBNAME="FOOBAR">
<subtitle>
<variable name="x">A-1234567</variable>
</subtitle>
</title>
and a... | Parsing and processing XML in Ruby | So I have a little XML document, foobar.xml
<?xml version="1.0" standalone="no"?>
<!DOCTYPE foo SYSTEM "bar.dtd">
<title _FORMAT="XXX.XXX" _QUANTITY="1" _DEVICENAME="XXX" _JOBNAME="FOOBAR">
<subtitle>
<variable name="x">A-1234567</variable>
</subtitle>
</title>
and a little Python,
with open('foobar.xm... | [
"I prefer Nokogiri for my XML parsing in Ruby; it's fast and efficient to use (and lets you use CSS-style selectors instead of XPath if you like):\nrequire 'nokogiri'\n$number = 3\n$start = 134341\n\nmy_xml = IO.read('foobar.xml')\ndoc = Nokogiri::XML(my_xml)\ndoc.css('variable').each do |el|\n $number.times do\n... | [
2,
1
] | [] | [] | [
"python",
"ruby",
"xml"
] | stackoverflow_0004391892_python_ruby_xml.txt |
Q:
Python function telling me I sent two arguments when I only sent one
I'm using Google's webapp framework.
What I'm trying to do below is simply send the results of query.fetch to a function that will take the results and create a table with them.
class Utilities():
def create_table(results):
#Create a table... | Python function telling me I sent two arguments when I only sent one | I'm using Google's webapp framework.
What I'm trying to do below is simply send the results of query.fetch to a function that will take the results and create a table with them.
class Utilities():
def create_table(results):
#Create a table for the results....
variable results gets two results back from query.fe... | [
"The first argument is set implicitly by python when the method is bound to an instance. In this case util. When defining a method in a class, the first argument is usually named self and is the bound object.\nclass Utilities():\n def create_table(self, results):\n pass # more to come\n\nShould work fine... | [
9,
3,
1,
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004393340_google_app_engine_python.txt |
Q:
Using pyuno with my existing python installation
I'm trying to use PyUNO as a method to convert different document formats (doc, wordperfect, html, etc) to PDF from within my Django server. I'm having a heck of a time getting import uno to work. It seems to fail when doing import pyuno, with a message of ImportE... | Using pyuno with my existing python installation | I'm trying to use PyUNO as a method to convert different document formats (doc, wordperfect, html, etc) to PDF from within my Django server. I'm having a heck of a time getting import uno to work. It seems to fail when doing import pyuno, with a message of ImportError: DLL Load Failed: The specified module could not ... | [
"For simply conversions, you needn't reinvent the wheel. Look at unoconv: http://dag.wieers.com/home-made/unoconv/\n'Import uno' will automatically work IF the python interpreter was bundled with OpenOffice, or in some Linux systems where the packagers have done a lot of work for you already.\nAlternative 1: For ot... | [
2,
0,
0
] | [] | [] | [
"openoffice.org",
"python",
"pyuno"
] | stackoverflow_0004270962_openoffice.org_python_pyuno.txt |
Q:
Python Ctypes Null Terminated String Block
I am using a ctypes implementation of CreateProcessWithLogonW, and everything works well except I cannot figure out how to handle this section:
A pointer to an environment block for the new process. If this parameter is NULL, the new process uses the environment of the c... | Python Ctypes Null Terminated String Block | I am using a ctypes implementation of CreateProcessWithLogonW, and everything works well except I cannot figure out how to handle this section:
A pointer to an environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process.
An environment block consists of... | [
"As far as I can tell, the whole string does get passed across the ctypes boundary correctly in one direction, but gets truncated on the way back.\n>>> ctypes.create_string_buffer('abc\\0def').value\n'abc'\n>>> ctypes.create_string_buffer('abc\\0def').raw\n'abc\\x00def'\n\nUnfortunately (at least for me, Python 2.6... | [
6
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0004393537_ctypes_python.txt |
Q:
OpenOffice.org development with pyUno for Windows—which Python?
At home, on Linux, I've experimented with pyUNO to control OpenOffice.org using Python. I've been using Python 2.6. It all seems to work nicely.
Now I thought I would try one of my scripts (run a graphical diff for ODF doc) on Windows. But when I trie... | OpenOffice.org development with pyUno for Windows—which Python? | At home, on Linux, I've experimented with pyUNO to control OpenOffice.org using Python. I've been using Python 2.6. It all seems to work nicely.
Now I thought I would try one of my scripts (run a graphical diff for ODF doc) on Windows. But when I tried to run it, I got:
ImportError: No module named uno
According to ud... | [
"Per openoffice's docs, the Python version supported is WAY behind -- \"Efforts on moving PyUNO to Python 2.5 continue\", 2.6 not even on the map. So \"stuck with this situation for now\" is a fair assessment!-)\n",
"OpenOffice.org 3.1 comes with Python 2.6.1. (As I recall, it was a fairly last-minute merge that... | [
5,
4,
3
] | [] | [] | [
"openoffice.org",
"python",
"pyuno",
"uno",
"windows"
] | stackoverflow_0000994429_openoffice.org_python_pyuno_uno_windows.txt |
Q:
nosegae blobstore support?
im trying to find out if nosegae supports the blobstore for tests like it does for the datastore.
im having troubles to test a blobstore upload. does anyone know more about it?
thank you.
edit:
blob is a BlobReferenceProperty()
right now im having some issues. probably because im missing... | nosegae blobstore support? | im trying to find out if nosegae supports the blobstore for tests like it does for the datastore.
im having troubles to test a blobstore upload. does anyone know more about it?
thank you.
edit:
blob is a BlobReferenceProperty()
right now im having some issues. probably because im missing something.
if i try to add an e... | [
"It should do - NoseGAE simply uses the dev_appserver's code to set up the environment identically.\n"
] | [
1
] | [] | [] | [
"blobstore",
"google_app_engine",
"nose",
"python"
] | stackoverflow_0004387665_blobstore_google_app_engine_nose_python.txt |
Q:
How do I set up a local python library directory / PYTHONPATH?
In the process of trying to write a Python script that uses PIL today, I discovered I don't seem have it on my local machine (OS X 10.5.8, default 2.5 Python install).
So I run:
easy_install --prefix=/usr/local/python/ pil
and it complains a little ab... | How do I set up a local python library directory / PYTHONPATH? | In the process of trying to write a Python script that uses PIL today, I discovered I don't seem have it on my local machine (OS X 10.5.8, default 2.5 Python install).
So I run:
easy_install --prefix=/usr/local/python/ pil
and it complains a little about /usr/local/python/lib/python2.5/site-packages not yet existing, ... | [
"You are using the Apple-supplied Python 2.5 in OS X; it's a framework build and, by default, uses /Library/Python/2.5/site-packages as the location for installed packages, not /usr/local. Normally you shouldn't need to specify --prefix with an OS X framework build. Also beware that the setuptools (easy_install) ... | [
4,
1
] | [] | [] | [
"easy_install",
"macos",
"path",
"python",
"python_imaging_library"
] | stackoverflow_0004393830_easy_install_macos_path_python_python_imaging_library.txt |
Q:
django app that runs constantly in the backend
hey guys, im trying to run a script in the backend of my django project, i have used django signals to call my script and run it when foo class is saved, and in the foo class theres a variable that can be true or false, if its true it calls an infinte loop that runs ... | django app that runs constantly in the backend | hey guys, im trying to run a script in the backend of my django project, i have used django signals to call my script and run it when foo class is saved, and in the foo class theres a variable that can be true or false, if its true it calls an infinte loop that runs a function every x seconds, but since this is an inf... | [
"If you want to run tasks asynchronously have a look at django-celery!\nEDIT: of course you can also set up a good old cron job on your system....\n"
] | [
3
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004393831_django_django_admin_django_models_python.txt |
Q:
What is the order in which the different operators are executed in Python
() Function calls
() Boolean And
() Assignment
() Binary + or -
() Parenthesis
() Boolean Or
() / , * , / / or %
() >,<,<>, !=,==, <=,>=
()Unary + or -
() Slicing
() Boolean Not
() Subscription
() Exponential
A:
See the table at ... | What is the order in which the different operators are executed in Python | () Function calls
() Boolean And
() Assignment
() Binary + or -
() Parenthesis
() Boolean Or
() / , * , / / or %
() >,<,<>, !=,==, <=,>=
()Unary + or -
() Slicing
() Boolean Not
() Subscription
() Exponential
| [
"See the table at : http://docs.python.org/reference/expressions.html#summary\nAlso check out the evaluation order. \n\nIt says - Python evaluates expressions from left to right.\nWhile evaluating an assignment, the right-hand side is evaluated before the left-hand side.\n\n"
] | [
4
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0004394223_operators_python.txt |
Q:
Python Tornado - making POST return immediately while async function keeps working
so I have a handler below:
class PublishHandler(BaseHandler):
def post(self):
message = self.get_argument("message")
some_function(message)
self.write("success")
The problem that I'm facing is that some... | Python Tornado - making POST return immediately while async function keeps working | so I have a handler below:
class PublishHandler(BaseHandler):
def post(self):
message = self.get_argument("message")
some_function(message)
self.write("success")
The problem that I'm facing is that some_function() takes some time to execute and I would like the post request to return strai... | [
"You might be able to accomplish this by using your IOLoop's add_callback method like so:\nloop.add_callback(lambda: some_function(message))\n\nTornado will execute the callback in the next IOLoop pass, which may (I'd have to dig into Tornado's guts to know for sure, or alternatively test it) allow the request to c... | [
7,
1
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0003869421_python_tornado.txt |
Q:
How do I Fix this Python Variable Issue?
Alright, if you run the below code in Python it only prints the first letter of the question variable, however it prints the rest just fine. This only happens \when I have the for loop function inside of my Python script. Any ideas on how to fix it so I get the entire quest... | How do I Fix this Python Variable Issue? | Alright, if you run the below code in Python it only prints the first letter of the question variable, however it prints the rest just fine. This only happens \when I have the for loop function inside of my Python script. Any ideas on how to fix it so I get the entire question variable printing?
import random
g... | [
"This is happening because you are overwriting the global variable question with one of the values of question at this line:\nquestion = random.choice(question)\n\nThis means that the following occurs:\nquestion = [...] # question is a list of strings\nquestion = random.choice(question) # question is a single strin... | [
9,
1
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0004394335_python_variables.txt |
Q:
Does python support fixed size LIFO?
I want a data structure, fixed size LIFO, last in first out. Is it already there?
Edit: Sorry, what I want is LIFO not FIFO.
I checked http://docs.python.org/library/queue.html, it already provides the LIFO, the only thing I want to achieve is automatically drop the oldest one.... | Does python support fixed size LIFO? | I want a data structure, fixed size LIFO, last in first out. Is it already there?
Edit: Sorry, what I want is LIFO not FIFO.
I checked http://docs.python.org/library/queue.html, it already provides the LIFO, the only thing I want to achieve is automatically drop the oldest one.
Eg) LIFO size 5 with elements: 1 2 3 4 5
... | [
"Both collections.deque and queue.Queue support fifo and a max size.\nAdaptation for clarification from the documentation:\nqueue.LifoQueue supports this, but will not pop the last one when the determined maxsize has been reached:\n\nclass queue.LifoQueue(maxsize=0)\nConstructor for a LIFO queue. maxsize is an inte... | [
8
] | [] | [] | [
"python"
] | stackoverflow_0004394389_python.txt |
Q:
Intercepting module calls?
I'm trying to 'intercept' all calls to a specific module, and reroute them to another object. I'd like to do this so that I can have a fairly simple plugin architecture.
For example, in main.py
import renderer
renderer.draw('circle')
In renderer.py
specificRenderer = OpenGLRenderer()
... | Intercepting module calls? | I'm trying to 'intercept' all calls to a specific module, and reroute them to another object. I'd like to do this so that I can have a fairly simple plugin architecture.
For example, in main.py
import renderer
renderer.draw('circle')
In renderer.py
specificRenderer = OpenGLRenderer()
#Then, i'd like to route all cal... | [
"In renderer.py:\nimport sys\n\nif __name__ != \"__main__\":\n sys.modules[__name__] = OpenGLRenderer()\n\nThe module name is now mapped to the OpenGLRenderer instance, and import renderer in other modules will get the same instance.\nActually, you don't even need the separate module. You can just do:\nimport sy... | [
5,
2,
2,
0,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0004392855_module_python.txt |
Q:
Python - solve polynomial for y
I'm taking in a function (e.g. y = x**2) and need to solve for x. I know I can painstakingly solve this manually, but I'm trying to find instead a method to use. I've browsed numpy, scipy and sympy, but can't seem to find what I'm looking for. Currently I'm making a lambda out of th... | Python - solve polynomial for y | I'm taking in a function (e.g. y = x**2) and need to solve for x. I know I can painstakingly solve this manually, but I'm trying to find instead a method to use. I've browsed numpy, scipy and sympy, but can't seem to find what I'm looking for. Currently I'm making a lambda out of the function so it'd be nice if i'm abl... | [
"If you are looking for numerical solutions (i.e. just interested in the numbers, not the symbolic closed form solutions), then there are a few options for you in the SciPy.optimize module. For something simple, the newton is a pretty good start for simple polynomials, but you can take it from there.\nFor symbolic ... | [
10,
4,
3
] | [] | [] | [
"equation",
"lambda",
"python"
] | stackoverflow_0004394504_equation_lambda_python.txt |
Q:
GC in python: what will this behave?
A python class A:
a = A()
array.append(a)
...
some operation triggers a's method b()
in a.b():
array.remove(self);
# will this make the self be freed? as the only reference has been removed from array.
# access the a's data...
A:
While the method is executing, you still hav... | GC in python: what will this behave? | A python class A:
a = A()
array.append(a)
...
some operation triggers a's method b()
in a.b():
array.remove(self);
# will this make the self be freed? as the only reference has been removed from array.
# access the a's data...
| [
"While the method is executing, you still have a reference(self) to a .\nOnly once the method completes is a eligible for collection.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004394623_python.txt |
Q:
numpy: compute x.T*x for a large matrix
In numpy, what's the most efficient way to compute x.T * x, where x is a large (200,000 x 1000) dense float32 matrix and .T is the transpose operator?
For the avoidance of doubt, the result is 1000 x 1000.
edit: In my original question I stated that np.dot(x.T, x) was taking... | numpy: compute x.T*x for a large matrix | In numpy, what's the most efficient way to compute x.T * x, where x is a large (200,000 x 1000) dense float32 matrix and .T is the transpose operator?
For the avoidance of doubt, the result is 1000 x 1000.
edit: In my original question I stated that np.dot(x.T, x) was taking hours. It turned out that I had some NaNs sn... | [
"This may not be the answer you're looking for, but one way to speed it up considerably is to use a gpu instead of your cpu. If you have a decently powerful graphics card around, it'll outperform your cpu any day, even if your system is very well tuned.\nFor nice integration with numpy, you could use theano (if you... | [
10,
5,
2
] | [] | [] | [
"matrix_multiplication",
"numpy",
"python",
"scipy",
"transpose"
] | stackoverflow_0004375617_matrix_multiplication_numpy_python_scipy_transpose.txt |
Q:
Swig, python and output strings
I am using Swig to wrap a C interface that looks like this:
int dosomething(char **str);
where str is an output string. For example, from C its called like this:
char *str= NULL;
int val= dosomething(&str);
...
free(str);
In Python, I'd like to be able to call it like this:
va... | Swig, python and output strings | I am using Swig to wrap a C interface that looks like this:
int dosomething(char **str);
where str is an output string. For example, from C its called like this:
char *str= NULL;
int val= dosomething(&str);
...
free(str);
In Python, I'd like to be able to call it like this:
val,str = dosomething()
However, pytho... | [
"Try this typemap (I'm using SWIG 2.0.0):\n%include <cstring.i>\n%cstring_output_allocate(char **str, free(*$1));\n\nDocumentation: cstring.i\n",
"Why not use it normally, passing a parameter, and wrap it inside python to return a tuple?\n"
] | [
1,
0
] | [] | [] | [
"c",
"python",
"swig"
] | stackoverflow_0004393500_c_python_swig.txt |
Q:
PyPy: What is all the buzz about?
Note: The title is deliberately provocative (to make you click on it and want to close-vote the question) and I don't want to look preoccupied.
I've been reading and hearing more and more about PyPy. It's like a linear graph.
Why is PyPy so special? As far as I know implementatio... | PyPy: What is all the buzz about? | Note: The title is deliberately provocative (to make you click on it and want to close-vote the question) and I don't want to look preoccupied.
I've been reading and hearing more and more about PyPy. It's like a linear graph.
Why is PyPy so special? As far as I know implementations of dynamic languages written in the ... | [
"Good thing to be aware when talking about the PyPy project is that it aims to actually provide two deliverables: first is JIT compiler generator. Yes, generator, meaning that they are implementing a framework for writing implementations of highly dynamic programming languages, such as Python. The second one is the... | [
47,
22,
11,
5,
4
] | [] | [] | [
"pypy",
"python"
] | stackoverflow_0002970108_pypy_python.txt |
Q:
How to override the stack trace template in django?
How can I change the template that django uses to display a stack trace when DEBUG mode is enabled and an exception gets caught at the top of the stack resulting in a 500?
Apologies if this is a dupe question -- I'm sure the answer is stated simply somewhere, but... | How to override the stack trace template in django? | How can I change the template that django uses to display a stack trace when DEBUG mode is enabled and an exception gets caught at the top of the stack resulting in a 500?
Apologies if this is a dupe question -- I'm sure the answer is stated simply somewhere, but owing to the nature of the search terms I'm having a har... | [
"Well, the trace is formatted by an internal template in views/debug.py. Look for TECHNICAL_500_TEMPLATE and for get_traceback_html() where it's used. So you could copy that template, hack it as you like, then monkeypatch it into django.view.debug. It ain't pretty, but this is fairly deep into the guts so you have ... | [
3,
1
] | [] | [] | [
"django",
"django_templates",
"exception_handling",
"python"
] | stackoverflow_0004392902_django_django_templates_exception_handling_python.txt |
Q:
How to import XSD schema with Python Suds (version 0.3.6) SOAP library : TypeNotFound exception?
I'm trying to use SABRE travel web services with Python Suds, but one XSD seems not well-formed (maybe namespace is missing in this schema).
from suds.client import Client
wsdl = 'http://webservices.sabre.com/wsdl/sab... | How to import XSD schema with Python Suds (version 0.3.6) SOAP library : TypeNotFound exception? | I'm trying to use SABRE travel web services with Python Suds, but one XSD seems not well-formed (maybe namespace is missing in this schema).
from suds.client import Client
wsdl = 'http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl'
client = Client(wsdl, cache=None)
Debug trace returns :
.DEB... | [
"I just posted a workaround to that Suds ticket. You may want to check it out: https://fedorahosted.org/suds/ticket/239#comment:19\nBriefly, here's the workaround code:\nfrom suds.client import Client\nimport sys\nsys.setrecursionlimit(10000)\nc = Client('http://url.to/endpoint?wsdl', cache=None)\n\n",
"This look... | [
3,
1
] | [] | [] | [
"python",
"soap",
"suds",
"wsdl"
] | stackoverflow_0001351125_python_soap_suds_wsdl.txt |
Q:
How can I generate an absolute url for a Pylons controller?
I need to generate a URL for use as a callback in an external system in my pylons application. This requires me to provide both the pylons-app-relative controller path (as generated by the url method:
>>> relative_url = url(controller='my_cont', action='c... | How can I generate an absolute url for a Pylons controller? | I need to generate a URL for use as a callback in an external system in my pylons application. This requires me to provide both the pylons-app-relative controller path (as generated by the url method:
>>> relative_url = url(controller='my_cont', action='callback', id=generated_id)
>>> print relative_url
/my_cont/callba... | [
"You can use the routes function url_for, which takes a parameter for host:\nfrom routes import url_for\nfrom pylons import request\n\nabs_url = url_for(host=request.host,\n controller=\"my_cont\",\n action=\"callback\",\n id=gen_id)\n\nOf course, this only works i... | [
1,
1
] | [] | [] | [
"mod_wsgi",
"pylons",
"python"
] | stackoverflow_0003926004_mod_wsgi_pylons_python.txt |
Q:
Why is my Django module missing?
I'm getting an error:
ImportError at /
No module named lxml
Request Method: GET
Request URL: http://www.myurl.com/
Django Version: 1.2.1
Exception Type: ImportError
Exception Value:
No module named lxml
Exception Location: /mypath/project/app/views.py in <module>, line 4
Pyt... | Why is my Django module missing? | I'm getting an error:
ImportError at /
No module named lxml
Request Method: GET
Request URL: http://www.myurl.com/
Django Version: 1.2.1
Exception Type: ImportError
Exception Value:
No module named lxml
Exception Location: /mypath/project/app/views.py in <module>, line 4
Python Executable: /usr/bin/python
Pytho... | [
"Because the .egg isn't in sys.path. If you've installed it to a custom path then you'll need to add it in yourself.\n"
] | [
3
] | [] | [] | [
"django",
"dreamhost",
"python"
] | stackoverflow_0004394712_django_dreamhost_python.txt |
Q:
variable value only comparing this two list
( I cannot edit my old question I couldont reach edit tool) ,SO I will send it again
Finding variable value in a list. Input (uppercase letter is variable name):
[ 1, [2, X], Y, [4, Y, X]]
[ 1, U, [3, U], [4, Z, 10]]
example output:
X = 10
U = [2,... | variable value only comparing this two list | ( I cannot edit my old question I couldont reach edit tool) ,SO I will send it again
Finding variable value in a list. Input (uppercase letter is variable name):
[ 1, [2, X], Y, [4, Y, X]]
[ 1, U, [3, U], [4, Z, 10]]
example output:
X = 10
U = [2, 10]
Y = [3, [2, 10]]
z = [3, [2, 10]]
How can w... | [
"\niterate over both lists simultaneously. \nfor every 2 items in the same position:\nif they're both numbers make sure they're equale. if not, return false\nif one is a variable and the other is a value, add the pair to an \"assignment set\"\napply the assignment set on the two lists (replace each occurrence of t... | [
2
] | [] | [] | [
"algorithm",
"python",
"recursion"
] | stackoverflow_0004395935_algorithm_python_recursion.txt |
Q:
Jython: Error in subprocess module, AttributeError: 'module' object has no attribute 'python'
I have my project set up like this, it starts in a Java class which uses the PythonInterpreter.initialize method to set my python path to the jython Lib directory and a directory that contains "org/curious/neofelis/my jyt... | Jython: Error in subprocess module, AttributeError: 'module' object has no attribute 'python' | I have my project set up like this, it starts in a Java class which uses the PythonInterpreter.initialize method to set my python path to the jython Lib directory and a directory that contains "org/curious/neofelis/my jython files". I then create a PythonInterpreter and have it execute my main jython file.
I guess it'... | [
"Importing a package -- org in this case -- won't always import all its subpackages and submodules. It is up to the package to define what will be included when you do import org. Obviously, the python subpackage is not included in the import by default, so you need to import it explicitly.\n"
] | [
0
] | [] | [] | [
"java",
"jython",
"python",
"subprocess"
] | stackoverflow_0004396288_java_jython_python_subprocess.txt |
Q:
Is there a way to have SQLAlchemy NOT wrap SQL writes within a BEGIN and COMMIT?
I'm using SQLAlchemy 0.6.4 on the Pylons 1.0 framework. I've tried every permutation of setting autoflush and autocommit to True and False, but I've found that SQLAlchemy wants to wrap all SQL sessions or writes with a BEGIN/COMMIT. ... | Is there a way to have SQLAlchemy NOT wrap SQL writes within a BEGIN and COMMIT? | I'm using SQLAlchemy 0.6.4 on the Pylons 1.0 framework. I've tried every permutation of setting autoflush and autocommit to True and False, but I've found that SQLAlchemy wants to wrap all SQL sessions or writes with a BEGIN/COMMIT. I've configured the scoped_session in models/meta.py as below:
"""SQLAlchemy Metadata... | [
"If your problem is the slowness of this behaviour, the solution might be to begin/end transactions in some sensible way explicitly in your application.\n",
"Does not look like it:\n\nWhile many DBAPIs implement a flag called autocommit, the current SQLAlchemy behavior is such that it implements its own autocommi... | [
2,
1
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0004393035_pylons_python_sqlalchemy.txt |
Q:
Python string extraction
In the following string how to get the id after the directory media and after getting the id ignore the rest of the string to read only the id numbers
id_arr= ["/opt/media/12/htmls","/opt/media/24/htmls","/opt/media/26/htmls","/opt/media/56/htmls"]
The output should be 12 24 26 56
A:
If... | Python string extraction | In the following string how to get the id after the directory media and after getting the id ignore the rest of the string to read only the id numbers
id_arr= ["/opt/media/12/htmls","/opt/media/24/htmls","/opt/media/26/htmls","/opt/media/56/htmls"]
The output should be 12 24 26 56
| [
"If the strings always look the way you said, try\nids = [int(s.split(\"/\")[3]) for s in id_arr]\n\n",
">>> import re\n>>> myre = re.compile(\"^.*/media/(\\d+)\")\n>>> for item in id_arr:\n... print (myre.search(item).group(1))\n...\n12\n24\n26\n56\n\n",
"[x.split('/')[3] for x in id_arr]\n",
"parts = \"... | [
3,
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004396453_python.txt |
Q:
json object as get parameter
I'm writing API for a mongo database. I need to pass JSON object as GET parameter:
example.com/api/obj/list/1/?find={"foo":"bar"}
How should I organize this better?
I thought about using JSON-like objects without quotes and spaces, for example:
{$or:[{a:foo+bar},{b:2}]}
So is there an... | json object as get parameter | I'm writing API for a mongo database. I need to pass JSON object as GET parameter:
example.com/api/obj/list/1/?find={"foo":"bar"}
How should I organize this better?
I thought about using JSON-like objects without quotes and spaces, for example:
{$or:[{a:foo+bar},{b:2}]}
So is there any tools to parse it in Python/Djan... | [
"It should be fine as long as the JSON objects aren't too big, they don't contain sensitive data (it sucks to see your password in your browser history) and you URL-escape them.\nUnfortunately, you have to take shortcuts if you want to have a human-readable JSON parameter. All JSON brackets ({, }, [, ]) are recomme... | [
3
] | [] | [] | [
"api",
"json",
"mongodb",
"python"
] | stackoverflow_0004396605_api_json_mongodb_python.txt |
Q:
Python search for value in string
I have a string like this:
STAT bytes 0
STAT curr_items 0
STAT total_items 0
STAT evictions 0
STAT reclaimed 0
END
I'm trying to get the value of curr_items, so far I've got
out = telnet.read_until("END")
req = re.search("curr_items", out).group(0).split()[0]
Which returns curr... | Python search for value in string | I have a string like this:
STAT bytes 0
STAT curr_items 0
STAT total_items 0
STAT evictions 0
STAT reclaimed 0
END
I'm trying to get the value of curr_items, so far I've got
out = telnet.read_until("END")
req = re.search("curr_items", out).group(0).split()[0]
Which returns curr_items, how do I get the value?
Thanks
| [
"You can add a capture group matching the value to your regex:\n>>> int(re.search(\"curr_items (\\d+)\", out).group(1))\n0\n\n",
"re.search(\"curr_items [0-9]*\", out).group(0).split()[1]\n",
"try:\n req = int(re.search(\"(?<=curr_items)\\s*([\\d]*)\", out).group(0))\nexcept:\n # No value was found.\n ... | [
6,
1,
1
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0004396929_python_regex_string.txt |
Q:
need help for calling function
List_of_subject = ['add user', 'modify user', delete user'] and so on
I have a variable called subject. so depending upon the subject other function are called.
like add_user, modify_user, delete_user and so on.
So when my subject is 'add_user'
I want to call add_user function. I ca... | need help for calling function | List_of_subject = ['add user', 'modify user', delete user'] and so on
I have a variable called subject. so depending upon the subject other function are called.
like add_user, modify_user, delete_user and so on.
So when my subject is 'add_user'
I want to call add_user function. I can call it like a normal function cal... | [
"In Python, functions are first-class objects, so you can put them into a dictionary:\nfn = {'add user': add_user, 'modify user': modify_user}\n\nTo then call the relevant function, use:\nuser = fn[subject]()\n\n",
"A (relatively) unsafe way of doing it would be \ndef add_user():\n (...)\n\nlist_of_subject = [... | [
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0004397304_python.txt |
Q:
What's the difference between "bind to variables" and "bind to object" in Python
When I studied "naming and binding" in Python, I saw the following example:
>>> def testClosure(maxIndex):
def closureTest(maxIndex=maxIndex):
return maxIndex
maxIndex += 5
return closureTest()
>>> ... | What's the difference between "bind to variables" and "bind to object" in Python | When I studied "naming and binding" in Python, I saw the following example:
>>> def testClosure(maxIndex):
def closureTest(maxIndex=maxIndex):
return maxIndex
maxIndex += 5
return closureTest()
>>> print(testClosure(10))
10
>>> def testClosure(maxIndex):
def closureTest():
... | [
"Two key facts:\n\nPython uses the LEGB rule to look up\nthe value of (bare) variables names.\nLEGB stands for Local, Extended,\nGlobal, Builtins. That means a\nvariable name \"binds\" to the local\nvalue, and if there is none, then\nthe value is looked-up in the\nextended scope, and if there is no\nsuch variable,... | [
8,
3,
0
] | [] | [] | [
"binding",
"closures",
"python"
] | stackoverflow_0004396679_binding_closures_python.txt |
Q:
Tracking global migration to Python 3.x
Python 3.x is looking ever more tempting with cleaned up syntax (I like it, others may not) new features and what looks like a gradual progression towards more speed and better multithreading.
But Python 3.x is still held back by lack of 3rd party support. Important packages... | Tracking global migration to Python 3.x | Python 3.x is looking ever more tempting with cleaned up syntax (I like it, others may not) new features and what looks like a gradual progression towards more speed and better multithreading.
But Python 3.x is still held back by lack of 3rd party support. Important packages like Django, Twisted, etc. are not ported. I... | [
"George Brandl has made a script that generates a graph with the amount of packages supporting Python 3:\n\nThe Link on the CheeseShop front page shows the packages in question: http://pypi.python.org/pypi?%3aaction=browse&c=533&show=all\nThere is also (a pretty crummy) list of unported packages ordered by how many... | [
9,
2
] | [] | [] | [
"migration",
"python",
"python_3.x"
] | stackoverflow_0004395683_migration_python_python_3.x.txt |
Q:
better way of extracting values from string
str = 'This is first line \n 2 line start from her\ Service Name: test \n some 4 line \n User Name: amit \n some something \n Last Name: amit amit \n
Basically What I am interested is getting the service name and user name.
Should I user regular expression for doing thi... | better way of extracting values from string | str = 'This is first line \n 2 line start from her\ Service Name: test \n some 4 line \n User Name: amit \n some something \n Last Name: amit amit \n
Basically What I am interested is getting the service name and user name.
Should I user regular expression for doing this.
I want to create a dict like
dict['service_nam... | [
"Given:\nstr = 'This is first line \\n 2 line start from her\\nService Name: test \\n some 4 line \\nUser Name: amit \\n some something \\nLast Name: amit amit \\n'\n\nThe following code:\ndict([line.split(':') for line in str.split('\\n') if ':' in line])\n\nproduces:\n{'Last Name': ' amit amit ', 'Service Name': ... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004397697_python.txt |
Q:
Scraping Data Off National Vulnerbility Database: can't figure out clicking on a button (Mechanize+Python)
I am trying to scrape some data off National Vulnerbability Database (http://web.nvd.nist.gov). What I want to do is enter a search term, which brings me the first 20 results, scrape that data. then I want to... | Scraping Data Off National Vulnerbility Database: can't figure out clicking on a button (Mechanize+Python) | I am trying to scrape some data off National Vulnerbability Database (http://web.nvd.nist.gov). What I want to do is enter a search term, which brings me the first 20 results, scrape that data. then I want to click "next 20" until I traversed all results.
I am able to successfully submit search terms, but clicking "ne... | [
"From the docstring of b.form.click:\n\nReturn request that would result from clicking on a control.\nThe request object is a\n urllib2.Request instance, which you\n can pass to urllib2.urlopen (or\n ClientCookie.urlopen).\n\nSo:\nrequest = b.form.click('vulnResultsForm:j_id116')\nb.open(request)\nresult = b.res... | [
1,
0
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0004396774_mechanize_python.txt |
Q:
TypeError: compile() expected string without null bytes
I am trying to translate a string using google translate API.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import urllib
import urllib2
import ast
url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='+urllib.quote(' '... | TypeError: compile() expected string without null bytes | I am trying to translate a string using google translate API.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import urllib
import urllib2
import ast
url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='+urllib.quote(' '.join(sys.argv[3:])) +'&langpair='+sys.ar... | [
"The response you get are likely in JSON format. Try using the json module, which is included with Python 2.6.\n",
"literal_eval expects Python representations, which don't include null. It's JSON, so use json.loads(transtext)\n"
] | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0004397903_python.txt |
Q:
How lambdas work?
I'm learning python using the tutorial on the official python website and came across this example:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
Where does x get it's value from? I'm not familiar with how lambda works, I und... | How lambdas work? | I'm learning python using the tutorial on the official python website and came across this example:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
Where does x get it's value from? I'm not familiar with how lambda works, I understand anonymous funct... | [
"Consider this. f is the object created by the make_incrementor function.\nIt is a lambda, an \"anonymous function\".\n>>> f= lambda x: x+42\n>>> f(10)\n52\n\nThe value for x showed up when we applied f to a value.\n",
"First off, here's a translation into JavaScript:\nfunction makeIncrementor(n) {\n return f... | [
5,
4,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0004394483_lambda_python.txt |
Q:
Python, SQL: Set the columns read as parameter
I have a SQL query, mad in Python using Psycopg2. The query reads some columns from the arches table:
rows = archesDB.read_all("""SELECT "+str(columns)[1:-1].replace("'","")+"
FROM arches
WHERE lower(arch) like '... | Python, SQL: Set the columns read as parameter | I have a SQL query, mad in Python using Psycopg2. The query reads some columns from the arches table:
rows = archesDB.read_all("""SELECT "+str(columns)[1:-1].replace("'","")+"
FROM arches
WHERE lower(arch) like '%%%s%%'""" % (arch.lower()))
I want to parametrize ... | [
"Column names cannot be passed in the SQL string as parameters within the DB API. And it would not make sense to it as well. \nIf you need to check the column name input, sanitize it beforehand.\nThe like string should go in as a parameter though\nThe following code sample would be an improvement if columns variabl... | [
2,
0
] | [] | [] | [
"parameters",
"psycopg2",
"python",
"sql"
] | stackoverflow_0004397150_parameters_psycopg2_python_sql.txt |
Q:
Best Practices in Handling Modules Prerequisites
Recently I started working on a personal project in my notebook that, all going OK, it will be placed in a server elsewhere. The problem is that I make use of modules. Some were installed from apt-get, others from easy_install and one or two of those were placed dir... | Best Practices in Handling Modules Prerequisites | Recently I started working on a personal project in my notebook that, all going OK, it will be placed in a server elsewhere. The problem is that I make use of modules. Some were installed from apt-get, others from easy_install and one or two of those were placed directly under a subdirectory since I changed them a bit.... | [
"Have a look at virtualenv. Virtualenv is a tool to create isolated Python environments.\n"
] | [
2
] | [] | [] | [
"distribution",
"easy_install",
"installation",
"package",
"python"
] | stackoverflow_0004398226_distribution_easy_install_installation_package_python.txt |
Q:
Optional string not matched in Regular Expression
The string s is bigger, but I have shortened it to simplify.
>>> import re
>>> s = "Blah. Tel.: 555 44 33 22."
>>> m = re.search(r"\s*Tel\.:\s*(?P<telephone>.+?)\.", s)
>>> m.group("telephone")
'555 44 33 22'
The code above works, but if I wrap the regex in ()? to... | Optional string not matched in Regular Expression | The string s is bigger, but I have shortened it to simplify.
>>> import re
>>> s = "Blah. Tel.: 555 44 33 22."
>>> m = re.search(r"\s*Tel\.:\s*(?P<telephone>.+?)\.", s)
>>> m.group("telephone")
'555 44 33 22'
The code above works, but if I wrap the regex in ()? to make it optional, I don't get any telephone.
>>> m = r... | [
"(anything)? matches the zero string at the very beginning of your string (before Blah), so it is happy and does not bother searching further.\nEDIT:\nIf you have many lines and only some of them contain the wanted string, try the following:\nimport re\n\nrex = re.compile(r\"\\s*Tel\\.:\\s*(?P<telephone>.+?)\\.\")\... | [
2,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004398534_python_regex.txt |
Q:
How can I create the following arrays
How could I create arrays for items in a list
something like
list = ["a","b","c"]
for thing in list:
thing = []
A:
I think the strict response to what you are asking is:
for x in lst:
locals()[x] = []
locals may be globals, depending on what you want. But it's u... | How can I create the following arrays | How could I create arrays for items in a list
something like
list = ["a","b","c"]
for thing in list:
thing = []
| [
"I think the strict response to what you are asking is:\nfor x in lst: \n locals()[x] = []\n\nlocals may be globals, depending on what you want. But it's usually advisable to use a dictionary to hold these values instead (as other have already proposed).\n[Edit] another way:\nlocals().update(dict.fromkeys(lst, [... | [
2,
1,
0,
0,
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0004398859_arrays_python.txt |
Q:
How can I add something to the heading part of HTML document with docutils
This document (http://docutils.sourceforge.net/docs/ref/rst/directives.html) explains about using .. raw:: to pass through HTML code in docutils, and the HTML code is in the body part of generated HTML.
How can I put something in heading pa... | How can I add something to the heading part of HTML document with docutils | This document (http://docutils.sourceforge.net/docs/ref/rst/directives.html) explains about using .. raw:: to pass through HTML code in docutils, and the HTML code is in the body part of generated HTML.
How can I put something in heading part (..) with docutils?
| [
"There is a meta directive to set meta tags if that's what you want.\nIf you are wanting to control the whole web page with your own css and javascript then you might want to look at Sphinx and write your own theme.\n"
] | [
1
] | [] | [] | [
"docutils",
"python"
] | stackoverflow_0004398962_docutils_python.txt |
Q:
Possible to create single pixel wide horizontal/vertical ttk.Separator's?
Is there a way to create single pixel wide horizontal and vertical ttk.Separator()'s?
Python 2.7/Windows: When I magnify the ttk Separators they are built as 2 parallel lines - one line gray and one line a light/white color. The latter color... | Possible to create single pixel wide horizontal/vertical ttk.Separator's? | Is there a way to create single pixel wide horizontal and vertical ttk.Separator()'s?
Python 2.7/Windows: When I magnify the ttk Separators they are built as 2 parallel lines - one line gray and one line a light/white color. The latter color added to create a subtle 3d effect?
I would like to create single pixel wide s... | [
"If you need a single pixel line, create a normal frame with a width of 1. It will have the default gray background. If you want the background of the root window you can always just ask:\nimport Tkinter as tk\nroot = tk.Tk()\nprint \"background is\", root[\"background\"]\n\n"
] | [
1
] | [] | [] | [
"python",
"separator",
"tkinter",
"ttk",
"user_interface"
] | stackoverflow_0004399198_python_separator_tkinter_ttk_user_interface.txt |
Q:
Can't connect to org.freedesktop.UDisks via DBus-Python
It's the first time I'm using DBus so please bear with me.
This is my code:
import gobject
import pprint
gobject.threads_init()
from dbus import glib
glib.init_threads()
import dbus
bus = dbus.SessionBus()
remote_object = bus.get_object("org.freedesktop.UD... | Can't connect to org.freedesktop.UDisks via DBus-Python | It's the first time I'm using DBus so please bear with me.
This is my code:
import gobject
import pprint
gobject.threads_init()
from dbus import glib
glib.init_threads()
import dbus
bus = dbus.SessionBus()
remote_object = bus.get_object("org.freedesktop.UDisks", # Connection name
"/org... | [
"You can try using DFeet to check if this dbus object really exists.\n",
"The following worked for me, but I don't see the ListNames method you used, so I used EnumerateDevices.\n\nimport dbus\nbus = dbus.SystemBus()\nudisks = bus.get_object(\"org.freedesktop.UDisks\", \"/org/freedesktop/UDisks\")\nudisks = dbus.... | [
2,
1
] | [] | [] | [
"dbus",
"python"
] | stackoverflow_0004142690_dbus_python.txt |
Q:
what is the best cloud computing platform for biopython?
i'm currently working (as a senior project) building and implementing a bioinformatics web application to manipulate large data & some some complex work on them
i'm using biopython for it
what cloud computing platform is best and why?
thanks in advance
A:
... | what is the best cloud computing platform for biopython? | i'm currently working (as a senior project) building and implementing a bioinformatics web application to manipulate large data & some some complex work on them
i'm using biopython for it
what cloud computing platform is best and why?
thanks in advance
| [
"I have been experimenting with Amazon EC2 and boto. So far, it has been a powerful but gentle introduction to cloud computing.\n"
] | [
1
] | [] | [] | [
"bioinformatics",
"cloud",
"python"
] | stackoverflow_0004400584_bioinformatics_cloud_python.txt |
Q:
C# equivalent of Python's id()?
Is there a C# equivalent to Python's id()? If not, how can I test if an object has changed? For example, in Python, an immutable object:
>>> s = "abc"
>>> id(s)
11172320
>>> s += "d"
>>> id(s)
18632928
and a mutable one:
>>> a = [1, 2, 3]
>>> id(a)
11259656
>>> a += [4]
>>> id(a)
1... | C# equivalent of Python's id()? | Is there a C# equivalent to Python's id()? If not, how can I test if an object has changed? For example, in Python, an immutable object:
>>> s = "abc"
>>> id(s)
11172320
>>> s += "d"
>>> id(s)
18632928
and a mutable one:
>>> a = [1, 2, 3]
>>> id(a)
11259656
>>> a += [4]
>>> id(a)
11259656
Edit - Most of the answers s... | [
"You can test object identity with Object.ReferenceEquals.\n",
"Well, you can use the Object.ReferenceEquals() function:\n\nDetermines whether the specified Object instances are the same instance.\n\nTo borrow your Python example a little bit:\nList<int> listA = new List<int> { 1, 2, 3 };\nList<int> listB = listA... | [
5,
4,
4,
3,
0
] | [] | [] | [
"c#",
"mutability",
"python"
] | stackoverflow_0004399969_c#_mutability_python.txt |
Q:
Performance difference in alternative switches in Python
I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments ... | Performance difference in alternative switches in Python | I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments that if's and elifs would have to check each statement and bec... | [
"dict's perfomance is typically going to be unbeatable, because a lookup into a dict is going to be O(1) except in rare and practically never-observed cases (where they key involves user-coded types with lousy hashing;-). You don't have to \"create new modules\" as you say, just arbitrary callables, and that creat... | [
8,
6,
3,
1,
0,
0
] | [] | [] | [
"performance",
"python",
"switch_statement"
] | stackoverflow_0001692107_performance_python_switch_statement.txt |
Q:
Python, len function
I need some help, PLEASE LOOK AT EDIT 2
This is code of huffman:
def printHuffTree(huffTree, prefix = ''):
if len(huffTree) == 2:
print huffTree[1], prefix
exampleData = [
(0.124167 , 'e')
]
if __name__ == '__main__':
huffTree = makeHuffTree(exampleData)
printHuffTree(huff... | Python, len function | I need some help, PLEASE LOOK AT EDIT 2
This is code of huffman:
def printHuffTree(huffTree, prefix = ''):
if len(huffTree) == 2:
print huffTree[1], prefix
exampleData = [
(0.124167 , 'e')
]
if __name__ == '__main__':
huffTree = makeHuffTree(exampleData)
printHuffTree(huffTree)
output is:
e 00
t ... | [
"As I understand your question, you need to add len(prefix) to your final print:\ndef printHuffTree(huffTree, prefix = ''):\n if len(huffTree) == 2:\n print huffTree[1], prefix, len(prefix)\n\nUpdate to answer the new question\ndef printHuffTree(huffTree, prefix = '', s=0):\n if len(huffTree) == 2:\n ... | [
4,
2,
0,
0
] | [] | [] | [
"python",
"text"
] | stackoverflow_0004401345_python_text.txt |
Q:
Uploading app with Google App Engine problem
I'm trying to learn how to use the google app engine because I want to use stashboard (looks like an awesome tool) But anyway, I am following the hello world tutorial http://code.google.com/appengine/docs/python/gettingstarted/helloworld.html and I wanted to try to depl... | Uploading app with Google App Engine problem | I'm trying to learn how to use the google app engine because I want to use stashboard (looks like an awesome tool) But anyway, I am following the hello world tutorial http://code.google.com/appengine/docs/python/gettingstarted/helloworld.html and I wanted to try to deploy it. When I click on run in the GAE launcher I g... | [
"Google App engine support 2.5 or above versions of Python 2.x based versions , you use python 3.1 , download python 2.6 or 2.7 & it will work fine\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"google_apps",
"python"
] | stackoverflow_0004401961_google_app_engine_google_apps_python.txt |
Q:
Split string into array with many char pro items
I have a string and I want an array of str for example:
"hello world"
["hel", "lo ", "wor", "ld"]
or
["hell", "o wo", "rld"]
I see that list(message) would be ok but just for
["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", ]
Any ideas?
A:
>>> s = 'hello... | Split string into array with many char pro items | I have a string and I want an array of str for example:
"hello world"
["hel", "lo ", "wor", "ld"]
or
["hell", "o wo", "rld"]
I see that list(message) would be ok but just for
["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", ]
Any ideas?
| [
">>> s = 'hello world'\n>>> [s[i:i+3] for i in range(len(s)) if not i % 3]\n['hel', 'lo ', 'wor', 'ld']\n\nFor a more general solution (i.e. custom-defined splits), try this function:\ndef split_on_parts(s, *parts):\n total = 0\n buildstr = []\n for p in parts:\n buildstr.append(s[total:total+p])\n ... | [
3,
3,
2,
1,
0
] | [] | [] | [
"function",
"python",
"split",
"string"
] | stackoverflow_0004402383_function_python_split_string.txt |
Q:
How to maintain different version of a python module?
I have this core python module we use in our facility called mfxLib. I need to be able to keep different version of this module without breaking all the other modules/plugin that are importing this module.
My solution was keep a duplicate of my module by renami... | How to maintain different version of a python module? | I have this core python module we use in our facility called mfxLib. I need to be able to keep different version of this module without breaking all the other modules/plugin that are importing this module.
My solution was keep a duplicate of my module by renaming them mfxLib01 and mfxLib02 then
to replace the original ... | [
"You can import a module as another name. Commonly people use this to save typing in a long module name, for example:\nimport numpy as np\nnp.array([1,2,3,4])\n\nHence you could do:\nimport mfxLib01 as mfxLib\n\nor\nimport mfxLib02 as mfxLib\n\nthen your code uses mfxLib everywhere.\nThat might help...\n",
"If yo... | [
4,
1,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0004402140_module_python.txt |
Q:
Handle multiple tags in a Text widget when each tag adds a style to the text?
I want to create a toolbar for a text widget that allows you to select bold or italic text, as well as their combination (bold and italic together).
I've been looking at this response to Advanced Tkinter text box, as well as code for th... | Handle multiple tags in a Text widget when each tag adds a style to the text? | I want to create a toolbar for a text widget that allows you to select bold or italic text, as well as their combination (bold and italic together).
I've been looking at this response to Advanced Tkinter text box, as well as code for the StyledText widget, but neither answers my question.
The basic way to configure t... | [
"Sadly, this is one of the few weaknesses of the text widget. If you want both bold and italic you need a tag with a font that has both of those attributes. You can create new tags on the fly so it's not an impossible problem to solve, but it can be a bit tedious to figure out which characters in a range need the \... | [
2
] | [] | [] | [
"fonts",
"python",
"tags",
"text",
"tkinter"
] | stackoverflow_0004399697_fonts_python_tags_text_tkinter.txt |
Q:
Python's [] at least 3x faster than list()?
It appears that using [] around a generator expression (test1) behaves substantially better than putting it inside of list() (test2). The slowdown isn't there when I simply pass a list into list() for shallow copy (test3). Why is this?
Evidence:
from timeit import Time... | Python's [] at least 3x faster than list()? | It appears that using [] around a generator expression (test1) behaves substantially better than putting it inside of list() (test2). The slowdown isn't there when I simply pass a list into list() for shallow copy (test3). Why is this?
Evidence:
from timeit import Timer
t1 = Timer("test1()", "from __main__ import te... | [
"Well, my first step was to set the two tests up independently to ensure that this is not a result of e.g. the order in which the functions are defined.\n>python -mtimeit \"x=[34534534, 23423523, 77645645, 345346]\" \"[e for e in x]\"\n1000000 loops, best of 3: 0.638 usec per loop\n\n>python -mtimeit \"x=[34534534,... | [
36,
9,
2,
1
] | [] | [] | [
"performance",
"profiling",
"python"
] | stackoverflow_0004402858_performance_profiling_python.txt |
Q:
Python decorator for Django views: Check for a particular setting in UserProfile
I'd like to write a decorator to use on views all over my site to first check if the logged in user's UserProfile has a particular setting. In my case it's user.get_profile.user_status and the value could be either "expired" or "activ... | Python decorator for Django views: Check for a particular setting in UserProfile | I'd like to write a decorator to use on views all over my site to first check if the logged in user's UserProfile has a particular setting. In my case it's user.get_profile.user_status and the value could be either "expired" or "active". If the user_status = "expired" i want to redirect them to a billing account update... | [
"First, read this http://docs.djangoproject.com/en/1.2/topics/auth/#limiting-access-to-logged-in-users-that-pass-a-test\nIt's actually simpler if you don't write a decorator.\nfrom django.contrib.auth.decorators import user_passes_test\n\ndef must_be_active( user ):\n if .... whatever .... \n\ndef paywall_check(... | [
3,
0
] | [] | [] | [
"authentication",
"decorator",
"django",
"python"
] | stackoverflow_0004402910_authentication_decorator_django_python.txt |
Q:
How does python load all the values in sys.path?
I'm a python beginner and I'm in my first days playing with my own python scripts and projects such as django.
I use Ubuntu and I set my PYTHONPATH as
export PYTHONPATH=/usr/lib/python2.6:~/Projects/mypython
When I run into a python interpreter
import sys
print sy... | How does python load all the values in sys.path? | I'm a python beginner and I'm in my first days playing with my own python scripts and projects such as django.
I use Ubuntu and I set my PYTHONPATH as
export PYTHONPATH=/usr/lib/python2.6:~/Projects/mypython
When I run into a python interpreter
import sys
print sys.path
I can see
['', '/usr/bin', '/usr/local/lib/py... | [
"This is a list of every file the Python interpreter on my computer (which is set up similar to, but not the same as, yours) opens before it starts running code provided by me:\n$ strace -eopen python -c 1 2>&1 | grep -ve '-1 E'\nopen(\"/etc/ld.so.cache\", O_RDONLY) = 3\nopen(\"/lib/libpthread.so.0\", O_RDONLY... | [
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004401885_django_python.txt |
Q:
How to Download Files using Python?
HI, everyone. I am new to Python and am using Python 2.5 on CentOS.
I need to download files like WGET do.
I have done some search, and there are some solutions, an obvious way is this:
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
output = ope... | How to Download Files using Python? | HI, everyone. I am new to Python and am using Python 2.5 on CentOS.
I need to download files like WGET do.
I have done some search, and there are some solutions, an obvious way is this:
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
output = open('test.mp3','wb')
output.write(mp3file.r... | [
"There's an easier way:\nimport urllib\nurllib.urlretrieve(\"http://www.example.com/songs/mp3.mp3\", \"/home/download/mp3.mp3\")\n\n",
"For really big files, your code would use a lot of memory, since you load the whole file into the memory at once. It might be better to read and write the data in chunks:\nfrom ... | [
16,
3,
2,
1
] | [] | [] | [
"centos",
"command_line",
"linux",
"python",
"wget"
] | stackoverflow_0004403289_centos_command_line_linux_python_wget.txt |
Q:
import & structure python modules / classes
im working on some basic python stuff within the google app engine and I was unable to figure out the correct way to structure my handlers.
/main.py
/project/handlers/__init__.py
/project/handlers/AccountHandler.py
the AccountHandler is basically a class
class Account... | import & structure python modules / classes | im working on some basic python stuff within the google app engine and I was unable to figure out the correct way to structure my handlers.
/main.py
/project/handlers/__init__.py
/project/handlers/AccountHandler.py
the AccountHandler is basically a class
class AccountHandler(webapp.RequestHandler):
when im using fr... | [
"To quote from the docs:\n\nA module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.\n\nThe AccountHandler you are importing is the module /project/handlers/AccountHandler.py in this case. The file AccountHandler.py is not callable, and the int... | [
6,
0
] | [] | [] | [
"gae_module",
"google_app_engine",
"module",
"python"
] | stackoverflow_0004403416_gae_module_google_app_engine_module_python.txt |
Q:
How do I change variable in a thread?
Here's my situation. Let's say I would like to create a thread that continually prints the number 1. When a button is clicked the value should then change to 2. My issue is that I'm unsure how I change a variable in an already running thread. Here's my code:
import wx
from thr... | How do I change variable in a thread? | Here's my situation. Let's say I would like to create a thread that continually prints the number 1. When a button is clicked the value should then change to 2. My issue is that I'm unsure how I change a variable in an already running thread. Here's my code:
import wx
from threading import Thread
import time
class tes... | [
"You can't change local variables.\nWhat you can do is this:\nclass testThread(Thread):\n def __init__(self, parent):\n self.parent = parent\n Thread.__init__(self)\n self.start()\n\n def run(self):\n self.value = 1\n while 1:\n print self.value\n time.... | [
2,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004403443_python_wxpython.txt |
Q:
Why a python method not returning?
I have a destroy() method which is called before my thread is coming down.
def destroy(self):
self.logger.debug("Instance is being destroyed")
//do stuff
self.logger.debug("Instance has been destroyed")
This is the code from where it is called:
if (__name__ == '__mai... | Why a python method not returning? | I have a destroy() method which is called before my thread is coming down.
def destroy(self):
self.logger.debug("Instance is being destroyed")
//do stuff
self.logger.debug("Instance has been destroyed")
This is the code from where it is called:
if (__name__ == '__main__'):
try:
instance = devic... | [
"Are you looking at the same logger?\n",
"Is your log level above to debug? Try with print \nAlso, try adding a log before the call.\n",
"I think we'll need a bit more information than this -- probably about the context of 'do something' and input_string\nI put this into a piece of code:\nimport logging ... | [
2,
1,
1
] | [] | [] | [
"methods",
"python"
] | stackoverflow_0004403323_methods_python.txt |
Q:
dbus signal handler for e NetworkManager VPN connection
I need to develop some python code to be executed when a VPN connection is established, the VPN is controlled from NetworkManager, I am trying to figure how to use an NM DBUS event for this.
Using "dbus-monitor --system" I was able to identify the connect sig... | dbus signal handler for e NetworkManager VPN connection | I need to develop some python code to be executed when a VPN connection is established, the VPN is controlled from NetworkManager, I am trying to figure how to use an NM DBUS event for this.
Using "dbus-monitor --system" I was able to identify the connect signal:
signal sender=:1.1 -> dest=(null destination) serial=464... | [
"I was able to figure it out:\ndef vpn_connection_handler(*args, **keywords):\n state = args[0].get('State',0)\n if state == 2:\n # On connect code goes here\n\nsystem_bus.add_signal_receiver(vpn_connection_handler,\n dbus_interface=\"org.freedesktop.NetworkManager.VPN.Connection\",\n signal_... | [
7
] | [] | [] | [
"dbus",
"linux",
"python"
] | stackoverflow_0004401851_dbus_linux_python.txt |
Q:
how to use 'linenumbers ' in django
this is my django code:
{{ 'one<br/>two<br/>three'|linenumbers}}
and it show :
1. one
two
three
i want to know , how to show this using 'linenumbers' :
1. one
2. two
3. three
thanks
A:
Never used before, but Django Docs says you should be using a return character.
in your... | how to use 'linenumbers ' in django | this is my django code:
{{ 'one<br/>two<br/>three'|linenumbers}}
and it show :
1. one
two
three
i want to know , how to show this using 'linenumbers' :
1. one
2. two
3. three
thanks
| [
"Never used before, but Django Docs says you should be using a return character.\nin your views:\ntext = \"\"\"\n ONE\n TWO \n THREE\n\"\"\"\n\nthen in your template:\n{{ text|linenumbers }}\n\nshows 1. ONE 2. TWO 3.THREE\nEDIT:\nHow ever every time I have had to do this, I usually do something like:\n{% f... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004403715_django_python.txt |
Q:
Which portion should I be looking at to modify the Path-Algorithm? ( I want to make 3 versions with different pathing algos)
class path_finder ():
def __init__ (self):
# map is a 1-DIMENSIONAL array.
# use the Unfold( (row, col) ) function to convert a 2D coordinate pair
# into a 1D index to use with t... | Which portion should I be looking at to modify the Path-Algorithm? ( I want to make 3 versions with different pathing algos) | class path_finder ():
def __init__ (self):
# map is a 1-DIMENSIONAL array.
# use the Unfold( (row, col) ) function to convert a 2D coordinate pair
# into a 1D index to use with this array.
self.map = {}
self.size = (-1, -1) # rows by columns
self.pathChainRev = ""
self.pathChain = ""
#... | [
"FindPath looks like the place to start. However, I don't think this code will help you if you want to implement totally different algorithms. What exactly are you trying to do?\nEdit:\nI think you should look into changing GetLowestNode and CalcF and CalcH too. I think that's where the next node to look at, cur... | [
2
] | [] | [] | [
"artificial_intelligence",
"path",
"python"
] | stackoverflow_0004401716_artificial_intelligence_path_python.txt |
Q:
update method for dictionaries-Python
I have written a code which tries to sort a dictionary using the values rather than keys
""" This module sorts a dictionary based on the values of the keys"""
adict={1:1,2:2,5:1,10:2,44:3,67:2} #adict is an input dictionary
items=adict.items()## converts the dictionary into ... | update method for dictionaries-Python | I have written a code which tries to sort a dictionary using the values rather than keys
""" This module sorts a dictionary based on the values of the keys"""
adict={1:1,2:2,5:1,10:2,44:3,67:2} #adict is an input dictionary
items=adict.items()## converts the dictionary into a list of tuples
##print items
list_value... | [
"Python dictionaries, no matter how you insert into them, are unordered. This is the nature of hash tables, in general.\nInstead, perhaps you should keep a list of keys in the order their values or sorted, something like: [ 5, 1, 44, ...]\nThis way, you can access your dictionary in sorted order at a later time.\n"... | [
3,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004398306_python.txt |
Q:
IO error when attempting to download images from url
The error happens when executing the following lines,
output[counter] = h['url']
name = '%(name)s%(#)03u' % {'title': user_input, '#': counter}
urllib.urlretrieve(output[counter], name)
counter += 1
>>>> File "/base/python_runtime/python_dist/lib/python2.5/urll... | IO error when attempting to download images from url | The error happens when executing the following lines,
output[counter] = h['url']
name = '%(name)s%(#)03u' % {'title': user_input, '#': counter}
urllib.urlretrieve(output[counter], name)
counter += 1
>>>> File "/base/python_runtime/python_dist/lib/python2.5/urllib.py", line 225, in retrieve
>>> tfp = open(filename, 'wb... | [
"Python is going to be looking for 'name' in the replacement dictionary you give it, not 'title'\nname = '%(name)s%(#)03u' % {'name' : 'title', '#' : counter}\n\n",
"It looks like urlfetch is trying to open a temporary file to store the result of the urlfetch in. Is the resulting page large? We recently increased... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004403355_google_app_engine_python.txt |
Q:
I already have a library that is in Python 2.3. Is there any advantage to rewriting it to 2.6?
Or, should we have a virutal environment and continue to run this on 2.3?
A:
EDIT: I take it back; porting between different 2.x versions is not trivial. Note that raise "Oops" worked in 2.5 but not in 2.6. However, th... | I already have a library that is in Python 2.3. Is there any advantage to rewriting it to 2.6? | Or, should we have a virutal environment and continue to run this on 2.3?
| [
"EDIT: I take it back; porting between different 2.x versions is not trivial. Note that raise \"Oops\" worked in 2.5 but not in 2.6. However, the port should be pretty easy; for one thing, I believe that anything that would break in version n+1 will warn in n, so you should be able to step through the versions. Alt... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0004404126_python.txt |
Q:
SWIG cross platform
My application is using SWIG to communicate between c++ and python on windows.
suppose if my interface is "example.h"
swig is generating example.py, example_wrap.cxx
/* File : example.i */
%module example
%{
#include "example.h"
%}
%include "std_string.i"
%include "std_wstring.i"
%include "e... | SWIG cross platform | My application is using SWIG to communicate between c++ and python on windows.
suppose if my interface is "example.h"
swig is generating example.py, example_wrap.cxx
/* File : example.i */
%module example
%{
#include "example.h"
%}
%include "std_string.i"
%include "std_wstring.i"
%include "example.h"
I am porting ... | [
"SWIG generates the same code regardless of the platform it is executed on.\nIf any parts of that code are OS/Compiler/etc.-specific (e.g. calling conventions on Windows for C#), this is handled by conditional compilation for C++ resp. similar techniques in the target language.\n"
] | [
4
] | [] | [] | [
"macos",
"python",
"swig",
"windows"
] | stackoverflow_0003997595_macos_python_swig_windows.txt |
Q:
Small problem with reg exps in python
So I have one variable that has all the code from some file. I need to remove all comments from this file. One of my regexp lines is this
x=re.sub('\/\*.*\*\/','',x,re.M,re.S);
What I want this to be doing is to remove all multi line comments. For some odd reason though, its s... | Small problem with reg exps in python | So I have one variable that has all the code from some file. I need to remove all comments from this file. One of my regexp lines is this
x=re.sub('\/\*.*\*\/','',x,re.M,re.S);
What I want this to be doing is to remove all multi line comments. For some odd reason though, its skipping two instances of */, and removing e... | [
".* will always match as many characters as possible. Try (.*?) - most implementations should try to match as few characters as possible then (should work without the brackets but not sure right now). So your whole pattern should look like this: \\/\\*.*?\\*\\/ or \\/\\*(.*?)\\*\\/\n",
"The expression .* is greed... | [
4,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004404492_python_regex.txt |
Q:
Switch between FCGI and CGI with Python and Flup
I'm currently moving all my Python CGI scripts to WSGI standard using Flup (http://trac.saddi.com/flup), I created a dispatch.fcgi file calling and using Flup as described in the documentation:
from flup.server.fcgi import WSGIServer
...
and works like a charm, the... | Switch between FCGI and CGI with Python and Flup | I'm currently moving all my Python CGI scripts to WSGI standard using Flup (http://trac.saddi.com/flup), I created a dispatch.fcgi file calling and using Flup as described in the documentation:
from flup.server.fcgi import WSGIServer
...
and works like a charm, the problem comes when I try to switch to CGI to debug so... | [
"FCGI protocol is different from CGI. That's why the simple change from FCGI to CGI didn't work and the FCGI would not work when changing the Apache .fcgi file handler to CGI handler.\n"
] | [
1
] | [] | [] | [
"cgi",
"fastcgi",
"flup",
"python"
] | stackoverflow_0004402685_cgi_fastcgi_flup_python.txt |
Q:
What could be some reasons why a class is not visible unless imported directly from a function?
Example:
import user
class Thing(object):
def doSomething(self):
u = user.User(1)
print u.name
>> UnboundLocalError: local variable 'user' referenced before assignment
But this works:
class Thi... | What could be some reasons why a class is not visible unless imported directly from a function? | Example:
import user
class Thing(object):
def doSomething(self):
u = user.User(1)
print u.name
>> UnboundLocalError: local variable 'user' referenced before assignment
But this works:
class Thing(object):
def doSomething(self):
import user
u = user.User(1)
print u... | [
"The code you've posted is missing something, because it works fine as shown.\nI'm guessing that your real code looks more like this:\nimport user\n\nclass Thing(object):\n\n def doSomething(self):\n u = user.User(1)\n print u.name\n # ...\n user = something\n\nThe problem is that by ... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0004404578_python.txt |
Q:
django ModelForm save issue with ManyToManyField
I'm new to Django and was needing some help on a view error i am getting.
I wrote a view that will display a data table of "Groups" if the request method is GET, or display a form to edit a particular "Group" if the request method is POST (item to edit is passed wi... | django ModelForm save issue with ManyToManyField | I'm new to Django and was needing some help on a view error i am getting.
I wrote a view that will display a data table of "Groups" if the request method is GET, or display a form to edit a particular "Group" if the request method is POST (item to edit is passed with POST data).
Also, if POST on an existing item, i'... | [
"Try to remove the intermediary models OctetAssignment and AliasAssignment. They should be used only when you want to add custom fields to them. Otherwise Django creates them and uses them transparently by itself.\n"
] | [
1
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0004403476_django_django_views_python.txt |
Q:
convert nested brackets into decimals
I have only just started working with Python and one of the exercises I got from my tutor is to convert a tuple (number of nested brackets) into decimals; I have been working on this for hours now, but I got nowhere...
e.g.
input = (((())))
output = 3
I started like this:
def ... | convert nested brackets into decimals | I have only just started working with Python and one of the exercises I got from my tutor is to convert a tuple (number of nested brackets) into decimals; I have been working on this for hours now, but I got nowhere...
e.g.
input = (((())))
output = 3
I started like this:
def add (x,y):
if y == '()':
return... | [
"You never change x. Presumably you want to add one to it before recursing. Also, constructs such as (()()) will trip you up.\n",
"print len(s) / 2\n\nAssuming you want to do this by recursion, you need to think about it a bit first. The point of recursion is to break the problem into smaller pieces which you kno... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004392503_python.txt |
Q:
debugging python web service
I am using the instructions found here, to try to inspect the HTTP commands being sent to my webserver.
However, I am not seeing the HTTP commands being printed on the console as suggested in the tutorial. Does anyone know how to display/debug the HTTP commands at the CLI?
I am runnin... | debugging python web service | I am using the instructions found here, to try to inspect the HTTP commands being sent to my webserver.
However, I am not seeing the HTTP commands being printed on the console as suggested in the tutorial. Does anyone know how to display/debug the HTTP commands at the CLI?
I am running Python 2.6.5 on Linux Ubuntu
| [
"The tutorial information seems to be deprecated. \nCorrect way to debug with urllib2 nowadays is:\nimport urllib2\nrequest = urllib2.Request('http://diveintomark.org/xml/atom.xml')\nopener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)) \nfeeddata = opener.open(request).read()\n\nDebugging with urllib... | [
16
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0004404654_python_urllib2.txt |
Q:
Windows 7 Task Scheduler & Python - Wallpaper doesn't change
I am attempting to run a Python script every five minutes to update a Windows 7 desktop background. It runs perfectly when started from the command-line, but not as a scheduled task.
The relevant code:
import ctypes
# According to MSDN/other websites
SP... | Windows 7 Task Scheduler & Python - Wallpaper doesn't change | I am attempting to run a Python script every five minutes to update a Windows 7 desktop background. It runs perfectly when started from the command-line, but not as a scheduled task.
The relevant code:
import ctypes
# According to MSDN/other websites
SPI_SETDESKWALLPAPER = 20
# Update wallpaper
ctypes.windll.user32.Sy... | [
"Make sure that the scheduled task is running with the same privilege as you.\n"
] | [
5
] | [] | [] | [
"python",
"scheduled_tasks",
"windows_7"
] | stackoverflow_0004404771_python_scheduled_tasks_windows_7.txt |
Q:
How to use Pylons / Mako templates to make an HTML email from a stand alone python script?
I'm basically asking how to "include" the plyons and mako files in a stand alone python script?
I have a working web site, but what I want to do is use Mako templetes to format emails that I initiate through a cron script. ... | How to use Pylons / Mako templates to make an HTML email from a stand alone python script? | I'm basically asking how to "include" the plyons and mako files in a stand alone python script?
I have a working web site, but what I want to do is use Mako templetes to format emails that I initiate through a cron script. I want to do it this way to reuse as much code as possible, as sometimes actions in the web sit... | [
"I have no experience with Pylons but to just render a template you can \nfrom mako.template import Template\n\nmytemplate = Template(filename='email.html')\nsendemail(\"text@example.com\", \"me@example.com\", mytemplate.render())\n\nThe \"standalone\" approach is basically the way Mako gets used with a lot of WSGI... | [
4
] | [] | [] | [
"mako",
"pylons",
"python"
] | stackoverflow_0004405066_mako_pylons_python.txt |
Q:
Python: mplot3d, graphing a solid
I'm trying to graph a wireframe solid of revolution. I'm following the example for a sphere here but I'm a bit at a loss. I've simplified everything down, but am now stuck on an error. I'm also looking at the function arguments described here, but unless I'm misunderstanding somet... | Python: mplot3d, graphing a solid | I'm trying to graph a wireframe solid of revolution. I'm following the example for a sphere here but I'm a bit at a loss. I've simplified everything down, but am now stuck on an error. I'm also looking at the function arguments described here, but unless I'm misunderstanding something, this code should be okay. I do re... | [
"When matplotlib writes data arguments in capital letters, that means it's expecting matrices of data. You can use the meshgrid function (see the example for mplot3d) to generate the grid.\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plot\nimport numpy\nimport pylab\n\nfig = plot.figure()\n... | [
3
] | [] | [] | [
"matplotlib",
"mplot3d",
"plot",
"python"
] | stackoverflow_0004405156_matplotlib_mplot3d_plot_python.txt |
Q:
Cant Connect to remote MS SQL server using PYODBC on Windows 7 in Python
So I am having some issues trying to connect to my server that is hosted on my network but on a different computer to the program I am trying to run. I have checked and both computers are on the same domain. I am coding in python and using PY... | Cant Connect to remote MS SQL server using PYODBC on Windows 7 in Python | So I am having some issues trying to connect to my server that is hosted on my network but on a different computer to the program I am trying to run. I have checked and both computers are on the same domain. I am coding in python and using PYODBC to make the connection.
The connect line is as follows:
connectLine = 'D... | [
"Some possibilities:\n(1) About this part of your connection string: SERVER=192.168.1.103\\OSBORNE; ... part of the definitely-non-generic error message says \"\"\"Error Locating Server/Instance Specified\"\"\"\nA note from connectionstrings.com: \n\"\"\"Are you using SQL Server 2005 Express? Don't miss the server ... | [
0
] | [] | [] | [
"python",
"sql_server"
] | stackoverflow_0004395122_python_sql_server.txt |
Q:
escape problem in django templates
Let's say that I have this string:
s = '<p>Hello!</p>'
When I pass this variable to a template, I want it to be rendered as raw html. Looking at the docs I see that I can either use the safe filter:
{{s|safe}}
or disable autoescape:
{%autoescape off}
{{s}}
{%endautoescape%}
or... | escape problem in django templates | Let's say that I have this string:
s = '<p>Hello!</p>'
When I pass this variable to a template, I want it to be rendered as raw html. Looking at the docs I see that I can either use the safe filter:
{{s|safe}}
or disable autoescape:
{%autoescape off}
{{s}}
{%endautoescape%}
or inside the python code declare it safe:... | [
"I think you should write as follows\n{{s|escape|safe}}\n\nit is ok for me\n",
"You pretty much covered it, those are indeed all the ways to disable autoescaping.\nAre you sure the value you are talking about is actually s = '<p>Hello!</p>'?\nMy hunch is that you have additional escaping somewhere in that string.... | [
10,
2
] | [
"Look at the HTML source code, is it escaped!??? I don't think so. It should be printing letter by letter, just like this:\n<\np\n>\nH\nE\nL\nL\nO\n<\n/\n>\n\n"
] | [
-4
] | [
"django",
"django_templates",
"html",
"python",
"rendering"
] | stackoverflow_0000871163_django_django_templates_html_python_rendering.txt |
Q:
Tuple Comparison
I`ve a dictionary defined like this :
d = {"date": tuple(date),"open":tuple(open),"close":tuple(close),"min":tuple(min),"max":tuple(max),"MA":tuple(ma)}
Each one of those tuples contains a list of values ( same number of values for each tuple ), how can I iterate trough each value of paticular ke... | Tuple Comparison | I`ve a dictionary defined like this :
d = {"date": tuple(date),"open":tuple(open),"close":tuple(close),"min":tuple(min),"max":tuple(max),"MA":tuple(ma)}
Each one of those tuples contains a list of values ( same number of values for each tuple ), how can I iterate trough each value of paticular keys to compare if "clos... | [
"what am I missing? d['close'] > d['MA']?\nEdit: Re, your comments \n\n[...] what I want to return is how many times one element of \"close\" is > to the matching element of MA . (same tuple index)\n\nsum( pair[0] > pair[1] for pair in zip(d['close'], d['MA']) )\n\n",
"From the Python docs:\n\n\nTuples and lists ... | [
1,
1
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0004405122_python_tuples.txt |
Q:
How come my javascript doesn't work when I put my HTML in an "include"?
{% include "abc.html" %}
In Django, I put my html in this.
Now, my javascript won't work.
$(function(){
alert('hi');
$(".div_inside_abc").css("background","#000");
});
I even tried putting this javascript inside abc.html (at the top).... | How come my javascript doesn't work when I put my HTML in an "include"? | {% include "abc.html" %}
In Django, I put my html in this.
Now, my javascript won't work.
$(function(){
alert('hi');
$(".div_inside_abc").css("background","#000");
});
I even tried putting this javascript inside abc.html (at the top). It still won't work.
When I do:
$(".div_inside_abc").each(function(e){
d... | [
"If you put JavaScript code inside HTML it won't execute (or be valid HTML). You have to wrap it in a SCRIPT tag if you're going to do it that way (which I don't advise) or as a DOM1 attribute.\nIf you want jQuery to run this function on load I'd suggest doing this in an externally referenced JavaScript file that's... | [
4,
0
] | [] | [] | [
"css",
"django",
"javascript",
"jquery",
"python"
] | stackoverflow_0004405217_css_django_javascript_jquery_python.txt |
Q:
My Python for loop is causing a MemoryError. How can I optimize this?
I'm trying to compile a list of all the MAC address Apple devices will have. oui.txt tells me Apple has been assigned 77 MAC ranges to use. These ranges come in the form of:
00:00:00
00:11:11
etc...
This leaves me the last three HEX digits to a... | My Python for loop is causing a MemoryError. How can I optimize this? | I'm trying to compile a list of all the MAC address Apple devices will have. oui.txt tells me Apple has been assigned 77 MAC ranges to use. These ranges come in the form of:
00:00:00
00:11:11
etc...
This leaves me the last three HEX digits to append. That's 16^6. A total of 1291845632 Apple MAC addresses.
The problem ... | [
"range(1, 1291845633) creates a list of 1,291,845,632 elements (several GB) all at once. Use xrange(1, 1291845633) instead and it will generate elements as you need them instead of all at once.\nRegardless, it looks like you want something more like this:\nfor mac in apple_mac_range: \n for i in xrange(16777216)... | [
18,
3,
1,
1,
0
] | [] | [] | [
"memory",
"optimization",
"out_of_memory",
"python"
] | stackoverflow_0004405083_memory_optimization_out_of_memory_python.txt |
Q:
How to make a FQL query with Python?
I do:
str('https://api.facebook.com/method/fql.query?query=') + query
then this should be queried and get the JSON data converted in Python, but how to do it?
A:
You should use something like urllib or pycurl to do http request and then use json library to decode received d... | How to make a FQL query with Python? | I do:
str('https://api.facebook.com/method/fql.query?query=') + query
then this should be queried and get the JSON data converted in Python, but how to do it?
| [
"You should use something like urllib or pycurl to do http request and then use json library to decode received data. I believe documentation on each module is very detailed, so it should be sufficient.\n"
] | [
3
] | [] | [] | [
"facebook_fql",
"python"
] | stackoverflow_0004404469_facebook_fql_python.txt |
Q:
is this django validation code too old to use
i find a django validation code ,but i find it was written 3 years ago ,
so is it too old to use?
has some better way to validation in django
this is the code :
class UserField(forms.CharField):
def clean(self, value):
super(UserField, self).clean(value... | is this django validation code too old to use | i find a django validation code ,but i find it was written 3 years ago ,
so is it too old to use?
has some better way to validation in django
this is the code :
class UserField(forms.CharField):
def clean(self, value):
super(UserField, self).clean(value)
try:
User.objects.get(username... | [
"My advice is: don't.\nI don't know if this was correct at the time and I'm not willing to test if it still works, but it looks really, really old.\nIt somewhat resembles the examples in the fine docs, take a look and you will be able to figure out what changed over the last 3 years.\n"
] | [
0
] | [] | [] | [
"django",
"python",
"validation"
] | stackoverflow_0004405161_django_python_validation.txt |
Q:
python passing argument to a function
folks, i got a question about passing mutable object to a function
with the following code, I was expecting the output to be [0,0,0], while the output is [0,1,2,3]
does it mean the argument is actually copied and then send to the inside of the function?
def lala(a):
n = [0... | python passing argument to a function | folks, i got a question about passing mutable object to a function
with the following code, I was expecting the output to be [0,0,0], while the output is [0,1,2,3]
does it mean the argument is actually copied and then send to the inside of the function?
def lala(a):
n = [0, 0 , 0]
a = n
a = [0,1,2,3]
lala(a)
... | [
"Python makes more sense if you think of attaching name tags to objects, rather than stuffing objects into named boxes.\ndef lala(a):\n n = [0, 0 , 0]\n a = n\n\nHere's what's happening.\n\nYou're receiving a parameter (a list in this case) and giving it the name a.\nYou're creating a new list and giving it t... | [
8,
3,
2,
2,
1,
0
] | [] | [] | [
"arguments",
"function",
"python"
] | stackoverflow_0004405349_arguments_function_python.txt |
Q:
Distributing Python packages which depend on in-house common convenience libraries
I have a few Python packages that I would like to tidy up and publish on PyPI. These packages import a couple of Python modules I've written to augment or simplify certain operations (e.g., reading/writing from CSV files with header... | Distributing Python packages which depend on in-house common convenience libraries | I have a few Python packages that I would like to tidy up and publish on PyPI. These packages import a couple of Python modules I've written to augment or simplify certain operations (e.g., reading/writing from CSV files with headers by wrapping csv functions), provide handy data structures, etc. Currently these module... | [
"You don't say why you're hesitant to 'provide copies'. In general, I think a reasonable approach is to think about how you've set things up for yourself to use the convenience modules. Did you install them in site-packages (or equivalent), or did you just depend on them being in the directory you ran the code from... | [
3,
2
] | [] | [] | [
"distribution",
"packaging",
"python"
] | stackoverflow_0004404486_distribution_packaging_python.txt |
Q:
how to post data to particular url?
I want to post some data in the particular url say http://localhost:8000/postme/. But I have know form yet. So, I want to test it without any form. So, How can I post data to the url without any form? I want to see the response to the web browser.
A:
You can do an Ajax post us... | how to post data to particular url? | I want to post some data in the particular url say http://localhost:8000/postme/. But I have know form yet. So, I want to test it without any form. So, How can I post data to the url without any form? I want to see the response to the web browser.
| [
"You can do an Ajax post using jQuery. See this page for the API.\nOr for Python, you can use httplib. See this page for the API. Here's an example:\n>>> import httplib, urllib\n>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})\n>>> headers = {\"Content-type\": \"application/x-www-form-urlencoded\",... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0004397077_python.txt |
Q:
Exception when using filter to retrieve a django model
To retrieve a django object, I am using the filter function as follows:
product = Product.objects.filter(code=request.POST['code'])
Then, when I try to access the retrieved object as:
product[0].description
I get an exception "list index out of range". Alth... | Exception when using filter to retrieve a django model | To retrieve a django object, I am using the filter function as follows:
product = Product.objects.filter(code=request.POST['code'])
Then, when I try to access the retrieved object as:
product[0].description
I get an exception "list index out of range". Although, the filter is indeed returning an object because the l... | [
"You should probably validate that request.POST['code'] is valid before you try to use it in anything:\n# code will be None if it isn't found in request.POST\ncode = request.POST.get('code')\nif code:\n products = Product.objects.filter(code=code)\n for product in products:\n print product.description\... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004400663_django_python.txt |
Q:
HTTP POST from jquery to django running on google app engine
I'm not sure what is wrong..
On my html file I'm doing the following:
$.post("some_page", {
param1: "something" , "param2": "something 2"
}, function(data) {
alert(data)
}, "json");
On the python file qwerty.py to which I'm posting I have foll... | HTTP POST from jquery to django running on google app engine | I'm not sure what is wrong..
On my html file I'm doing the following:
$.post("some_page", {
param1: "something" , "param2": "something 2"
}, function(data) {
alert(data)
}, "json");
On the python file qwerty.py to which I'm posting I have following:
def some_page(request):
param1 = request.POST['param1']
p... | [
"Make sure that you don't quote the keys in your $.post data dictionary as you did with 'param2' above.\n$.post(\"some_page\", {\n param1: \"something\",\n param2: \"something 2\"\n }, function(data) {\n alert(data)\n }, \"json\");\n\nAlso, when you attempt to get the value out of a dict ... | [
0
] | [] | [] | [
"django",
"jquery",
"python"
] | stackoverflow_0004405259_django_jquery_python.txt |
Q:
Numpy solver : max value
I`ve got 2 variables :
period and result
How would I tell the Numpy solver ( I assume that's what I would have to use ) to return the period value that gives me the highest result ? Period has to be between 1 and 100 .
Edit :
Right now period at 14, gives me a result of 40 .
period at 12 .... | Numpy solver : max value | I`ve got 2 variables :
period and result
How would I tell the Numpy solver ( I assume that's what I would have to use ) to return the period value that gives me the highest result ? Period has to be between 1 and 100 .
Edit :
Right now period at 14, gives me a result of 40 .
period at 12 . gives me a result of 42 .
Can... | [
"Just declare a variable equal to the period value of the first, then do your own loop, changing the initial variable any time the current number is bigger:\nbiggest = period(0)\nindex = 0\n\nfor i in range (1, 100)\n if period(i) > biggest\n biggest = period(i)\n index = i\n\nreturn biggest\n\n"... | [
1,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004405830_numpy_python.txt |
Q:
How to retrieve the sql code from an Excel 2007 PivotTable
I have a pivot table, which I want to recreate programatically through python. Is there way to retrieve the current sql code of the pivot table for me to use it in python?
A:
I wrote this recently. It might work for you. It attempts to copy pivot cache... | How to retrieve the sql code from an Excel 2007 PivotTable | I have a pivot table, which I want to recreate programatically through python. Is there way to retrieve the current sql code of the pivot table for me to use it in python?
| [
"I wrote this recently. It might work for you. It attempts to copy pivot cache and/or query table data for the active workbook to the clipboard. It's surrounded by On Error Resume Next so if it doesn't find a particular piece of data it keeps going:\nSub Copy_Connection_Info_To_Clipboard()\n\nDim ptCache As Exce... | [
2
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0004402969_excel_python.txt |
Q:
App Engine ( Python ) and Provisioning API
I'm trying pull out a list of AllUsers from a Google Apps Domain.
So far I've come to this http://code.google.com/googleapps/domain/gdata_provisioning_api_v2.0_reference_python.html
A provisioning API that does do what I need but returns a UserFeed object? Some sort of A... | App Engine ( Python ) and Provisioning API | I'm trying pull out a list of AllUsers from a Google Apps Domain.
So far I've come to this http://code.google.com/googleapps/domain/gdata_provisioning_api_v2.0_reference_python.html
A provisioning API that does do what I need but returns a UserFeed object? Some sort of Atom field?
Im not sure where to go from there.
A... | [
"Try this:\nimport gdata.apps\nimport gdata.apps.service\nimport gdata.alt.appengine\n\nservice = gs.AppsService(email=\"[[ account email with admin privs ]]\",domain=\"[[ google apps domain ]]\",password=\"[[ account password ]]\")\n\ngdata.alt.appengine.run_on_appengine(service)\n\nservice.ProgrammaticLogin()\nus... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004405193_google_app_engine_python.txt |
Q:
python regular expression help
Need to match any string ends up with a letter, and the second last character is '>'
It will match:
abc>a
ddd_4>f
It will not match:
abc>ab
abc>2
A:
>>> import re
>>> s = 'abc>a'
>>> r = re.compile(r'>[:alpha:]$')
>>> print( r.search(s) )
<_sre.SRE_Match object at 0xb76c5a30>
>>> ... | python regular expression help | Need to match any string ends up with a letter, and the second last character is '>'
It will match:
abc>a
ddd_4>f
It will not match:
abc>ab
abc>2
| [
">>> import re\n>>> s = 'abc>a'\n>>> r = re.compile(r'>[:alpha:]$')\n>>> print( r.search(s) )\n<_sre.SRE_Match object at 0xb76c5a30>\n>>> \n\nIf you want to match letters according to locales.\n",
"re.compile(r'.*>[a-zA-Z]$')\n\nshould generate the pattern that you want.\nHowever, I recommend that you take a read... | [
3,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004406571_python_regex.txt |
Q:
what are python web frameworks
I've asked this question on some places but I never get a completely straight answer. I've heard a lot about web frameworks and only know a basic understanding. Okay is a web framework installed on top of server architecture like apache or is it its own thing?
I've read a good amount... | what are python web frameworks | I've asked this question on some places but I never get a completely straight answer. I've heard a lot about web frameworks and only know a basic understanding. Okay is a web framework installed on top of server architecture like apache or is it its own thing?
I've read a good amount about web frameworks and I like wha... | [
"It can be \"its own thing\", meaning it can listen on a port and service requests without Apache; or it can run under Apache or any other web server, for example as a CGI script. For an easy-to-swallow overview, see http://bitworking.org/news/Why_so_many_Python_web_frameworks\nAlso see What exactly is a web applic... | [
2,
1
] | [] | [] | [
"cgi",
"python",
"web_applications",
"web_frameworks"
] | stackoverflow_0004406676_cgi_python_web_applications_web_frameworks.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.