title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Serializing a Python namedtuple to json
5,906,831
38
2011-05-06T04:34:56Z
6,572,104
11
2011-07-04T13:21:09Z
[ "python", "json", "namedtuple" ]
What is the recommended way of serializing a [`namedtuple`](http://docs.python.org/dev/library/collections.html#collections.namedtuple) to json with the field names retained? Serializing a `namedtuple` to json results in only the values being serialized and the field names being lost in translation. I would like the f...
It looks like you used to be able to subclass `simplejson.JSONEncoder` to make this work, but with the latest simplejson code, that is no longer the case: you have to actually modify the project code. I see no reason why simplejson should not support namedtuples, so I forked the project, added namedtuple support, and I...
Serializing a Python namedtuple to json
5,906,831
38
2011-05-06T04:34:56Z
15,800,273
20
2013-04-03T23:55:52Z
[ "python", "json", "namedtuple" ]
What is the recommended way of serializing a [`namedtuple`](http://docs.python.org/dev/library/collections.html#collections.namedtuple) to json with the field names retained? Serializing a `namedtuple` to json results in only the values being serialized and the field names being lost in translation. I would like the f...
If it's just one `namedtuple` you're looking to serialize, using its `__dict__` property will work (with Python >= 2.7) ``` >>> from collections import namedtuple >>> import json >>> FB = namedtuple("FB", ("foo", "bar")) >>> fb = FB(123, 456) >>> json.dumps(fb.__dict__) '{"foo": 123, "bar": 456}' ```
how to create a dynamically-created radio buttons form in django
5,907,193
2
2011-05-06T05:34:54Z
5,907,351
7
2011-05-06T05:58:06Z
[ "python", "django" ]
![enter image description here](http://i.stack.imgur.com/OQsK0.png) hello . im new to django and i want to create a form that looks like the image above in html. the form should save the data when the user chose a radio button. how to implement such a form in django ( please note that user cannot chose more than one...
You want to use [ChoiceField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield) and [RadioSelect](http://docs.djangoproject.com/en/1.3/ref/forms/widgets/#django.forms.RadioSelect): ``` from django import forms class GenderForm(forms.Form): CHOICES = ( ('M', 'Male'), ('F', 'Female...
Installing second python on Debian
5,907,352
15
2011-05-06T05:58:08Z
5,907,498
21
2011-05-06T06:16:12Z
[ "python", "debian", "virtualenv" ]
So I have Debian machine for my Django production server. I need to install second python (2.7.1) to use with virtualenv. But it always write I don't have some modules, then I have to search manually, apt-install them and rebuild. Is there either a way to resolve the dependencies for building, or pre-compiled .deb with...
Get the Python 2.7.1 sources and compile it manually: ``` configure --prefix=/path/to/python-2.7 make; make install ```
Installing second python on Debian
5,907,352
15
2011-05-06T05:58:08Z
5,908,622
12
2011-05-06T08:14:06Z
[ "python", "debian", "virtualenv" ]
So I have Debian machine for my Django production server. I need to install second python (2.7.1) to use with virtualenv. But it always write I don't have some modules, then I have to search manually, apt-install them and rebuild. Is there either a way to resolve the dependencies for building, or pre-compiled .deb with...
[Python 2.7 is available for *wheezy* (testing)](http://packages.debian.org/wheezy/python2.7), so you should be able to install it by adding the `testing` repository and doing some [APT pinning](http://wiki.debian.org/AptPreferences#Pinning). 1) add the repository in **/etc/apt/sources.list** ``` deb http://ftp.us.de...
Installing second python on Debian
5,907,352
15
2011-05-06T05:58:08Z
17,713,425
9
2013-07-18T02:17:40Z
[ "python", "debian", "virtualenv" ]
So I have Debian machine for my Django production server. I need to install second python (2.7.1) to use with virtualenv. But it always write I don't have some modules, then I have to search manually, apt-install them and rebuild. Is there either a way to resolve the dependencies for building, or pre-compiled .deb with...
Here is two methods for Debian GNU/Linux 6.0.7 (on 18/07/2013): # The classic Install dependencies ``` aptitude -y install build-essential python-pip libmysqlclient-dev libadns1-dev \ python-dev libreadline-dev libgdbm-dev zlib1g-dev libsqlite3-dev \ libssl-dev libbz2-dev libncurses5-dev libdb-dev ``` Download py...
Adding attributes to python objects
5,907,937
27
2011-05-06T07:07:35Z
5,907,969
42
2011-05-06T07:10:18Z
[ "python", "object", "attributes" ]
It's a thing that bugged me for a while. Why can't I do: ``` >>> a = "" >>> a.foo = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'foo' ``` ...while I can do the following? ``` >>> class Bar(): ... pass ... >>> a = Bar() >>> a.foo = 10 #...
You can add attributes to any object that has a `__dict__`. * `x = object()` doesn't have it, for example. * Strings and other simple builtin objects also don't have it. * Classes using `__slots__` also do not have it. * Classes defined with `class` have it unless the previous statement applies. If an object is using...
how to fill a list with 0 using python
5,908,420
28
2011-05-06T07:56:50Z
5,908,462
60
2011-05-06T08:00:04Z
[ "python", "list" ]
I want to get a fixed length list from another list like: ``` a = ['a','b','c'] b = [0,0,0,0,0,0,0,0,0,0] ``` And I want to get a list like this: `['a','b','c',0,0,0,0,0,0,0]`. In other words, if `len(a) < len(b)`, i want to fill up list `a` with values from list `b` up to length of the list `b`, somewhat similar to ...
Why not just: ``` a = a + [0]*(maxLen - len(a)) ```
how to fill a list with 0 using python
5,908,420
28
2011-05-06T07:56:50Z
5,908,502
19
2011-05-06T08:03:24Z
[ "python", "list" ]
I want to get a fixed length list from another list like: ``` a = ['a','b','c'] b = [0,0,0,0,0,0,0,0,0,0] ``` And I want to get a list like this: `['a','b','c',0,0,0,0,0,0,0]`. In other words, if `len(a) < len(b)`, i want to fill up list `a` with values from list `b` up to length of the list `b`, somewhat similar to ...
Use itertools repeat. ``` >>> from itertools import repeat >>> a + list(repeat(0, 6)) ['a', 'b', 'c', 0, 0, 0, 0, 0, 0] ```
How can I pretty-print ASCII tables with Python?
5,909,873
38
2011-05-06T10:09:21Z
5,910,078
33
2011-05-06T10:28:25Z
[ "python", "table", "ascii" ]
I'm looking for a Python library for printing tables like this: ``` ======================= | column 1 | column 2 | ======================= | value1 | value2 | | value3 | value4 | ======================= ``` I've found [asciitable](http://cxc.harvard.edu/contrib/asciitable/) but it doesn't do the borders etc....
Here's a quick and dirty little function I wrote for displaying the results from SQL queries I can only make over a SOAP API. It expects an input of a sequence of one or more `namedtuples` as table rows. If there's only one record, it prints it out differently. It is handy for me and could be a starting point for you:...
How can I pretty-print ASCII tables with Python?
5,909,873
38
2011-05-06T10:09:21Z
5,910,332
14
2011-05-06T10:54:38Z
[ "python", "table", "ascii" ]
I'm looking for a Python library for printing tables like this: ``` ======================= | column 1 | column 2 | ======================= | value1 | value2 | | value3 | value4 | ======================= ``` I've found [asciitable](http://cxc.harvard.edu/contrib/asciitable/) but it doesn't do the borders etc....
For some reason when I included 'docutils' in my google searches I stumbled across [texttable](http://pypi.python.org/pypi?name=texttable&%3aaction=display), which seems to be what I'm looking for.
How can I pretty-print ASCII tables with Python?
5,909,873
38
2011-05-06T10:09:21Z
11,515,603
17
2012-07-17T03:24:46Z
[ "python", "table", "ascii" ]
I'm looking for a Python library for printing tables like this: ``` ======================= | column 1 | column 2 | ======================= | value1 | value2 | | value3 | value4 | ======================= ``` I've found [asciitable](http://cxc.harvard.edu/contrib/asciitable/) but it doesn't do the borders etc....
okay old thread,, but the best I've found for this is [Prettytable](http://code.google.com/p/prettytable/)... are there better?
How can I pretty-print ASCII tables with Python?
5,909,873
38
2011-05-06T10:09:21Z
15,344,226
20
2013-03-11T16:57:16Z
[ "python", "table", "ascii" ]
I'm looking for a Python library for printing tables like this: ``` ======================= | column 1 | column 2 | ======================= | value1 | value2 | | value3 | value4 | ======================= ``` I've found [asciitable](http://cxc.harvard.edu/contrib/asciitable/) but it doesn't do the borders etc....
I've read this question long time ago, and finished writing my own pretty-printer for tables: [`tabulate`](https://pypi.python.org/pypi/tabulate). My use case is: * I want a one-liner most of the time * which is smart enough to figure the best formatting for me * and can output different plain-text formats Given you...
How can I pretty-print ASCII tables with Python?
5,909,873
38
2011-05-06T10:09:21Z
26,553,487
7
2014-10-24T17:52:31Z
[ "python", "table", "ascii" ]
I'm looking for a Python library for printing tables like this: ``` ======================= | column 1 | column 2 | ======================= | value1 | value2 | | value3 | value4 | ======================= ``` I've found [asciitable](http://cxc.harvard.edu/contrib/asciitable/) but it doesn't do the borders etc....
I too wrote my own solution to this. I tried to keep it simple. <https://github.com/Robpol86/terminaltables> ``` from terminaltables import AsciiTable table_data = [ ['Heading1', 'Heading2'], ['row1 column1', 'row1 column2'], ['row2 column1', 'row2 column2'] ] table = AsciiTable(table_data) print table.ta...
Python - How to send utf-8 e-mail?
5,910,104
22
2011-05-06T10:31:47Z
5,910,530
52
2011-05-06T11:09:50Z
[ "python", "email", "utf-8", "smtp" ]
how to send utf8 e-mail please? ``` import sys import smtplib import email import re from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def sendmail(firm, fromEmail, to, template, subject, date): with open(template, encoding="utf-8") as template_file: message = template_f...
You should just add `'utf-8'` argument to your `MIMEText` calls (it assumes `'us-ascii'` by default). For example: ``` # -*- encoding: utf-8 -*- from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText msg = MIMEMultipart("alternative") msg["Subject"] = u'テストメール' part1 = MIMET...
Difference between closures in python and javascript
5,910,146
7
2011-05-06T10:37:00Z
5,910,361
8
2011-05-06T10:56:48Z
[ "javascript", "python", "closures" ]
In JS, we can write closure like: ``` function f(){ var a=0; function g(){ alert(a++); } return g; } g=f() g() ``` However, if I write following code in python ``` def f(): a=0 def g(): a+=1 print a return g g=f() g() ``` Then I get *UnboundedLocalError*. Can anyone tell me the diff...
When you use `a += 1` in Python it refers to a local (uninitialized) variable in scope of `g` function. Basically you can read variables from upper scopes, but if you try to write it will refer to a variable in most recent scope. To make it work like you want you have to use `nonlocal` keyword that is only present Pyth...
Importing modules in Python and __init__.py
5,910,379
25
2011-05-06T10:58:20Z
5,910,426
15
2011-05-06T11:02:06Z
[ "python", "module", "import" ]
I have been reading about the function of `__init__.py` file. It is said that we need an empty `__init__.py` file in the folder which contains modules, so that these modules can be imported. However, I tried adding a folder path to PYTHONPATH (Environment Variable in Windows 7). Although this folder does not contain an...
`__init__.py` turns a folder into a [package](http://docs.python.org/tutorial/modules.html#packages). This is useful to create a sort of hierarchy of modules, where you can have import-statements like this: ``` import mymodule.cool.stuff ``` This is not possible without packages.
Importing modules in Python and __init__.py
5,910,379
25
2011-05-06T10:58:20Z
5,910,430
8
2011-05-06T11:02:20Z
[ "python", "module", "import" ]
I have been reading about the function of `__init__.py` file. It is said that we need an empty `__init__.py` file in the folder which contains modules, so that these modules can be imported. However, I tried adding a folder path to PYTHONPATH (Environment Variable in Windows 7). Although this folder does not contain an...
If a directory (folder) contains a `__init__.py` file then it becomes a *package*. What you thought you read was not strictly correct, as you found. A package can be imported as if it was a module by itself, and any code in `__init__.py` is run, although it is often empty. Packages are a way of grouping multiple module...
Importing modules in Python and __init__.py
5,910,379
25
2011-05-06T10:58:20Z
21,166,205
8
2014-01-16T15:38:54Z
[ "python", "module", "import" ]
I have been reading about the function of `__init__.py` file. It is said that we need an empty `__init__.py` file in the folder which contains modules, so that these modules can be imported. However, I tried adding a folder path to PYTHONPATH (Environment Variable in Windows 7). Although this folder does not contain an...
The difference between **having \_*init*\_.py** and **not having** one in your module directory is: When you **have** `__init__.py` (blank one), you can import the module using ``` from dirname import MyModule ``` But when you **dont have** \_*init*\_.py at all, you cannot import the module without adding the path t...
Howto get all methods of a python class with given decorator
5,910,703
50
2011-05-06T11:23:38Z
5,910,893
71
2011-05-06T11:41:21Z
[ "python", "class", "methods", "decorator", "inspect" ]
How to get all methods of a given class A that are decorated with the @decorator2? ``` class A(): def method_a(self): pass @decorator1 def method_b(self, b): pass @decorator2 def method_c(self, t=5): pass ```
### Method 1: Basic registering decorator I already answered this question here: [Calling functions by array index in Python](http://stackoverflow.com/questions/5707589/calling-functions-by-array-index-in-python/5707605#5707605) =) --- ### Method 2: Sourcecode parsing *If you do not have control over the **class** ...
Howto get all methods of a python class with given decorator
5,910,703
50
2011-05-06T11:23:38Z
9,580,006
9
2012-03-06T08:11:45Z
[ "python", "class", "methods", "decorator", "inspect" ]
How to get all methods of a given class A that are decorated with the @decorator2? ``` class A(): def method_a(self): pass @decorator1 def method_b(self, b): pass @decorator2 def method_c(self, t=5): pass ```
To expand upon @ninjagecko's excellent answer in Method 2: Source code parsing, you can use the `ast` module introduced in Python 2.6 to perform self-inspection as long as the inspect module has access to the source code. ``` def findDecorators(target): import ast, inspect res = {} def visit_FunctionDef(no...
Matplotlib quiver scale
5,911,439
7
2011-05-06T12:30:17Z
5,911,947
7
2011-05-06T13:12:33Z
[ "python", "matplotlib", "scale", "arrow" ]
I'm trying to plot some arrows using matploblib with the quiver function. But I want to choose the length of each arrow individually using an array. <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.quiver> [<http://matplotlib.sourceforge.net/examples/pylab_examples/quiver_demo.html>](http://mat...
To specify each arrow's location and vector *and* length is an over-specification of the quiver plot. So what you need to do is change the data that you are plotting. If you have the vector field U and V (same U and V as your examples), you can normalize them by: ``` N = numpy.sqrt(U**2+V**2) # there may be a faster...
Pymongo / MongoDB: create index or ensure index?
5,912,661
37
2011-05-06T14:12:48Z
5,914,380
37
2011-05-06T16:35:37Z
[ "python", "mongodb", "pymongo" ]
I don't understand the difference between `create_index` and `ensure_index` in pymongo. On the [MongoDB indexes page](http://docs.mongodb.org/manual/core/indexes/), it says > you can create an index by calling the > `ensureIndex()` However in pymongo there are two different commands [`create_index`](http://api.mongod...
@andreas-jung is right in that `ensure_index()` is a wrapper over `create_index()`, I think the confusion arises with the phrase: > When an index is created (or ensured) > by PyMongo it is “remembered” for ttl > seconds. It's not that the index is temporary or "transient", what happens is that during the specifie...
Pymongo / MongoDB: create index or ensure index?
5,912,661
37
2011-05-06T14:12:48Z
10,552,429
9
2012-05-11T13:35:29Z
[ "python", "mongodb", "pymongo" ]
I don't understand the difference between `create_index` and `ensure_index` in pymongo. On the [MongoDB indexes page](http://docs.mongodb.org/manual/core/indexes/), it says > you can create an index by calling the > `ensureIndex()` However in pymongo there are two different commands [`create_index`](http://api.mongod...
The `ensureIndex` method in the Interactive Shell and `ensure_index` in the python driver are different things, although the same word is used. Both the `create_index` and `ensure_index` method from the python driver create an index permanently. Maybe one would use `ensure_index` with a reasonable TTL in such a situat...
Pymongo / MongoDB: create index or ensure index?
5,912,661
37
2011-05-06T14:12:48Z
30,314,946
8
2015-05-19T00:38:36Z
[ "python", "mongodb", "pymongo" ]
I don't understand the difference between `create_index` and `ensure_index` in pymongo. On the [MongoDB indexes page](http://docs.mongodb.org/manual/core/indexes/), it says > you can create an index by calling the > `ensureIndex()` However in pymongo there are two different commands [`create_index`](http://api.mongod...
Keep in mind that in Mongo 3.x [ensureIndex](http://docs.mongodb.org/manual/reference/method/db.collection.ensureIndex/) is deprecated and should be discouraged. > Deprecated since version 3.0.0: db.collection.ensureIndex() is now an alias for db.collection.createIndex(). The same is in [pymongo](http://api.mongodb.o...
wxpython scrolled Panel Not Updating scroll bars
5,912,761
4
2011-05-06T14:21:09Z
5,914,064
7
2011-05-06T16:08:25Z
[ "python", "wxpython", "scrolledwindow" ]
I'm using winxp and wxpython ( wxpython 3.1, python 2.6 ) to make a GUI program which will copy the text from a TextCtrl, into a ScrollablePanel that contains a StaticText. This all works fine, however, the Scrolled part doesn't work quite right. It seems like it won't update in real time. When I ummaximize the window ...
It would be better if you'll post something that could be running right after copy and paste. Anyway it appears that you missed the following things that are mandatory to make scrolled panel works: 1. Scrolled panel must have a sizer. This could be done via `self.test_panel.SetSizer(self.a_sizer)` method. All other c...
Complexity of list.index(x) in Python
5,913,671
11
2011-05-06T15:34:45Z
5,913,745
13
2011-05-06T15:40:55Z
[ "python", "algorithm", "list", "big-o", "performance" ]
I'm referring to this: <http://docs.python.org/tutorial/datastructures.html> What would be the running time of `list.index(x)` function in terms of big O notation?
It's O(n), also check out: <http://wiki.python.org/moin/TimeComplexity> > This page documents the time-complexity (aka "Big O" or "Big Oh") of various operations in current CPython. Other Python implementations (or older or still-under development versions of CPython) may have slightly different performance characteri...
Reportlab : How to switch between portrait and landscape?
5,913,682
13
2011-05-06T15:35:26Z
5,936,903
10
2011-05-09T12:30:28Z
[ "python", "reportlab" ]
I am using reportlab to generate a pdf report automatically from dynamic data. As the content sometimes is too large to be displayed in portrait, I am trying to switch to landscape for large content. Here is how my report generation works : Main function : ``` doc = DocTemplate(...) //Doctemplate is a cust...
I finally figured out the best way to do it by myself : I added a new PageTemplate in my DocTemplate with landscape settings, and then simply used NextPageTemplate from the reportlab.platypus package : `array.append(NextPageTemplate('landscape'))` To get back in portrait, i use : `array.append(NextPageTemplate('por...
Reportlab : How to switch between portrait and landscape?
5,913,682
13
2011-05-06T15:35:26Z
10,908,455
23
2012-06-06T05:09:09Z
[ "python", "reportlab" ]
I am using reportlab to generate a pdf report automatically from dynamic data. As the content sometimes is too large to be displayed in portrait, I am trying to switch to landscape for large content. Here is how my report generation works : Main function : ``` doc = DocTemplate(...) //Doctemplate is a cust...
Use the landscape and portrait functions that are already in the pagesizes module. ``` from reportlab.lib.pagesizes import letter, landscape c = canvas.Canvas(file, pagesize=landscape(letter)) ```
In Python on Unix, determine if I am using my computer? or idle?
5,914,506
6
2011-05-06T16:40:46Z
5,915,422
7
2011-05-06T18:17:57Z
[ "python", "networking", "keyboard", "python-idle" ]
I would like to write a script to do an heavy network upload, in the background. However, I would like it to pause when I am using my computer (either by detecting network activity or keyboard activity or that I am not idle). What is the best way to detect that I am using the computer, on Python on Unix?
Unixy solution using X11/XScreenSaver to get idle time: ``` #!/usr/bin/python import ctypes import os class XScreenSaverInfo( ctypes.Structure): """ typedef struct { ... } XScreenSaverInfo; """ _fields_ = [('window', ctypes.c_ulong), # screen saver window ('state', ctypes.c_int), # off,...
Prepend line to beginning of a file
5,914,627
21
2011-05-06T16:56:31Z
5,914,636
12
2011-05-06T16:57:12Z
[ "python" ]
I can do this with using a separate file but how do i append a line to the beginning of a file? ``` f=open('log.txt','a') f.seek(0) #get to the first position f.write("text") f.close() ``` This starts writing from the end of the file since the file is opened in append mode.
In all filesystems that I am familiar with, you can't do this in-place. You have to use an auxiliary file (which you can then rename to take the name of the original file).
Prepend line to beginning of a file
5,914,627
21
2011-05-06T16:56:31Z
5,917,395
39
2011-05-06T21:52:20Z
[ "python" ]
I can do this with using a separate file but how do i append a line to the beginning of a file? ``` f=open('log.txt','a') f.seek(0) #get to the first position f.write("text") f.close() ``` This starts writing from the end of the file since the file is opened in append mode.
In mode **'a'** or **'a+'** , any writing is done at the end of the file, even if at the current moment when the **write()** function is triggered the file's pointer is not at the end of the file: the pointer is moved to the end of file before any writing. You can do what you want in two manners. **1st way**, can be u...
Python ctypes MemoryError in fcgi process from PIL library
5,914,673
11
2011-05-06T17:00:53Z
6,620,077
23
2011-07-08T04:48:12Z
[ "python", "django", "python-imaging-library", "fastcgi" ]
I'm trying to run Django on shared hosting (Bluehost). I'm using functionality that requires PIL. PIL imports and works from an interactive shell, but in my fcgi process it crashes with a MemoryError at from PIL import image. Any help on why it might be failing inside fcgi would be much appreciated. ``` __Environment ...
I have temporarily fixed that error commenting the last line in this file `$HOME/lib/python2.7/ctypes/__init__.py` that is something like `#CFUNCTYPE(c_int)(lambda: None)`. That's work for me, but i don't know what exactly the problem is. Bye **UPDATE** In python 2.7.3 the line number is :279 not the last as I said...
Upload a file-like object with Paramiko?
5,914,761
5
2011-05-06T17:10:57Z
5,915,059
8
2011-05-06T17:43:45Z
[ "python", "paramiko" ]
I have a bunch of code that looks like this: ``` with tempfile.NamedTemporaryFile() as tmpfile: tmpfile.write(fileobj.read()) # fileobj is some file-like object tmpfile.flush() try: self.sftp.put(tmpfile.name, path) except IOError: # error handling removed for ease of reading pa...
**Update** As of Paramiko *1.10*, you can use [putfo](http://docs.paramiko.org/en/1.16/api/sftp.html#paramiko.sftp_client.SFTPClient.putfo): ``` self.sftp.putfo(fileobj, path) ``` --- Instead of using `paramiko.SFTPClient.put`, you can use `paramiko.SFTPClient.open`, which opens a `file`-like object. You can write t...
How to determine if your app is running on local Python Development Server?
5,914,802
13
2011-05-06T17:14:33Z
5,914,957
35
2011-05-06T17:32:48Z
[ "python", "google-app-engine" ]
I need to programatically determine if my app is running in development or not, so that I can provide sandbox values for a variety of constants and methods. Something like: ``` if app.development: # Live mode FREEBASE_USER = "spam123" FREEBASE_PSWD = "eggs123" FREEBASE = freebase else: # Sandbox mode FREEBAS...
``` import os DEV = os.environ['SERVER_SOFTWARE'].startswith('Development') ```
Python: telling a raw string (r'') from a string ('')
5,915,940
7
2011-05-06T19:09:12Z
5,915,971
13
2011-05-06T19:13:02Z
[ "python", "regex", "string" ]
I'm currently building a tool that will have to match filenames against a pattern. For convenience, I intend to provide both lazy matching (in a glob-like fashion) and regexp matching. For example, the following two snippets would eventually have the same effects: ``` @mylib.rule('static/*.html') def myfunc(): pas...
You can't tell them apart. Every raw string literal could also be written as a standard string literal (possibly requiring more quoting) and vice versa. Apart from this, I'd definitely give different names to the two decorators. They don't do the same things, they do different things. Example (CPython): ``` >>> a = r...
Python: telling a raw string (r'') from a string ('')
5,915,940
7
2011-05-06T19:09:12Z
5,916,054
9
2011-05-06T19:20:52Z
[ "python", "regex", "string" ]
I'm currently building a tool that will have to match filenames against a pattern. For convenience, I intend to provide both lazy matching (in a glob-like fashion) and regexp matching. For example, the following two snippets would eventually have the same effects: ``` @mylib.rule('static/*.html') def myfunc(): pas...
You can't tell whether a string was defined as a raw string after the fact. Personally, I would in fact use a separate decorator, but if you don't want to, you could use a named parameter (e.g. `@rule(glob="*.txt")` for globs and `@rule(re=r".+\.txt")` for regex). Alternatively, require users to provide a compiled reg...
Nested django templates
5,915,942
3
2011-05-06T19:09:21Z
5,916,250
7
2011-05-06T19:41:57Z
[ "python", "django", "django-templates", "nested" ]
This seems like a pretty basic thing to do but although I've been using Django for around a year, I've never run into this scenario yet. In a lot of templating/web frameworks, template inheritance works a bit differently, in that usually it behaves more like wrappers, so if you have childtemplate.html, parenttemplate....
the extends template tag can take a variable argument. so: ``` base.html {% block content %} <p>BASE</p> {% endblock %} parent.html {% extends "base.html" %} {% block content %} {{ block.super }} <p>PARENT</p> {% endblock %} foo.html {% extends ext_templ %} {% b...
python's webbrowser launches IE instead of default on windows 7
5,916,270
22
2011-05-06T19:43:49Z
5,916,357
10
2011-05-06T19:53:01Z
[ "python", "browser" ]
I'm attempting to launch a local html file from python in the default browser. Right now my default is google chrome. If I double-click on a .html file, chrome launches. When I use python's webbrowser.open, IE launches instead, with a blank address bar. ``` Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500...
You can use [`get(name)`](http://docs.python.org/library/webbrowser.html#webbrowser.get) to use a specific browser. [You'll need to register the Chrome webbrowser](http://docs.python.org/library/webbrowser.html#webbrowser.register), as it doesn't seem to be one of the [predefined browser types](http://docs.python.org/...
python's webbrowser launches IE instead of default on windows 7
5,916,270
22
2011-05-06T19:43:49Z
5,943,706
14
2011-05-09T23:50:34Z
[ "python", "browser" ]
I'm attempting to launch a local html file from python in the default browser. Right now my default is google chrome. If I double-click on a .html file, chrome launches. When I use python's webbrowser.open, IE launches instead, with a blank address bar. ``` Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500...
My main issue was a bad URL by attempting prepend `file://` to a relative path. It can be fixed with this: ``` webbrowser.open('file://' + os.path.realpath(filename)) ``` Using `webbrowser.open` will try multiple methods until one "succeeds", which is a loose definition. The `WindowsDefault` class calls `os.startfil...
Python Trailing L Problem
5,917,203
13
2011-05-06T21:28:51Z
5,917,233
11
2011-05-06T21:32:01Z
[ "python" ]
I'm using Python to script some operations on specific locations in memory (32 bit addresses) in an embedded system. When I'm converting these addresses to and from strings, integers and hex values a trailing L seems to appear. This can be a real pain, for example the following seemingly harmless code won't work: ```...
Calling `str()` on those values should omit the trailing 'L'.
Python Trailing L Problem
5,917,203
13
2011-05-06T21:28:51Z
5,917,238
16
2011-05-06T21:32:41Z
[ "python" ]
I'm using Python to script some operations on specific locations in memory (32 bit addresses) in an embedded system. When I'm converting these addresses to and from strings, integers and hex values a trailing L seems to appear. This can be a real pain, for example the following seemingly harmless code won't work: ```...
If you do the conversion to hex using ``` "%x" % 4220963601 ``` there will be neither the `0x` nor the trailing `L`.
understanding for loops with reference to list containers in python
5,917,244
5
2011-05-06T21:33:01Z
5,917,319
7
2011-05-06T21:42:05Z
[ "python", "list", "reference", "for-loop" ]
My question is regarding the following for loop: ``` x=[[1,2,3],[4,5,6]] for v in x: v=[0,0,0] ``` here if you print x you get [[1,2,3],[4,5,6]].. so the v changed is not really a reference to the list in x. But when you do something like the following: ``` x=[[1,2,3],[4,5,6]] for v in x: v[0]=0; v[1]=0; v[2] =0...
When python executes `v = [0, 0, 0]`, it's 1. Creating a new list object with three zeroes in it. 2. Assigning a reference to the new list to a label called `v` It doesn't matter if `v` was a reference to something else before. If you want to change the contents of the list currently referenced by `v`, then you can'...
Speeding Up the Django Admin Delete Page
5,917,409
5
2011-05-06T21:55:03Z
5,917,541
8
2011-05-06T22:11:31Z
[ "python", "django", "django-admin", "django-orm" ]
How would you speed up the Django Admin record deletion action/page? I have a model B with a foreign key constraint to model A. For every record in A, there are about 10k records in B bound to A. So when I have to delete a record in A using the default "Delete selected A" action in admin, Django will take 15 minutes t...
As usual browse the django source to find your answer (it's surprisingly readable with variables, functions, classes, and files named logically). Looking at `django/contrib/admin/templates/admin/delete_confirmation.html` (in django 1.2.5), you will see a template that has the 24th line contains: ``` <ul>{{ deleted_ob...
Unzipping and the * operator
5,917,522
23
2011-05-06T22:09:44Z
5,917,600
14
2011-05-06T22:18:13Z
[ "python", "unzip" ]
The python docs gives this code as the reverse operation of zip: ``` >>> x2, y2 = zip(*zipped) ``` In particular "zip() in conjunction with the \* operator can be used to unzip a list". Can someone explain to me how the \* operator works in this case? As far as I understand, \* is a binary operator and can be used fo...
`zip(*zipped)` means "feed each element of `zipped` as an argument to `zip`". `zip` is similar to transposing a matrix in that doing it again will leave you back where you started. ``` >>> a = [(1, 2, 3), (4, 5, 6)] >>> b = zip(*a) >>> b [(1, 4), (2, 5), (3, 6)] >>> zip(*b) [(1, 2, 3), (4, 5, 6)] ```
Unzipping and the * operator
5,917,522
23
2011-05-06T22:09:44Z
5,917,619
14
2011-05-06T22:19:55Z
[ "python", "unzip" ]
The python docs gives this code as the reverse operation of zip: ``` >>> x2, y2 = zip(*zipped) ``` In particular "zip() in conjunction with the \* operator can be used to unzip a list". Can someone explain to me how the \* operator works in this case? As far as I understand, \* is a binary operator and can be used fo...
When used like this, the \* (asterisk, also know in some circles as the "splat" operator) is a signal to unpack arguments from a list. See <http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists> for a more complete definition with examples.
Unzipping and the * operator
5,917,522
23
2011-05-06T22:09:44Z
5,918,066
40
2011-05-06T23:34:43Z
[ "python", "unzip" ]
The python docs gives this code as the reverse operation of zip: ``` >>> x2, y2 = zip(*zipped) ``` In particular "zip() in conjunction with the \* operator can be used to unzip a list". Can someone explain to me how the \* operator works in this case? As far as I understand, \* is a binary operator and can be used fo...
Although [hammar's answer](http://stackoverflow.com/questions/5917522/unzipping-and-the-operator/5917600#5917600) explains how the reversing works in the case of the `zip()` function, it may be useful to look at argument unpacking in a more general sense. Let's say we have a simple function which takes some arguments: ...
In Python, why won't something print without a newline?
5,917,537
12
2011-05-06T22:11:13Z
5,917,595
19
2011-05-06T22:17:40Z
[ "python", "posix" ]
``` import time import sys sys.stdout.write("1") time.sleep(5) print("2") ``` will print "12" after 5 seconds ``` import time import sys sys.stdout.write("1\n") time.sleep(5) print("2") ``` will print "1\n" right away, then "2" after 5 seconds Why is this?
If you add "\n" then stream is flushed automaticaly, and it is not without new line at the end. You can flush output with: ``` sys.stdout.flush() ```
In Python, why won't something print without a newline?
5,917,537
12
2011-05-06T22:11:13Z
5,917,602
7
2011-05-06T22:18:21Z
[ "python", "posix" ]
``` import time import sys sys.stdout.write("1") time.sleep(5) print("2") ``` will print "12" after 5 seconds ``` import time import sys sys.stdout.write("1\n") time.sleep(5) print("2") ``` will print "1\n" right away, then "2" after 5 seconds Why is this?
Because `stdout` is buffered. You may be able to force the output sooner with a `sys.stdout.flush()` call.
Python: override __str__ in an exception instance
5,918,003
4
2011-05-06T23:22:58Z
5,918,210
10
2011-05-07T00:07:35Z
[ "python", "exception", "string" ]
I'm trying to override the printed output from an Exception subclass in Python after the exception has been raised and I'm having no luck getting my override to actually be called. ``` def str_override(self): """ Override the output with a fixed string """ return "Override!" def reraise(exception): ...
The problem is not that `__str__()` doesn't get overriden (just like you've already said, it does), but rather that `str(e)` (which invisibly gets called by print) is **not** always equivalent to e.**str**(). More specifically, if I get it right, `str()` (and other special methods, such as `repr()`), won't look for **s...
-bash: ./manage.py: Permission denied
5,918,582
21
2011-05-07T01:37:14Z
5,918,589
49
2011-05-07T01:40:29Z
[ "python", "django", "django-south" ]
After running: `$ ./manage.py migrate` I am getting the following error: ``` -bash: ./manage.py: Permission denied ``` Trying to run a migration after making a change in the DB. Any advice would be really appreciated.
You need to make manage.py executable to excecute it. Do `chmod +x manage.py` to make it excecutable. Alternately you can do `python manage.py <cmd>` instead.
custom tagging with nltk
5,919,355
19
2011-05-07T05:36:46Z
5,922,373
18
2011-05-07T16:18:34Z
[ "python", "nltk" ]
I'm trying to create a small english-like language for specifying tasks. The basic idea is to split a statement into verbs and noun-phrases that those verbs should apply to. I'm working with nltk but not getting the results i'd hoped for, eg: ``` >>> nltk.pos_tag(nltk.word_tokenize("select the files and copy to harddr...
One solution is to create a manual [UnigramTagger](http://www.nltk.org/api/nltk.tag.html#nltk.tag.sequential.UnigramTagger) that backs off to the NLTK tagger. Something like this: ``` >>> import nltk.tag, nltk.data >>> default_tagger = nltk.data.load(nltk.tag._POS_TAGGER) >>> model = {'select': 'VB'} >>> tagger = nltk...
custom tagging with nltk
5,919,355
19
2011-05-07T05:36:46Z
8,014,834
17
2011-11-04T19:37:15Z
[ "python", "nltk" ]
I'm trying to create a small english-like language for specifying tasks. The basic idea is to split a statement into verbs and noun-phrases that those verbs should apply to. I'm working with nltk but not getting the results i'd hoped for, eg: ``` >>> nltk.pos_tag(nltk.word_tokenize("select the files and copy to harddr...
Jacob's answer is spot on. However, to expand upon it, you may find you need more than just unigrams. For example, consider the three sentences: ``` select the files use the select function on the sockets the select was good ``` Here, the word "select" is being used as a verb, adjective, and noun respectively. A uni...
What is the pythonic way to calculate dot product?
5,919,530
9
2011-05-07T06:32:55Z
5,919,541
14
2011-05-07T06:37:56Z
[ "python", "dot-product" ]
I have two lists, one is named as A, another is named as B. Each element in A is a triple, and each element in B is just an number. I would like to calculate the result defined as : result = A[0][0] \* B[0] + A[1][0] \* B[1] + ... + A[n-1][0] \* B[n-1] I know the logic is easy but how to write in pythonic way? Thank...
``` import numpy result = numpy.dot( numpy.array(A)[:,0], B) ``` <http://docs.scipy.org/doc/numpy/reference/> If you want to do it without numpy, try ``` sum( [a[i][0]*b[i] for i in range(len(b))] ) ```
Getting data from a chart that is displayed on a website
5,919,981
6
2011-05-07T08:34:43Z
5,920,811
16
2011-05-07T11:45:03Z
[ "python", "latex", "tikz" ]
I was asked to draw a graph like this one ![enter image description here](http://i.stack.imgur.com/xnD2V.png) using Latex (more precisely, tikz and/or pgf). This would not be a problem if I had the data, but I don't. All I have is the [website](http://www.google.com/transparencyreport/traffic/) from where graphs can ...
Well, it'd be great if Google provided an API for this data! That said, you can still scrape some data out of the site. Here's how to go about it... **Install Firebug** I prefer [Firebug](http://getfirebug.com/) for Firefox, but Chrome's developer tools should also work. **Investigate** First things first, let's vis...
how to define a function from a string using python
5,920,120
3
2011-05-07T09:04:55Z
5,920,139
8
2011-05-07T09:09:57Z
[ "python", "string", "function" ]
this is my code : ``` a = \ '''def fun():\n print 'bbb' ''' eval(a) fun() ``` but it shows error : ``` Traceback (most recent call last): File "c.py", line 8, in <module> eval(a) File "<string>", line 1 def fun(): ^ SyntaxError: invalid syntax ``` so what can i do , thanks
`eval()` with string a string argument is only for expressions. If you want to execute statements, use `exec`: ``` exec """def fun(): print 'bbb' """ ``` But before you do that, think about whether you really need dynamic code or not. By far most things can be done without.
How to uninstall wxpython 2.8 on Mac OSX 10.6
5,920,764
5
2011-05-07T11:33:19Z
5,922,093
8
2011-05-07T15:37:35Z
[ "python", "osx", "wxpython", "uninstall" ]
Some details of my machine and installed packages before proceeding further: Mac OSX version: 10.6.6 Python version: Activestate Python 2.7.1 wxpython version: wxpython 2.8 (uses Carbon API hence limited to 32-bit mode arch only) I installed wxPython2.8-osx-unicode-py2.7 from wxpython website using their .dmg install...
If you look in the .dmg for wxPython, there is an uninstall\_wxPython.py unininstall script. Just drag it to your desktop and run `python ~/Desktop/uninstall_wxPython.py` in a terminal.
using dict vs class __dict__ method to format strings
5,921,901
2
2011-05-07T15:10:28Z
5,921,927
7
2011-05-07T15:14:13Z
[ "python" ]
I have been using dict to format strings ``` s = '%(name1)s %(name2)s' d = {} d['name1'] = 'asdf' d['name2'] = 'whatever' result = s % d ``` I just realized that I can do this with a class and using the **dict** method instead: ``` s = '%(name1)s %(name2)s' class D : pass d = D() d.name1 = 'asdf' d.name2 = 'whatever...
You can use new-style formatting, which allows getattr and getitem operators in format string: ``` >>> class X(object): ... pass ... >>> x = X() >>> x.x = 1 >>> d = {'a':1, 'b':2} >>> "{0[a]} {0[b]} {1.x}".format(d, x) '1 2 1' ``` Regarding disadvantages of your approach - object's `__dict__` is limited to whate...
Pyaudio installation error - 'command 'gcc' failed with exit status 1'
5,921,947
16
2011-05-07T15:17:36Z
5,922,091
12
2011-05-07T15:37:22Z
[ "python", "linux", "gcc", "pyaudio" ]
I'm running Ubuntu 11.04, Python 2.7.1 and wanted to install Pyaudio. So I ran, ``` $ sudo easy_install pyaudio ``` in the terminal and the process exited with following error messages, ``` Searching for pyaudio Reading http://pypi.python.org/simple/pyaudio/ Reading http://people.csail.mit.edu/hubert/pyaudio/ Best m...
Well, I solved the problem by using the package manager, ``` $ sudo apt-get install python-pyaudio ``` Although still has no clue why easy\_install fails.
Pyaudio installation error - 'command 'gcc' failed with exit status 1'
5,921,947
16
2011-05-07T15:17:36Z
21,014,700
24
2014-01-09T08:04:51Z
[ "python", "linux", "gcc", "pyaudio" ]
I'm running Ubuntu 11.04, Python 2.7.1 and wanted to install Pyaudio. So I ran, ``` $ sudo easy_install pyaudio ``` in the terminal and the process exited with following error messages, ``` Searching for pyaudio Reading http://pypi.python.org/simple/pyaudio/ Reading http://people.csail.mit.edu/hubert/pyaudio/ Best m...
Found an answer at <https://groups.google.com/forum/#!msg/pyo-discuss/ptp_m39ACpI/XgKdK8YGNSoJ> ``` sudo apt-get install portaudio19-dev ```
Pyaudio installation error - 'command 'gcc' failed with exit status 1'
5,921,947
16
2011-05-07T15:17:36Z
21,801,632
11
2014-02-15T18:15:40Z
[ "python", "linux", "gcc", "pyaudio" ]
I'm running Ubuntu 11.04, Python 2.7.1 and wanted to install Pyaudio. So I ran, ``` $ sudo easy_install pyaudio ``` in the terminal and the process exited with following error messages, ``` Searching for pyaudio Reading http://pypi.python.org/simple/pyaudio/ Reading http://people.csail.mit.edu/hubert/pyaudio/ Best m...
On ubuntu 13.10 aka **Saucy Salamander**, I solved the problem by installing **libjack-jackd2-dev** and **portaudio19-dev**. ``` sudo apt-get install libjack-jackd2-dev portaudio19-dev ``` Then `pip install pyaudio` should work.
How to execute a shell command through Python
5,922,590
6
2011-05-07T16:52:49Z
5,922,610
8
2011-05-07T16:55:02Z
[ "python", "shell" ]
I am new to Python programming. I want to execute a shell command "at" from a Python program. Can any one of the Python gurus help me out? Thanks in advance.
The [`subprocess`](http://docs.python.org/library/subprocess.html) module can be used for this purpose: ``` import subprocess retcode = subprocess.call(["at", "x", "y", "z"]) ``` Replace `x`, `y` and `z` with the parameters to `at`.
CSRF token missing or incorrect even though I have {% csrf_token %}
5,922,773
9
2011-05-07T17:20:12Z
5,922,801
11
2011-05-07T17:25:17Z
[ "python", "html", "django" ]
I have been getting this error referring to this method in my views.py file: ``` def AddNewUser(request): a=AMI() if(request.method == "POST"): print(request.POST) # print(request['newUser']) # print(request['password']) return render_to_response("ac/AddNewUser.html", {}) ``` But my ...
You have to use a [RequestContext](http://docs.djangoproject.com/en/1.3/ref/templates/api/#django.template.RequestContext) object to get the context, then pass the results in to your *render\_to\_response()* function. *RequestContext* adds in a required CSRF token. ``` from django.template import RequestContext from d...
'WSGIRequest' object is not subscriptable
5,922,958
5
2011-05-07T17:56:19Z
5,922,974
9
2011-05-07T18:00:45Z
[ "python", "html", "django" ]
I'm getting this error in this function in my views.py file. It's confusing because I don't know what 'WSGIRequest' is or why it's giving me problems. I know I have a variable called "newUser" because when I take out that one line the print(request.POST) line prints it out. def AddNewUser(request): ``` a=AMI() if(req...
[It means that WSGIRequest does not implement `__getitem__`](http://stackoverflow.com/questions/216972/in-python-what-does-it-mean-if-an-object-is-subscriptable-or-not). You are trying to treat the `HttpRequest` object like a dictionary but it's not. If you want to access this newUser variable use the POST object, whic...
Registering Multiple Signals in Django
5,923,012
5
2011-05-07T18:06:49Z
5,923,048
11
2011-05-07T18:11:39Z
[ "python", "django", "signals" ]
I'm trying to register multiple signals on one model. It seems that as I register an additional signal, it removes the previous signal. ``` from django.dispatch import receiver from django.db.models.signals import post_save,post_delete from my.app.models import Resource @receiver(post_save,sender=Resource) def Resou...
You are (probably unintentionally) redefining ResourceSaved. Try this instead: ``` @receiver(post_save,sender=Resource) def ResourceSaved(sender,**kwargs): print "Saved" @receiver(post_delete,sender=Resource) def ResourceDeleted(sender,**kwargs): print "Deleted" ```
Plotting frequency distributions in python
5,923,168
6
2011-05-07T18:34:02Z
5,923,240
12
2011-05-07T18:48:09Z
[ "python", "matplotlib", "probability" ]
I have a graph stored in an adjacency list format. I randomly select a bunch of nodes and note the number of neighbors each of them have. I now want to plot the distribution, and the way I do it right now is by manually checking if the size of the neighbor set falls into a particular bucket (I set the bucket sizes manu...
Is [matplotlib.pyplot.hist()](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.hist) what you are looking for?
Problems importing GDK
5,923,746
2
2011-05-07T20:15:22Z
5,923,790
8
2011-05-07T20:29:45Z
[ "python", "user-interface", "import", "gtk", "gdk" ]
I am trying to import GDK to my program however I continue to get an error ``` No module named GDK ``` Do you know how I can fix this? Since it was working before I already tried `import gtk.GDK` and `import GDK`. I have installed PyGTK and PyGDK is part of of it pyGTK.
Try: ``` import gtk.gdk ``` (note: small letters)
Python dictionary memory usage
5,924,151
5
2011-05-07T21:36:35Z
5,924,182
7
2011-05-07T21:42:38Z
[ "python", "memory", "dictionary" ]
I've been working on a project that involves loading a relatively large dictionary into memory from a file. The dictionary has just under 2 million entries, each entry (key and value combined) is under 20 bytes. The size of the file on disk is 38 MB. My problem is that when I try to load the dictionary, my program imm...
I think the memory is used to parse the dictionary syntax AST. For this kind of use it's much better if you go for the [cPickle](http://docs.python.org/library/pickle.html?highlight=cpickle) module instead of using `repr`/`eval`. ``` import cPickle x = {} for i in xrange(1000000): x["k%i" % i] = "v%i" % i cPickl...
Global variable in Python
5,924,636
3
2011-05-07T23:18:16Z
5,924,645
9
2011-05-07T23:20:24Z
[ "python", "function", "global-variables", "declaration" ]
I've been reading a Python textbook, and I see the following code: ``` class Database: # the database implementation pass database = None def initialize_database(): global database database = Database() ``` Now, why is there a `global` declaration inside `initialize_database` function? We had defined `d...
You can reference a global when it's not declared global in a function, but you can only read it; writing it will create a new local variable hiding the global variable. The `global` declaration makes it able to write to the global.
Can this be written as a python reduce function?
5,924,828
5
2011-05-08T00:08:05Z
5,924,907
9
2011-05-08T00:31:13Z
[ "python" ]
Can you make this more pythonic by using the map and/or reduce functions? it just sums the products of every consecutive pair of numbers. ``` topo = (14,10,6,7,23,6) result = 0 for i in range(len(topo)-1): result += topo[i]*topo[i+1] ```
This is the nicest way I can think of: ``` import operator sum(map(operator.mul, topo[:-1], topo[1:])) ``` **Edit**: I've just found out there's a better way to do this: ``` import operator import itertools def pairwise(iterable): a, b = itertools.tee(iterable) next(b, None) return a, b def sum_product...
How to create a new instance from a class object in Python
5,924,879
25
2011-05-08T00:23:39Z
7,616,959
55
2011-09-30T23:11:42Z
[ "python", "oop" ]
I need to dynamically create an instance of a class in Python. Basically I am using the load\_module and inspect module to import and load the class into a class object, but I can't figure out how to create an instance of this class object. Please help!
I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it. ``` class k: pass a = k() k2 = a.__class__ a2 = k2() ``` At this point, a and a2 are both instances of the same class (class k).
urllib2 POST progress monitoring
5,925,028
9
2011-05-08T01:15:16Z
5,928,451
20
2011-05-08T15:42:02Z
[ "python", "http", "urllib2", "http-post" ]
I'm uploading a fairly large file with urllib2 to a server-side script via POST. I want to display a progress indicator that shows the current upload progress. Is there a hook or a callback provided by urllib2 that allows me to monitor upload progress? I know that you can do it with download using successive calls to t...
It is possible but you need to do a few things: * Fake out the urllib2 subsystem into passing a file handle down to httplib by attaching a `__len__` attribute which makes `len(data)` return the correct size, used to populate the Content-Length header. * Override the `read()` method on your file handle: as httplib call...
Remove <br> tags from a parsed Beautiful Soup list?
5,925,385
11
2011-05-08T03:18:59Z
5,925,497
11
2011-05-08T03:57:20Z
[ "python", "html-parsing" ]
I'm currently getting into a for loop with all the rows I want: ``` page = urllib2.urlopen(pageurl) soup = BeautifulSoup(page) tables = soup.find("td", "bodyTd") for row in tables.findAll('tr'): ``` At this point, I have my information, but the ``` <br /> ``` tags are ruining my output. What's the ...
``` for e in soup.findAll('br'): e.extract() ```
Remove <br> tags from a parsed Beautiful Soup list?
5,925,385
11
2011-05-08T03:18:59Z
5,925,525
17
2011-05-08T04:09:42Z
[ "python", "html-parsing" ]
I'm currently getting into a for loop with all the rows I want: ``` page = urllib2.urlopen(pageurl) soup = BeautifulSoup(page) tables = soup.find("td", "bodyTd") for row in tables.findAll('tr'): ``` At this point, I have my information, but the ``` <br /> ``` tags are ruining my output. What's the ...
If you want to translate the `<br />`'s to newlines, do something like this: ``` def text_with_newlines(elem): text = '' for e in elem.recursiveChildGenerator(): if isinstance(e, basestring): text += e.strip() elif e.name == 'br': text += '\n' return text ```
Plot Histogram in Python
5,926,061
13
2011-05-08T06:50:57Z
5,926,411
38
2011-05-08T08:30:14Z
[ "python", "frequency", "histogram" ]
I have two lists, x and y. x contains the alphabet A-Z and Y contains the frequency of them in a file. I've tried researching how to plot these values in a histogram but has had no success with understanding how to plot it. ``` n, bins, patches = plt.hist(x, 26, normed=1, facecolor='blue', alpha=0.75) ``` Would x ...
`hist` works on a collection of values and computes and draws the histogram from them. In your case you already precalculated the frequency of each group (letter). To represent your data in an histogram form use better matplotlib `bar`: ``` import numpy as np import matplotlib.pyplot as plt alphab = ['A', 'B', 'C', '...
Get character position in alphabet
5,927,149
12
2011-05-08T11:29:24Z
5,927,160
28
2011-05-08T11:31:06Z
[ "python", "position", "character", "alphabet" ]
I'm 90% sure there is a built in function that does this. I need to find the position of a character in an alphabet. So the character "b" is position 1 (counting from 0), etc. Does anyone know what the function is called? Thanks in advance! EDIT: What i'm trying to do is to send all the characters X amount of "steps...
It is called `index`. For e.g. ``` >>> import string >>> string.lowercase.index('b') 1 >>> ``` Note: in Python 3, `string.lowercase` has been renamed to `string.ascii_lowercase`.
Get character position in alphabet
5,927,149
12
2011-05-08T11:29:24Z
5,927,403
8
2011-05-08T12:29:05Z
[ "python", "position", "character", "alphabet" ]
I'm 90% sure there is a built in function that does this. I need to find the position of a character in an alphabet. So the character "b" is position 1 (counting from 0), etc. Does anyone know what the function is called? Thanks in advance! EDIT: What i'm trying to do is to send all the characters X amount of "steps...
Without the import ``` def char_position(letter): return ord(letter) - 97 def pos_to_char(pos): return chr(pos + 97) ```
removing data from a numpy.array
5,927,180
12
2011-05-08T11:36:11Z
5,927,244
19
2011-05-08T11:50:02Z
[ "python", "numpy", "slice", "boxplot" ]
I have a rank-1 numpy.array of which I want to make a boxplot. However, I want to exclude all values equal to zero in the array ... Currently, I solved this by looping the array and copy the value to a new array if not equal to zero. However, as the array consists of 86 000 000 values and i have to do this multiple tim...
For a NumPy array `a`, you can use ``` a[a != 0] ``` to extract the values not equal to zero.
removing data from a numpy.array
5,927,180
12
2011-05-08T11:36:11Z
5,940,970
10
2011-05-09T18:34:53Z
[ "python", "numpy", "slice", "boxplot" ]
I have a rank-1 numpy.array of which I want to make a boxplot. However, I want to exclude all values equal to zero in the array ... Currently, I solved this by looping the array and copy the value to a new array if not equal to zero. However, as the array consists of 86 000 000 values and i have to do this multiple tim...
this is a case where you want to use masked arrays, it keeps the shape of your array and it is automatically recognized by all numpy and matplotlib functions. ``` X = np.random.randn(1e3, 5) X[np.abs(X)< .1]= 0 # some zeros X = np.ma.masked_equal(X,0) plt.boxplot(X) #masked values are not plotted #other functionaliti...
How do i find the frequency count of a word in English using WordNet?
5,928,704
11
2011-05-08T16:26:29Z
12,376,620
11
2012-09-11T19:30:39Z
[ "python", "nltk", "wordnet" ]
Is there a way to find the frequency of the usage of a word in English language using WordNet or NLTK using python? NOTE: I do not want the frequency count of a word in a given input file. I want the frequency count of a word in general based on the usage in today's time.
In WordNet, every Lemma has a frequency count that is returned by the method `lemma.count()`, and which is stored in the file `nltk_data/corpora/wordnet/cntlist.rev`. Code example: ``` from nltk.corpus import wordnet syns = wordnet.synsets('stack') for s in syns: for l in s.lemmas(): print l.name + " " + ...
python decorators with parameters
5,929,107
131
2011-05-08T17:40:08Z
5,929,165
237
2011-05-08T17:54:08Z
[ "python", "decorator" ]
I have a problem with the transfer of variable 'insurance\_mode' by the decorator. I would do it by the following decorator statement: ``` @execute_complete_reservation(True) def test_booking_gta_object(self): self.test_select_gta_object() ``` but unfortunately, this statement does not work. Perhaps maybe ther...
You mean `def test_booking_gta_object`, right? Anyway, the syntax for decorators with arguments is a bit different - the decorator with arguments should return a function that will *take a function* and return another function. So it should really return a normal decorator. A bit confusing, right? What I mean is: ``` ...
python decorators with parameters
5,929,107
131
2011-05-08T17:40:08Z
5,929,178
25
2011-05-08T17:56:14Z
[ "python", "decorator" ]
I have a problem with the transfer of variable 'insurance\_mode' by the decorator. I would do it by the following decorator statement: ``` @execute_complete_reservation(True) def test_booking_gta_object(self): self.test_select_gta_object() ``` but unfortunately, this statement does not work. Perhaps maybe ther...
I presume your problem is passing arguments to your decorator. This is a little tricky and not straight forward. Here's an example of how to do this: ``` class MyDec(object): def __init__(self,flag): self.flag = flag def __call__(self, original_func): decorator_self = self def wrappee(...
python decorators with parameters
5,929,107
131
2011-05-08T17:40:08Z
25,827,070
59
2014-09-13T19:52:50Z
[ "python", "decorator" ]
I have a problem with the transfer of variable 'insurance\_mode' by the decorator. I would do it by the following decorator statement: ``` @execute_complete_reservation(True) def test_booking_gta_object(self): self.test_select_gta_object() ``` but unfortunately, this statement does not work. Perhaps maybe ther...
One way of thinking about decorators with arguments is ``` @decorator def foo(*args, **kwargs): pass ``` Translates to ``` foo = decorator(foo) ``` so if the decorator had arguments: ``` @decorator_with_args(arg) def foo(*args, **kwargs): pass ``` translates to ``` foo = decorator_with_args(arg)(foo) ```...
python decorators with parameters
5,929,107
131
2011-05-08T17:40:08Z
26,151,604
23
2014-10-01T22:17:24Z
[ "python", "decorator" ]
I have a problem with the transfer of variable 'insurance\_mode' by the decorator. I would do it by the following decorator statement: ``` @execute_complete_reservation(True) def test_booking_gta_object(self): self.test_select_gta_object() ``` but unfortunately, this statement does not work. Perhaps maybe ther...
Even if this question was already answered and accepted, I'd like to show an idea which is IMHO quite elegant. The solution proposed by t.dubrownik shows a pattern which is always the same: you need the three-layered wrapper regardless of what the decorator does. So I tought this is a job for a meta-decorator, that is...
Some problem with dict function
5,929,397
8
2011-05-08T18:29:51Z
5,929,432
15
2011-05-08T18:34:15Z
[ "python" ]
I'm trying to convert a list to a dictionary by using the `dict` function. ``` inpu = input.split(",") dic = dict(inpu) ``` The above code is trying to get a string and `split` it on `','` and afterwards I use the `dict` function to convert the list to a dictionary. However, I get this error: > ValueError: dictiona...
`dict` expects an iterable of 2-element containers (like a list of tuples). You can't just pass a list of items, it doesn't know what's a key and what's a value. You are trying to do this: ``` >>> range(10) <<< [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> dict(range(10)) --------------------------------------------------------...
Calling Python functions from inline C with scipy.weave
5,929,600
8
2011-05-08T19:02:16Z
5,929,802
10
2011-05-08T19:35:59Z
[ "python", "performance", "inline", "scipy" ]
Can I call a python function from inline C code (using weave)? Motivation: I have a bit of code that I'd like to optimize, and I've identified the bottleneck in one function. After my usual tricks, I usually turn to [scipy.weave.inline](http://docs.scipy.org/doc/scipy/reference/generated/scipy.weave.inline.html) for o...
It's a little involved, as Weave doesn't have a way to automatically marshall the arguments and return value. You need to do a little more work: ``` def bar_weave(): code = """ int a = 0; for (int i=0;i<10;++i){ py::tuple arg(1); arg[0] = i; a += (int) foo.call(arg); } retur...
Separating file extensions using python os.path module
5,930,036
10
2011-05-08T20:11:10Z
5,930,176
18
2011-05-08T20:31:13Z
[ "python" ]
I'm working in python with `os.path.splitext()` and curious if it is possible to separate filenames from extensions with multiple "."? e.g. "foobar.aux.xml" using splitext. Filenames vary from [foobar, foobar.xml, foobar.aux.xml]. Is there a better way?
Split with `os.extsep`. ``` >>> import os >>> 'filename.ext1.ext2'.split(os.extsep) ['filename', 'ext1', 'ext2'] ``` If you want everything after the first dot: ``` >>> 'filename.ext1.ext2'.split(os.extsep, 1) ['filename', 'ext1.ext2'] ``` If you are using paths with directories that may contain dots: ``` >>> def ...
Python: Find the sum of all the multiples of 3 or 5 below 1000
5,930,300
5
2011-05-08T20:51:26Z
5,930,338
7
2011-05-08T20:59:57Z
[ "python", "algorithm" ]
Not sure if i should've posted this on math.stackexchange instead, but it includes more programming so i posted it here. The question seems really simple, but i've sat here for at least one hour now not figuring it out. I've tried different solutions, and read math formulas for it etc but it wont give me the right ans...
You are overcomplicating things. You just need a list of numbers that are multiples of 3 or 5 which you can get easily with a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` >>> [i for i in range(1000) if i % 3 == 0 or i % 5 == 0] ``` Then use [`sum`](http://docs.pyt...
How to use Python 3 and Django with Apache?
5,930,585
9
2011-05-08T21:45:04Z
5,930,592
13
2011-05-08T21:46:33Z
[ "python", "django", "apache", "python-3.x", "walkthrough" ]
My goal is to set up Python 3 with Apache. My biggest problem is actually acquiring mod\_python.so. For the life of me I found only one site where it could be downloaded (http://www.modpython.org/) and what I got was a bunch of build and install files. **I can find no guide explaining how to set up Python 3 with Apach...
Django 1.6+ and mod\_wsgi 3.4+ are required to use Python 3 with Apache. For more detail refer to [scot's answer](http://stackoverflow.com/a/22111602/641766%5d).
How to use Python 3 and Django with Apache?
5,930,585
9
2011-05-08T21:45:04Z
22,111,602
8
2014-03-01T07:37:59Z
[ "python", "django", "apache", "python-3.x", "walkthrough" ]
My goal is to set up Python 3 with Apache. My biggest problem is actually acquiring mod\_python.so. For the life of me I found only one site where it could be downloaded (http://www.modpython.org/) and what I got was a bunch of build and install files. **I can find no guide explaining how to set up Python 3 with Apach...
**These answers are no longer true of Django 1.6 - it supports python3. The mod\_wsgi page says version 3.4 supports python 3**. <https://code.google.com/p/modwsgi/> Don't know if it all works at this point though (I will return and edit when I find out)! The answer is YES it works! I have an AWS EC3 Ubuntu instance...
How can I create a Set of Sets in Python?
5,931,291
64
2011-05-09T00:15:52Z
5,931,295
15
2011-05-09T00:17:36Z
[ "python", "class", "set" ]
I'm trying to make a set of sets in Python. I can't figure out how to do it. Starting with the empty set `xx`: ``` xx = set([]) # Now we have some other set, for example elements = set([2,3,4]) xx.add(elements) ``` but I get ``` TypeError: unhashable type: 'list' ``` or ``` TypeError: unhashable type: 'set' ``` ...
Use [`frozenset`](http://docs.python.org/library/stdtypes.html#frozenset) inside.
How can I create a Set of Sets in Python?
5,931,291
64
2011-05-09T00:15:52Z
5,931,299
58
2011-05-09T00:18:49Z
[ "python", "class", "set" ]
I'm trying to make a set of sets in Python. I can't figure out how to do it. Starting with the empty set `xx`: ``` xx = set([]) # Now we have some other set, for example elements = set([2,3,4]) xx.add(elements) ``` but I get ``` TypeError: unhashable type: 'list' ``` or ``` TypeError: unhashable type: 'set' ``` ...
Python's complaining because the inner `set` objects are mutable and thus not hashable. The solution is to use `frozenset` for the inner sets, to indicate that you have no intention of modifying them.
How can I create a Set of Sets in Python?
5,931,291
64
2011-05-09T00:15:52Z
21,401,146
19
2014-01-28T09:06:32Z
[ "python", "class", "set" ]
I'm trying to make a set of sets in Python. I can't figure out how to do it. Starting with the empty set `xx`: ``` xx = set([]) # Now we have some other set, for example elements = set([2,3,4]) xx.add(elements) ``` but I get ``` TypeError: unhashable type: 'list' ``` or ``` TypeError: unhashable type: 'set' ``` ...
People already mentioned that you can do this with a [frozenset()](http://docs.python.org/2/library/stdtypes.html#frozenset), so I will just add a code how to achieve this: For example you want to create a set of sets from the following list of lists: ``` t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]] `...
How would you properly break this line to match pep8 rules?
5,931,297
13
2011-05-09T00:18:17Z
5,931,337
19
2011-05-09T00:27:32Z
[ "python", "pep8" ]
Given this Python class, implementing a Django form, how would you properly break this to meet the PEP8 standards? ``` class MyForm(forms.Form): categories = forms.CharField(required=False, widget=forms.SelectMultiple(choices=CATEGORY_VALUE), ...
I don't think PEP8 says much about it, but I would simply go with double indentation for the parameters: ``` class MyForm(forms.Form): categories = forms.CharField( required=False, widget=forms.SelectMultiple(choices=CATEGORY_VALUE), label="Categories" ) additional_i...
Explicitly set docstring of a method
5,931,386
7
2011-05-09T00:39:28Z
5,931,391
14
2011-05-09T00:40:55Z
[ "python", "nxt" ]
I help to maintain a package for python called nxt-python. It uses metaclasses to define the methods of a control object. Here's the method that defines the available functions: ``` class _Meta(type): 'Metaclass which adds one method for each telegram opcode' def __init__(cls, name, bases, dict): supe...
For plain functions: ``` def f(): # for demonstration pass f.__doc__ = "Docstring!" help(f) ``` This works in both python2 and python3, on functions with and without docstrings defined. You can also do `+=`. Note that it is `__doc__` and not `__docs__`. For methods, you need to use the `__func__` attribute of ...
Can't execute an INSERT statement in a Python script via MySQLdb
5,931,771
4
2011-05-09T02:01:54Z
5,931,840
10
2011-05-09T02:13:35Z
[ "python", "mysql", "sql" ]
I'm trying to execute a basic `INSERT` statement on a MySQL table from a Python script using MySQLdb. My table looks like this: ``` CREATE TABLE `testtable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `testfield` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ``` Running this query from the MySQL command line wo...
You either need to set `conn.autocommit()`, or you need to do `conn.commit()` - see [the FAQ](http://mysql-python.sourceforge.net/FAQ.html#id3)
Partitioning a string in Python by a regular expression
5,932,059
6
2011-05-09T03:00:30Z
5,932,097
11
2011-05-09T03:09:11Z
[ "python", "regex", "split", "whitespace" ]
I need to split a string into an array on word boundaries (whitespace) while maintaining the whitespace. For example: ``` 'this is a\nsentence' ``` Would become ``` ['this', ' ', 'is', ' ', 'a' '\n', 'sentence'] ``` I know about [str.partition](http://docs.python.org/library/stdtypes.html#str.partition) and [re....
Try this: ``` s = "this is a\nsentence" re.split(r'(\W+)', s) # Notice parentheses and a plus sign. ``` Result would be: ``` ['this', ' ', 'is', ' ', 'a', '\n', 'sentence'] ```
In NLTK pos_tag, why "hello" is classified as Noun?
5,932,227
2
2011-05-09T03:33:36Z
5,945,062
8
2011-05-10T04:07:24Z
[ "python", "nlp", "nltk" ]
I've tried ``` text = nltk.word_tokenize("hello, my name is John") words = nltk.pos_tag(text) for w in words: print "%s = %s" % (w[0], w[1]) ``` And I got: ``` hello = NN , = , my = PRP$ name = NN is = VBZ John = NNP ```
According to the Penn Treebank tagset, *hello* is definitely an interjection and is consistently tagged UH. The problem you're running into is that the taggers that NLTK ships with were most likely trained on the part of the Wall Street Journal section of the Penn Treebank that is available for free, which unfortunatel...
Internals of Python list, access and resizing runtimes
5,932,328
19
2011-05-09T03:55:24Z
5,932,364
29
2011-05-09T04:02:29Z
[ "python", "list", "time", "space", "internals" ]
Is Python's [] a list or array. Is the access time of an index O(1) like an array or O(n) like a list, and is appending/resizing O(1) like a list or O(n) like an array, or is it a hybrid that can manage O(1) for accessing and resizing? I read somewhere (http://norvig.com/python-lisp.html) that array access is really sl...
Python's `[]` is implemented as an *array*, not a linked list. Although resizing is O(n), appending to it is *amortized O(1)*, because resizes happen very rarely. If you're not familiar with how this works, read this [Wikipedia entry on dynamic arrays](http://en.wikipedia.org/wiki/Dynamic_array). Python's list doesn't ...
Internals of Python list, access and resizing runtimes
5,932,328
19
2011-05-09T03:55:24Z
5,932,366
8
2011-05-09T04:02:49Z
[ "python", "list", "time", "space", "internals" ]
Is Python's [] a list or array. Is the access time of an index O(1) like an array or O(n) like a list, and is appending/resizing O(1) like a list or O(n) like an array, or is it a hybrid that can manage O(1) for accessing and resizing? I read somewhere (http://norvig.com/python-lisp.html) that array access is really sl...
There is a great list [here](http://wiki.python.org/moin/TimeComplexity) outlining the time complexity of the python data types. In your case item retrieval should be O(1) time.