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 |
|---|---|---|---|---|---|---|---|---|---|
Read a file in reverse order using python | 2,301,789 | 59 | 2010-02-20T10:09:26Z | 2,301,802 | 7 | 2010-02-20T10:13:43Z | [
"python",
"file",
"reverse"
] | How to read a file in reverse order using python? I want to read a file from last line to first line. | ```
for line in reversed(open("file").readlines()):
print line.rstrip()
```
If you are on linux, you can use `tac` command.
```
$ tac file
```
2 recipes you can find in ActiveState [here](http://code.activestate.com/recipes/276149/) and [here](http://code.activestate.com/recipes/120686/) |
Read a file in reverse order using python | 2,301,789 | 59 | 2010-02-20T10:09:26Z | 2,301,867 | 8 | 2010-02-20T10:36:27Z | [
"python",
"file",
"reverse"
] | How to read a file in reverse order using python? I want to read a file from last line to first line. | ```
import re
def filerev(somefile, buffer=0x20000):
somefile.seek(0, os.SEEK_END)
size = somefile.tell()
lines = ['']
rem = size % buffer
pos = max(0, (size // buffer - 1) * buffer)
while pos >= 0:
somefile.seek(pos, os.SEEK_SET)
data = somefile.read(rem + buffer) + lines[0]
rem = 0
lines ... |
Read a file in reverse order using python | 2,301,789 | 59 | 2010-02-20T10:09:26Z | 23,646,049 | 62 | 2014-05-14T05:09:51Z | [
"python",
"file",
"reverse"
] | How to read a file in reverse order using python? I want to read a file from last line to first line. | A correct, efficient answer written as a generator.
```
import os
def reverse_readline(filename, buf_size=8192):
"""a generator that returns the lines of a file in reverse order"""
with open(filename) as fh:
segment = None
offset = 0
fh.seek(0, os.SEEK_END)
file_size = remainin... |
Read a file in reverse order using python | 2,301,789 | 59 | 2010-02-20T10:09:26Z | 26,747,854 | 7 | 2014-11-05T00:42:49Z | [
"python",
"file",
"reverse"
] | How to read a file in reverse order using python? I want to read a file from last line to first line. | How about something like this:
```
import os
def readlines_reverse(filename):
with open(filename) as qfile:
qfile.seek(0, os.SEEK_END)
position = qfile.tell()
line = ''
while position >= 0:
qfile.seek(position)
next_char = qfile.read(1)
if next_... |
Editing the raw HTML inside a TinyMCE control | 2,302,171 | 5 | 2010-02-20T12:31:57Z | 2,302,243 | 10 | 2010-02-20T12:59:59Z | [
"python",
"django",
"tinymce",
"django-tinymce"
] | I have a Django website in which I use `django-tinymce` to edit HTML fields with a TinyMCE control.
TinyMCE practically gives me a WYSIWYG way to edit HTML. My question is, can I get access to edit the underlying HTML directly? I was thinking, maybe there's some button I can enbale which will toggle between "WYSIWYG m... | Simply add the `code` button to one of the toolbars, e.g. with this configuration for django-tinymce:
```
TINYMCE_DEFAULT_CONFIG = {
# your other configuration
'theme_advanced_buttons3_add': 'code',
}
```
[Here](http://wiki.moxiecode.com/index.php/TinyMCE%3aControl_reference#Default_buttons_available_in_the_a... |
How to test whether a variable has been initialized before using it? | 2,303,005 | 2 | 2010-02-20T17:34:46Z | 2,303,018 | 11 | 2010-02-20T17:41:11Z | [
"python"
] | So let's say you've got an application with a variable that you will be creating an instance of when you load it independently (ie when you use `if __name__ == '__main__'`).
Also, there is a method that is to be called for when a client imports the application for use within another application. This method will also ... | It's an error to access a variable before it is initialized. An uninitialized variable's value isn't None; accessing it just raises an exception.
You can catch the exception if you like:
```
>>> try:
... foo = x
... except NameError:
... x = 5
... foo = 1
```
In a class, you can provide a default value of N... |
What does Django do with `MEDIA_ROOT`? | 2,303,254 | 8 | 2010-02-20T18:53:41Z | 2,305,649 | 8 | 2010-02-21T11:09:01Z | [
"python",
"django"
] | What does Django do with `MEDIA_ROOT` exactly? I never understood it. Since Django itself doesn't serve static media, and you have to set up apache or something similar for it, why does it care in which directory it sits? | You're not the only one who wonders; check out [Django ticket #10650](http://code.djangoproject.com/ticket/10650). Based on the comments by Django developers there, I think this pretty much sums up what `MEDIA_ROOT` is used for:
> Unfortunately, Django is also at fault for being far too vague in its docs about what
> ... |
Specifying python interpreter from virtualenv in emacs | 2,303,956 | 11 | 2010-02-20T22:12:01Z | 2,307,435 | 8 | 2010-02-21T20:50:44Z | [
"python",
"emacs",
"virtualenv"
] | Today I've been trying to bring more of the Python related modes into
my Emacs configuration but I haven't had much luck.
First what I've noticed is that depending on how Emacs is
launched (terminal vs from the desktop), the interpreter it decides to
use is different.
* launched from KDE menu: `M-! which python` give... | So it seems that python-shell does the right thing by picking up the environment settings, whereas py-shell does not. python-shell is provided by python.el and py-shell is provided by python-mode.el , There's bug reports etc related to this, so I'm just not going to use py-shell for now. Figured I'd close the loop on t... |
_ElementInterface instance has no attribute 'tostring' | 2,304,082 | 4 | 2010-02-20T22:56:52Z | 2,304,157 | 8 | 2010-02-20T23:15:45Z | [
"python"
] | The code below generates this error. I can't figure out why. If ElementTree has parse, why doesn't it have tostring? <http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree>
```
from xml.etree.ElementTree import ElementTree
...
tree = ElementTree()
node = ElementTree()
node = tr... | `tostring` is a method of the `xml.etree.ElementTree` module, not the confusingly similarly-named `xml.etree.ElementTree.ElementTree` class.
```
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import tostring
tree = ElementTree()
node = tree.parse(open("my_xml.xml"))
text = tostring(node)
``` |
regex for Twitter username | 2,304,632 | 28 | 2010-02-21T03:19:46Z | 2,304,640 | 15 | 2010-02-21T03:25:04Z | [
"python",
"regex",
"twitter"
] | Could you provide a regex that match Twitter usernames?
Extra bonus if a Python example is provided. | If you're talking about the `@username` thing they use on twitter, then you can use this:
```
import re
twitter_username_re = re.compile(r'@([A-Za-z0-9_]+)')
```
To make every instance an HTML link, you could do something like this:
```
my_html_str = twitter_username_re.sub(lambda m: '<a href="http://twitter.com/%s"... |
regex for Twitter username | 2,304,632 | 28 | 2010-02-21T03:19:46Z | 2,330,300 | 9 | 2010-02-24T22:55:59Z | [
"python",
"regex",
"twitter"
] | Could you provide a regex that match Twitter usernames?
Extra bonus if a Python example is provided. | Twitter [recently released](http://engineering.twitter.com/2010/02/introducing-open-source-twitter-text.html) to open source both [java](http://github.com/mzsanford/twitter-text-java) and [ruby](http://github.com/mzsanford/twitter-text-rb) ([gem](http://rubygems.org/gems/twitter-text)) implementations of the code they ... |
regex for Twitter username | 2,304,632 | 28 | 2010-02-21T03:19:46Z | 6,351,873 | 47 | 2011-06-15T01:01:13Z | [
"python",
"regex",
"twitter"
] | Could you provide a regex that match Twitter usernames?
Extra bonus if a Python example is provided. | ```
(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)
```
Ive used this as it disregards emails
Here is a sample tweet
```
@Hello how are @you doing, email @000 me @ whats.up@example.com @shahmirj
```
Picks Up:
```
@Hello
@you
@shahmirj
```
It will also work for hash tags, I use the same experssion with the `@... |
regex for Twitter username | 2,304,632 | 28 | 2010-02-21T03:19:46Z | 13,396,934 | 9 | 2012-11-15T11:48:51Z | [
"python",
"regex",
"twitter"
] | Could you provide a regex that match Twitter usernames?
Extra bonus if a Python example is provided. | The regex I use, and that have been tested in multiple contexts :
```
/(^|[^@\w])@(\w{1,15})\b/
```
This is the cleanest way I've found to test and replace Twitter username in strings.
```
#!/usr/bin/python
import re
text = "@RayFranco is answering to @jjconti, this is a real '@username83' but this is an@email.com... |
QWebView not loading external CSS | 2,304,952 | 3 | 2010-02-21T05:43:37Z | 2,305,088 | 7 | 2010-02-21T06:34:57Z | [
"python",
"qt",
"pyqt",
"qwebview",
"pyside"
] | I am using a QWebView to display some content and I want to use custom CSS to spruce up the output. I found that I can use the `QWebSettings.setUserStyleSheetUrl()` method to load my own CSS into the view. The `.css` file is in the same directory as my main program.
```
self.webview = QWebView(MainWindow)
self.webview... | In Qt, all paths to external files need to be **ABSOLUTE** paths, not relative ones.
To fix the problem, I add to make the following change:
```
path = os.getcwd()
self.webview.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(path + "/myCustom.css"))
```
And everything worked correctly. Hopefully this will help so... |
Is there a open-search solution for python? | 2,305,026 | 3 | 2010-02-21T06:13:54Z | 2,305,062 | 8 | 2010-02-21T06:26:29Z | [
"python",
"search",
"lucene"
] | lucene-like would be preferred.
thanks | Why you need lucene-like when you can use lucene (PyLucene) :)
<http://lucene.apache.org/pylucene/>
It is great and builds against the latest build of lucene
quote from site:
> PyLucene is a Python extension for
> accessing Java Lucene. Its goal is to
> allow you to use Lucene's text
> indexing and searching capabi... |
Is there a open-search solution for python? | 2,305,026 | 3 | 2010-02-21T06:13:54Z | 2,307,477 | 10 | 2010-02-21T21:14:56Z | [
"python",
"search",
"lucene"
] | lucene-like would be preferred.
thanks | You can also check [ElasticSearch](http://www.elasticsearch.com), it has native JSON interface so integrating with it in python should be simpler. Seems like [Simon Willison](http://simonwillison.net/2010/Feb/11/elastic/) thinks it got potential... |
Remove and insert lines in a text file | 2,305,115 | 4 | 2010-02-21T06:49:37Z | 2,305,144 | 7 | 2010-02-21T07:00:18Z | [
"python",
"file-io"
] | I have a text file looks like:
```
first line
second line
third line
forth line
fifth line
sixth line
```
I want to replace the third and forth lines with three new lines. The above contents would become:
```
first line
second line
new line1
new line2
new line3
fifth line
sixth line
```
How ... | For **python2.6**
```
with open("file1") as infile:
with open("file2","w") as outfile:
for i,line in enumerate(infile):
if i==2:
# 3rd line
outfile.write("new line1\n")
outfile.write("new line2\n")
outfile.write("new line3\n")
... |
How can I limit an SQL query to be nondestructive? | 2,305,353 | 2 | 2010-02-21T08:48:46Z | 2,305,379 | 14 | 2010-02-21T08:57:39Z | [
"python",
"sql",
"django",
"security",
"sql-injection"
] | I'm planning on building a Django log-viewing app with powerful filters. I'd like to enable the user to finely filter the results with some custom (possibly DB-specific) SELECT queries.
However, I dislike giving the user write access to the database. Is there a way to make sure a query doesn't change anything in the d... | Connect with a user that has only been granted SELECT permissions. Situations like this is why permissions exist in the first place. |
Django form validation: making "required" conditional? | 2,306,800 | 11 | 2010-02-21T18:00:06Z | 2,307,132 | 19 | 2010-02-21T19:25:40Z | [
"python",
"django",
"django-forms"
] | I'm new to Django (and Python), and am trying to figure out how to conditionalize certain aspects of form validation. In this case, there's a HTML interface to the application where the user can choose a date and a time from widgets. The `clean` method on the form object takes the values of the time and date fields and... | This is done with the `clean` method on the form. You need to set `foo_date` and `foo_time` to `required=False`, though, because `clean` is only called after every field has been validated (see also the [documentation](http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend... |
What is the difference between root.destroy() and root.quit()? | 2,307,464 | 18 | 2010-02-21T21:09:21Z | 2,308,687 | 17 | 2010-02-22T03:50:24Z | [
"python",
"tkinter"
] | In Python using `tkinter`, what is the difference between `root.destroy()` and `root.quit()` when closing the root window?
Is one prefered over the other? Does one release resources that the other doesn't? | "quit() stops the TCL interpreter. This is in most cases what you want, because your Tkinter-app will also stop. It can be a problem, if you e.g. call your app from idle. idle is itself a Tkinker-app, so if you call quit() in your app and the TCL interpreter gets terminated, idle will also terminate (or get confused ).... |
Generating and applying diffs in python | 2,307,472 | 20 | 2010-02-21T21:13:09Z | 2,307,741 | 21 | 2010-02-21T22:39:28Z | [
"python",
"diff",
"revision",
"difflib"
] | Is there an 'out-of-the-box' way in python to generate a list of differences between two texts, and then applying this diff to one file to obtain the other, later?
I want to keep the revision history of a text, but I don't want to save the entire text for each revision if there is just a single edited line. I looked a... | Did you have a look at diff-match-patch from google? Apparantly google Docs uses this set of algoritms. It includes not only a diff module, but also a patch module, so you can generate the newest file from older files and diffs.
A python version is included.
<http://code.google.com/p/google-diff-match-patch/> |
Generating and applying diffs in python | 2,307,472 | 20 | 2010-02-21T21:13:09Z | 2,307,743 | 9 | 2010-02-21T22:39:35Z | [
"python",
"diff",
"revision",
"difflib"
] | Is there an 'out-of-the-box' way in python to generate a list of differences between two texts, and then applying this diff to one file to obtain the other, later?
I want to keep the revision history of a text, but I don't want to save the entire text for each revision if there is just a single edited line. I looked a... | Does difflib.unified\_diff do want you want? There is an example [here](http://www.doughellmann.com/PyMOTW/difflib/index.html). |
Python class syntax - is this a good idea? | 2,307,590 | 4 | 2010-02-21T21:47:36Z | 2,307,601 | 8 | 2010-02-21T21:50:22Z | [
"python",
"syntax"
] | I'm tempted to define my Python classes like this:
```
class MyClass(object):
"""my docstring"""
msg = None
a_variable = None
some_dict = {}
def __init__(self, msg):
self.msg = msg
```
Is declaring the object variables (msg, a\_variable, etc) at the top, like Java good or bad or indiffer... | Defining variables in the class defintion like that makes the variable accessible between every instance of that class. In Java terms it is *a bit like* making the variable static. However, there are major differences as show below.
```
class MyClass(object):
msg = "ABC"
print MyClass.msg #prints ABC
a = MyCl... |
Uploading a HTML file to Google App Engine - getting 405 | 2,307,645 | 3 | 2010-02-21T22:07:22Z | 2,307,729 | 9 | 2010-02-21T22:35:07Z | [
"python",
"google-app-engine"
] | I'm trying to do a simple echo app using Python. I want to submit a file with a POST form and echo it back (an HTML file).
Here's the `handlers` section of the YAML I'm using:
```
handlers:
- url: /statics
static_dir: statics
- url: .*
script: main.py
```
It's basically the hello world example in `main.py` and ... | You are submitting your form with the POST method, but you implemented a `get()` handler instead of a `post()` handler. Changing `def get(self):` to `def post(self):` should fix the HTTP 405 error. |
Encoding detection library in python | 2,307,795 | 3 | 2010-02-21T22:55:54Z | 2,308,000 | 9 | 2010-02-21T23:52:44Z | [
"python",
"html",
"xml",
"http",
"character-encoding"
] | This is somehow related to my question [here](http://stackoverflow.com/questions/2305997/unicodedecodeerror-problem-with-mechanize).
I process tons of texts (in HTML and XML mainly) fetched via HTTP. I'm looking for a library in python that can do smart encoding detection based on different strategies and convert text... | [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)'s [UnicodeDammit](http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit), which in turn uses [chardet](https://pypi.python.org/pypi/chardet).
`chardet` by itself is quite useful for the general c... |
How to limit the heap size? | 2,308,091 | 35 | 2010-02-22T00:21:12Z | 2,308,635 | 36 | 2010-02-22T03:33:53Z | [
"python",
"linux",
"memory"
] | I sometimes write Python programs which are very difficult to determine how much memory it will use before execution. As such, I sometimes invoke a Python program that tries to allocate massive amounts of RAM causing the kernel to heavily swap and degrade the performance of other running processes.
Because of this, I ... | Check out [resource.setrlimit()](http://docs.python.org/library/resource.html#resource.setrlimit). It only works on Unix systems but it seems like it might be what you're looking for, as you can choose a maximum heap size for your process and your process's children with the resource.RLIMIT\_DATA parameter.
EDIT: Addi... |
How to convert a numeric string with place-value commas into an integer? | 2,308,443 | 7 | 2010-02-22T02:20:57Z | 2,308,452 | 9 | 2010-02-22T02:22:30Z | [
"python"
] | In Python, what is a clean and elegant way to convert strings like "1,374" or "21,000,000" to int values like 1374 or 21000000? | It really depends where you get your number from.
If the number you are trying to convert comes from user input, use `locale.atoi()`. That way, the number will be parsed in a way that is consistent with the user's settings and thus expectations.
If on the other hand you read it, let's say, from a file, that always us... |
Multiple value checks using 'in' operator (Python) | 2,308,944 | 4 | 2010-02-22T05:12:01Z | 2,308,950 | 15 | 2010-02-22T05:13:21Z | [
"python"
] | ```
if 'string1' in line: ...
```
... works as expected but what if I need to check multiple strings like so:
```
if 'string1' or 'string2' or 'string3' in line: ...
```
... doesn't seem to work. | ```
if any(s in line for s in ('string1', 'string2', ...)):
``` |
Inserting an item in a Tuple | 2,309,329 | 18 | 2010-02-22T07:03:52Z | 2,309,334 | 26 | 2010-02-22T07:05:46Z | [
"python",
"insert",
"tuples"
] | Yes, I understand tuples are immutable but the situation is such that I need to insert an extra value into each tuple. So one of the items is the amount, I need to add a new item next to it in a different currency, like so:
```
('Product', '500.00', '1200.00')
```
Possible?
Thanks! | You can cast it to a list, insert the item, then cast it back to a tuple.
```
a = ('Product', '500.00', '1200.00')
a = list(a)
a.insert(3, 'foobar')
a = tuple(a)
print a
>> ('Product', '500.00', '1200.00', 'foobar')
``` |
Inserting an item in a Tuple | 2,309,329 | 18 | 2010-02-22T07:03:52Z | 2,309,338 | 29 | 2010-02-22T07:07:03Z | [
"python",
"insert",
"tuples"
] | Yes, I understand tuples are immutable but the situation is such that I need to insert an extra value into each tuple. So one of the items is the amount, I need to add a new item next to it in a different currency, like so:
```
('Product', '500.00', '1200.00')
```
Possible?
Thanks! | Since tuples are immutable, this will result in a new tuple. Just place it back where you got the old one.
```
sometuple + (someitem,)
``` |
Inserting an item in a Tuple | 2,309,329 | 18 | 2010-02-22T07:03:52Z | 2,309,350 | 13 | 2010-02-22T07:09:40Z | [
"python",
"insert",
"tuples"
] | Yes, I understand tuples are immutable but the situation is such that I need to insert an extra value into each tuple. So one of the items is the amount, I need to add a new item next to it in a different currency, like so:
```
('Product', '500.00', '1200.00')
```
Possible?
Thanks! | You absolutely need to make a new tuple -- then you can rebind the name (or whatever reference[s]) from the old tuple to the new one. The `+=` operator can help (if there was only one reference to the old tuple), e.g.:
```
thetup += ('1200.00',)
```
does the appending and rebinding in one fell swoop. |
Inserting an item in a Tuple | 2,309,329 | 18 | 2010-02-22T07:03:52Z | 31,571,003 | 8 | 2015-07-22T18:18:47Z | [
"python",
"insert",
"tuples"
] | Yes, I understand tuples are immutable but the situation is such that I need to insert an extra value into each tuple. So one of the items is the amount, I need to add a new item next to it in a different currency, like so:
```
('Product', '500.00', '1200.00')
```
Possible?
Thanks! | ```
def tuple_insert(tup,pos,ele):
tup = tup[:pos]+(ele,)+tup[pos:]
return tup
tuple_insert(tup,pos,9999)
```
**tup: tuple
pos: Position to insert
ele: Element to insert** |
Get rid of leading zeros for date strings in Python? | 2,309,828 | 14 | 2010-02-22T09:10:29Z | 2,309,910 | 7 | 2010-02-22T09:24:15Z | [
"python",
"date",
"leading-zero"
] | Is there a nimble way to get rid of leading zeros for date strings in Python?
In the example below I'd like to get 12/1/2009 in return instead of 12/01/2009. I guess I could use regular expressions. But to me that seems like overkill. Is there a better solution?
```
>>> time.strftime('%m/%d/%Y',time.strptime('12/1/20... | @OP, it doesn't take much to do a bit of string manipulation.
```
>>> t=time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
>>> '/'.join( map( str, map(int,t.split("/")) ) )
'12/1/2009'
``` |
Get rid of leading zeros for date strings in Python? | 2,309,828 | 14 | 2010-02-22T09:10:29Z | 2,309,945 | 21 | 2010-02-22T09:33:15Z | [
"python",
"date",
"leading-zero"
] | Is there a nimble way to get rid of leading zeros for date strings in Python?
In the example below I'd like to get 12/1/2009 in return instead of 12/01/2009. I guess I could use regular expressions. But to me that seems like overkill. Is there a better solution?
```
>>> time.strftime('%m/%d/%Y',time.strptime('12/1/20... | A simpler and readable solution is to format it yourself:
```
>>> d = datetime.datetime.now()
>>> "%d/%d/%d"%(d.month, d.day, d.year)
4/8/2012
``` |
plotting lines without blocking execution | 2,310,851 | 16 | 2010-02-22T12:40:56Z | 2,312,184 | 12 | 2010-02-22T16:08:10Z | [
"python",
"matplotlib"
] | I am using matplotlib to draw charts and graphs.
When I plot the chart using the command `show()` my code blocks at this command.
I would like to refresh my list of values with new data , and than refresh the image on the background. How to do that without closing each time the window with the graph?
Below is the cod... | In IPython started with `-pylab` it should not block.
Otherwise:
With `ion()` you turn the interactive mode on. `show()` does not block your system
anymore. Every `draw()` or `plot(x, y)` updated your plot.
`ioff()` turns interactive mode off. Useful if you add lots of data and don't
want to update every little detai... |
Getting a machine's external IP address | 2,311,510 | 21 | 2010-02-22T14:36:40Z | 2,311,543 | 15 | 2010-02-22T14:41:19Z | [
"python",
"standard-library"
] | Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x
```
import os
import urllib2
def check_in():
fqn = os.uname()[1]
ex... | If you are behind a router which obtains the external IP, I'm afraid you have no other option but to use external service like you do. If the router itself has some query interface, you can use it, but the solution will be very environment-specific and unreliable. |
Getting a machine's external IP address | 2,311,510 | 21 | 2010-02-22T14:36:40Z | 2,311,622 | 7 | 2010-02-22T14:52:17Z | [
"python",
"standard-library"
] | Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x
```
import os
import urllib2
def check_in():
fqn = os.uname()[1]
ex... | If you think and external source is too unreliable, you could pool a few different services. For most ip lookup pages they require you to scrape html, but a few of them that have created lean pages for scripts like yours - also so they can reduce the hits on their sites:
* [automation.whatismyip.com/n09230945.asp](htt... |
Getting a machine's external IP address | 2,311,510 | 21 | 2010-02-22T14:36:40Z | 22,157,882 | 25 | 2014-03-03T21:31:28Z | [
"python",
"standard-library"
] | Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x
```
import os
import urllib2
def check_in():
fqn = os.uname()[1]
ex... | I wrote a module for that: [ipgetter](https://pypi.python.org/pypi/ipgetter).
Is designed to fetch your external IP address from the internet. It is used mostly when behind a NAT. It picks your IP randomly from a serverlist to minimize request overhead on a single server.
Actually with 44 server and test function to ve... |
python string interpolation | 2,311,906 | 13 | 2010-02-22T15:29:26Z | 2,312,243 | 8 | 2010-02-22T16:17:07Z | [
"python",
"string",
"string-interpolation"
] | What could generate the following behavior ?
```
>>> print str(msg)
my message
>>> print unicode(msg)
my message
```
But:
```
>>> print '%s' % msg
another message
```
More info:
* my `msg` object is inherited from `unicode`.
* the methods `__str__`/`__unicode__`/`__repr__` methods were overridden to return the str... | *Update 2:* Please find the original answer, including a simple example of a class exhibiting the behaviour described by the OP, below the horizontal bar. As for what I was able to surmise in the course of my inquiry into Python's sources (v. 2.6.4):
The file `Include/unicodeobject.h` contains the following to lines (... |
Python ( or general programming ). Why use <> instead of != and are there risks? | 2,312,169 | 5 | 2010-02-22T16:06:40Z | 2,312,202 | 15 | 2010-02-22T16:10:47Z | [
"python",
"operators"
] | I think if I understand correctly, `a <> b` is the exact same thing functionally as `a != b`, and in Python `not a == b`, but is there reason to use `<>` over the other versions? I know a common mistake for Python newcomers is to think that `not a is b` is the same as `a != b` or `not a == b`.
1. Do similar misconcept... | `<>` in Python 2 is an exact synonym for `!=` -- no reason to use it, no disadvantages either except the gratuitous heterogeneity (a style issue). It's been long discouraged, and has now been removed in Python 3. |
Python ( or general programming ). Why use <> instead of != and are there risks? | 2,312,169 | 5 | 2010-02-22T16:06:40Z | 2,312,600 | 8 | 2010-02-22T17:06:42Z | [
"python",
"operators"
] | I think if I understand correctly, `a <> b` is the exact same thing functionally as `a != b`, and in Python `not a == b`, but is there reason to use `<>` over the other versions? I know a common mistake for Python newcomers is to think that `not a is b` is the same as `a != b` or `not a == b`.
1. Do similar misconcept... | Just a pedantic note: the `<>` operator is in some sense misnamed (misdenoted?). `a <> b` might naturally be interpreted as meaning `a < b or a > b` (evaluating `a` and `b` only once, of course), but since not all orderings are total orderings, this doesn't match the actual semantics. For example, `2.0 != float('nan')`... |
Window Icon of Exe in PyQt4 | 2,312,210 | 9 | 2010-02-22T16:11:53Z | 5,424,782 | 14 | 2011-03-24T19:57:43Z | [
"python",
"windows",
"qt",
"qt4",
"py2exe"
] | I have a small program in PyQt4 and I want to compile the program into an Exe. I am using py2exe to do that. I can successfully set icon in the windows title bar using the following code, but when i compile it into exe the icon is lost and i see the default windows application. here is my program:
```
import sys
from ... | The problem is that py2exe doesn't include the qt icon reader plugin. You need to tell it to include it with the data\_files parameter. Something along these lines:
```
setup(windows=[{"script":script_path,
"icon_resources":[(1, icon_path)]}],
data_files = [
('imageformats', [
... |
Can the Django dev server correctly serve SVG? | 2,312,714 | 15 | 2010-02-22T17:24:16Z | 2,313,050 | 37 | 2010-02-22T18:17:00Z | [
"python",
"django",
"svg"
] | I am trying to serve a svg map using:
```
<object data="map.svg" type="image/svg+xml" width="400" height="300">
<embed src="map.svg" type="image/svg+xml" width="400" height="300" />
</object>
```
In Firefox this leads to a plugin prompt. If I rename map.**svg** to map.**xml** it shows the image correctly. I assum... | I don't have Django available to test this at the moment but it looks like the static server uses the [mimetypes library](http://docs.python.org/dev/library/mimetypes.html) to determine the content type (specifically guess\_type()).
With a little bit a Googling, I came across [some code](http://moinmo.in/MacroMarket/E... |
regex for state abbreviations (python) | 2,313,032 | 3 | 2010-02-22T18:13:28Z | 2,313,098 | 7 | 2010-02-22T18:23:16Z | [
"python",
"regex"
] | I am trying to create a regex that matches a US state abbreviations in a string using python.
The abbreviation can be in the format:
```
CA
Ca
```
The string could be:
```
Boulder, CO 80303
Boulder, Co
Boulder CO
...
```
Here is what I have, which obviously doesn't work that well. I'm not very good with regular ex... | A simple and reliable way is to have all the states listed:
```
states = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN', 'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL',... |
Python: How to Access Linux Paths | 2,313,053 | 2 | 2010-02-22T18:17:39Z | 2,313,119 | 7 | 2010-02-22T18:24:55Z | [
"python",
"linux",
"path"
] | Using Python, how does one parse/access files with Linux-specific features, like `"~/.mozilla/firefox/*.default"`? I've tried this, but it doesn't work.
Thanks | This
```
import glob, os
glob.glob(os.path.expanduser('~/.mozilla/firefox/*.default'))
```
will give you a list of all files ending in ".default" in the current user's `~/.mozilla/firefox` directory using [os.path.expanduser](http://docs.python.org/library/os.path.html#os.path.expanduser) to expand the `~` in the pat... |
Default value in a function in Python | 2,313,075 | 7 | 2010-02-22T18:20:03Z | 2,313,105 | 10 | 2010-02-22T18:23:36Z | [
"python",
"default-value"
] | I am noticing the following:
```
class c:
def __init__(self, data=[]):
self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]
```
Is this the correct behavior? | Yes, it's correct behavior.
However, from your question, it appears that it's not what you expected.
If you want it to match your expectations, be aware of the following:
Rule 1. Do not use mutable objects as default values.
```
def anyFunction( arg=[] ):
```
Will not create a fresh list object. The default list o... |
Python: Access a MySQL db without MySQLdb module | 2,313,307 | 2 | 2010-02-22T18:54:20Z | 2,313,495 | 8 | 2010-02-22T19:23:02Z | [
"python",
"mysql",
"osx"
] | Is there another way to connect to a MySQL database with what came included in the version of Python (2.5.1) that is bundled with Mac OS 10.5.x? I unfortunately cannot add the the MySQLdb module to the client machines I am working with...I need to work with the stock version of Python that shipped with Leopard. | Why not install a user (non-system) copy of MySQLdb?
These are [the files](http://sourceforge.net/projects/mysql-python/files/) you'd need to install:
```
/usr/lib/pyshared/python2.6
/usr/lib/pyshared/python2.6/_mysql.so
/usr/share/pyshared
/usr/share/pyshared/MySQLdb
/usr/share/pyshared/MySQLdb/constants
/usr/share/p... |
Google apps login in django | 2,313,573 | 10 | 2010-02-22T19:37:51Z | 2,575,075 | 8 | 2010-04-04T16:33:40Z | [
"python",
"django",
"google-apps",
"django-openid-auth"
] | I'm developing a django app that integrates with google apps. I'd like to let the users login with their google apps accounts (accounts in google hosted domains, *not google accounts*) so they can access their docs, calendar, and whatnot.
In order to do it, I downloaded and started using django\_openid\_auth (and thus... | According to <http://groups.google.com/group/google-federated-login-api/web/openid-discovery-for-hosted-domains>, Google changed the way of IdP Discovery and user XRDS check a little bit to give Google Apps users openid in <http://example.com/openid?id=108441225163454056756> kind of format without asking the users to b... |
Python & sql server | 2,314,178 | 25 | 2010-02-22T21:04:50Z | 2,314,269 | 13 | 2010-02-22T21:16:53Z | [
"python",
"sql",
"sql-server"
] | What is the best way to access sql server from python is it DB-API ?
Also could someone provide a such code using the DB-API how to connect to sql server from python and excute query ? | See [pyodbc](http://code.google.com/p/pyodbc/) - [Python Database API Specification v2.0](http://www.python.org/dev/peps/pep-0249/) implementation. Works great.
Additionally you can use it with other databases. If using with SQL Server 2008, make sure you use Native Driver if you need to support new `DATE` data types. |
Python: Why does right shift >> round down and where should it be used? | 2,314,181 | 3 | 2010-02-22T21:05:20Z | 2,314,209 | 13 | 2010-02-22T21:09:51Z | [
"python",
"operators"
] | I've never used the `>>` and `<<` operators, not because I've never needed them, but because I don't know if I could have used them, or where I should have.
`100 >> 3` outputs `12` instead of `12.5`. Why is this. Perhaps learning where to best use right shift will answer that implicitly, but I'm curious. | **Right shift is *not* division**
Let's look at what [right-shift](http://en.wikipedia.org/wiki/Logical_shift) *actually* does, and it will become clear.
First, recall that a number is stored in memory as a collection of binary digits. If we have 8 bits of memory, we can store 2 as `00000010` and 5 as `00000101`.
Ri... |
Using python to run other programs | 2,314,206 | 6 | 2010-02-22T21:09:20Z | 2,314,225 | 7 | 2010-02-22T21:11:38Z | [
"python",
"unix",
"subprocess"
] | I have a command that works great on the command line. It has lots of arguments like `cmd --thing foo --stuff bar -a b input output`
I want to run this from python and block waiting for it to complete. As the script prints things to `stdout` and `stderr` I want it to be immediately shown to the user.
What is the righ... | You have to quote each field separately, ie. split the options from their arguments.
```
import subprocess
output = subprocess.call(["cmd", "--thing", "foo", "--stuff", "bar", "-a", "b", "input", "output"])
```
otherwise you are effectively running cmd like this
```
$ cmd --thing\ foo --stuff\ bar -a\ b input output... |
python logging to database | 2,314,307 | 15 | 2010-02-22T21:22:10Z | 2,314,325 | 11 | 2010-02-22T21:24:45Z | [
"python",
"database",
"logging"
] | I'm seeking a way to let the python logger module to log to database and falls back to file system when the db is down.
So basically 2 things: How to let the logger log to database and how to make it fall to file logging when the db is down. | Write yourself a **[handler](http://docs.python.org/library/logging.html#handlers)** that directs the logs to the database in question. When it fails, you can remove it from the handler list of the logger. There are many ways to deal with the failure-modes. |
How to plot the lines first and points last in matplotlib | 2,314,379 | 23 | 2010-02-22T21:34:48Z | 2,314,461 | 35 | 2010-02-22T21:44:19Z | [
"python",
"matplotlib"
] | I have a simple plot with several sets of points and lines connecting each set. I want the points to be plotted on top of the lines (so that the line doesn't show inside the point). Regardless of order of the `plot` and `scatter` calls, this plot comes out the same, and not as I'd like. Is there a simple way to do it?
... | You need to set the Z-order.
```
plt.plot(R,P,color='0.2',lw=1.5, zorder=1)
plt.scatter(R,P,s=150,color=c, zorder=2)
```
Check out this example.
<http://matplotlib.sourceforge.net/examples/pylab_examples/zorder_demo.html> |
Python daemon to watch a folder and update a database | 2,314,892 | 4 | 2010-02-22T22:51:56Z | 2,315,452 | 8 | 2010-02-23T00:59:23Z | [
"python",
"database",
"filesystems",
"daemon"
] | This is specifically geared towards managing MP3 files, but it should easily work for any directory structure with a lot of files.
I want to find or write a daemon (preferably in Python) that will watch a folder with many subfolders that should all contain X number of MP3 files. Any time a file is added, updated or de... | Another answer already suggested [pyinotify](http://trac.dbzteam.org/pyinotify) for Linux, let me add [watch\_directory](http://timgolden.me.uk/python/downloads/watch_directory.py) for Windows (a good discussion of the possibilities in Windows is [here](http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_c... |
How do I find missing dates in a list of sorted dates? | 2,315,032 | 8 | 2010-02-22T23:18:29Z | 2,315,279 | 13 | 2010-02-23T00:11:40Z | [
"python"
] | In Python how do I find all the missing days in a sorted list of dates? | using sets
```
>>> from datetime import date, timedelta
>>> d = [date(2010, 2, 23), date(2010, 2, 24), date(2010, 2, 25),
date(2010, 2, 26), date(2010, 3, 1), date(2010, 3, 2)]
>>> date_set = set(d[0] + timedelta(x) for x in range((d[-1] - d[0]).days))
>>> missing = sorted(date_set - set(d))
>>> missing
[date... |
How to generate a module object from a code object in Python | 2,315,044 | 11 | 2010-02-22T23:21:25Z | 2,315,369 | 15 | 2010-02-23T00:34:56Z | [
"python",
"bytecode"
] | Given that I have the code object for a module, how do I get the corresponding module object?
It looks like `moduleNames = {}; exec code in moduleNames` does something very close to what I want. It returns the globals declared in the module into a dictionary. But if I want the actual module object, how do I get it?
E... | As a comment already indicates, in today's Python the preferred way to instantiate types that don't have built-in names is to call the type obtained via the [types](http://docs.python.org/library/types.html?highlight=types#module-types) module from the standard library:
```
>>> import types
>>> m = types.ModuleType('m... |
How can I determine if instance of class from Django model is subclass of another model? | 2,315,047 | 8 | 2010-02-22T23:21:58Z | 2,315,059 | 8 | 2010-02-22T23:24:05Z | [
"python",
"django",
"inheritance",
"django-models",
"subclass"
] | I have a class called `BankAccount` as base class. I also have `CheckingAccount` and `SavingsAccount` classes that inherit from `BankAccount`.
BankAccount is not an abstract class but I do not create an object from it, only the inheriting classes.
Then, I execute a query like this:
```
account = BankAccount.objects.... | Try to use the `checkingaccount` and `savingsaccount` attributes. The one it is will not blow up. |
UTF-8 and upper() | 2,315,451 | 6 | 2010-02-23T00:59:09Z | 2,315,457 | 12 | 2010-02-23T01:00:23Z | [
"python",
"case-sensitive"
] | I want to transform UTF-8 strings using built-in functions such as upper() and capitalize().
For example:
```
>>> mystring = "iÅÄüı"
>>> print mystring.upper()
IÅÄüı # should be İÅÄÃI instead.
```
How can I fix this? | Do not perform actions on encoded strings; decode to `unicode` first.
```
>>> mystring = "iÅÄüı"
>>> print mystring.decode('utf-8').upper()
IÅÄÃI
``` |
In Python, how do I loop through the dictionary and change the value if it equals something? | 2,315,520 | 23 | 2010-02-23T01:19:42Z | 2,315,529 | 71 | 2010-02-23T01:21:31Z | [
"python",
"dictionary"
] | If the value is None, I'd like to change it to "" (empty string).
I start off like this, but I forget:
```
for k, v in mydict.items():
if v is None:
... right?
``` | ```
for k, v in mydict.iteritems():
if v is None:
mydict[k] = ''
```
In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using `items` to loop on an independent list copy thereof might be prudent -- but assi... |
In Python, how do I loop through the dictionary and change the value if it equals something? | 2,315,520 | 23 | 2010-02-23T01:19:42Z | 2,315,715 | 7 | 2010-02-23T02:16:01Z | [
"python",
"dictionary"
] | If the value is None, I'd like to change it to "" (empty string).
I start off like this, but I forget:
```
for k, v in mydict.items():
if v is None:
... right?
``` | You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
```
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
```
***Update*** - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varyi... |
Get number of modified rows after sqlite3 execute | 2,316,003 | 5 | 2010-02-23T03:55:19Z | 2,316,070 | 12 | 2010-02-23T04:16:09Z | [
"python",
"c",
"sqlite3"
] | When performing SQL statements such as `UPDATE`, and `INSERT`, the usual `.fetch*()` methods on the `Cursor` instance obviously don't apply to the number of **rows modified**.
In the event of executing one of the aforementioned statements, what is the correct way to obtain the corresponding row count in Python, and th... | After calling your `Cursor.execute*()` methods with your UPDATE or INSERT statements you can use `Cursor.rowcount` to see the # of rows affected by the execute call.
If I had to guess I would say the python lib is calling [`int sqlite3_changes(sqlite3*)`](http://www.sqlite.org/c3ref/changes.html) from the C API but I ... |
How to print line breaks in Python Django template | 2,316,028 | 8 | 2010-02-23T04:03:34Z | 2,316,038 | 26 | 2010-02-23T04:07:33Z | [
"python",
"html",
"django",
"templates"
] | ```
{'quotes': u'Live before you die.\n\n"Dream as if you\'ll live forever, live as if you\'ll die today"\n\n"Love one person, take care of them until you die. You know, raise kids. Have a good life. Be a good friend. Try to be completely who you are, figure out what you personally love and go after it with everything ... | Use the [`linebreaks`](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#linebreaks) filter. |
Converting a string to a formatted date-time string using Python | 2,316,987 | 17 | 2010-02-23T09:29:24Z | 2,316,990 | 8 | 2010-02-23T09:29:44Z | [
"python",
"datetime",
"time",
"strftime",
"strptime"
] | I'm trying to convert a string "20091229050936" into "05:09 29 December 2009 (UTC)"
```
>>>import time
>>>s = time.strptime("20091229050936", "%Y%m%d%H%M%S")
>>>print s.strftime('%H:%M %d %B %Y (UTC)')
```
gives
`AttributeError: 'time.struct_time' object has no attribute 'strftime'`
Clearly, I've made a mistake: tim... | `time.strptime` returns a `time_struct`; `time.strftime` accepts a `time_struct` as an optional parameter:
```
>>>s = time.strptime(page.editTime(), "%Y%m%d%H%M%S")
>>>print time.strftime('%H:%M %d %B %Y (UTC)', s)
```
gives
`05:09 29 December 2009 (UTC)` |
Converting a string to a formatted date-time string using Python | 2,316,987 | 17 | 2010-02-23T09:29:24Z | 2,317,046 | 34 | 2010-02-23T09:39:08Z | [
"python",
"datetime",
"time",
"strftime",
"strptime"
] | I'm trying to convert a string "20091229050936" into "05:09 29 December 2009 (UTC)"
```
>>>import time
>>>s = time.strptime("20091229050936", "%Y%m%d%H%M%S")
>>>print s.strftime('%H:%M %d %B %Y (UTC)')
```
gives
`AttributeError: 'time.struct_time' object has no attribute 'strftime'`
Clearly, I've made a mistake: tim... | For `datetime` objects, `strptime` is a [static method](http://docs.python.org/library/datetime.html#datetime.datetime.strftime) of the `datetime` class, not a free function in the `datetime` module:
```
>>> import datetime
>>> s = datetime.datetime.strptime("20091229050936", "%Y%m%d%H%M%S")
>>> print s.strftime('%H:%... |
PIP: Installing only the dependencies | 2,317,410 | 10 | 2010-02-23T10:44:38Z | 2,318,246 | 13 | 2010-02-23T12:59:39Z | [
"python",
"distribution",
"virtualenv",
"pip",
"distribute"
] | I have a script that creates a `virtualenv`, installs `distribute` and `pip` in it and then optionally clones a `git` repo.
Now I have the project I will be working on, installed. But its dependencies are not installed. How can I make `pip` install all the dependencies as if I have issued a `pip install MyApp`?
**EDI... | You should use the pip requirements file.
Essentially, place all your requirements, one in each line in a file and pass that to pip using the command
```
pip install -r requirements.txt
```
What more, if you have a standard environment, pip can actually dump such a file from existing installs using the command:
```... |
PIP: Installing only the dependencies | 2,317,410 | 10 | 2010-02-23T10:44:38Z | 2,354,586 | 14 | 2010-03-01T08:31:43Z | [
"python",
"distribution",
"virtualenv",
"pip",
"distribute"
] | I have a script that creates a `virtualenv`, installs `distribute` and `pip` in it and then optionally clones a `git` repo.
Now I have the project I will be working on, installed. But its dependencies are not installed. How can I make `pip` install all the dependencies as if I have issued a `pip install MyApp`?
**EDI... | In my package root issuing `pip install -e .` installs dependencies. |
Django count RawQuerySet | 2,317,452 | 15 | 2010-02-23T10:52:45Z | 2,317,552 | 16 | 2010-02-23T11:09:44Z | [
"python",
"django",
"count"
] | Hay, I'm using django 1.2 and i want to know how to count rows from a raw queryset(RawQuerySet).
The traditional .count() method doesn't work.
Heres my query
```
query = "SELECT *, ((ACOS(SIN(%s * PI() / 180) * SIN(lat * PI() / 180) + COS(%s * PI() / 180) * COS(lat * PI() / 180) * COS((%s - lon) * PI() / 180)) * 180... | Use the 'len()' function. This would give:
```
query = "SELECT *, ((ACOS(SIN(%s * PI() / 180) * SIN(lat * PI() / 180) + COS(%s * PI() / 180) * COS(lat * PI() / 180) * COS((%s - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM app_car WHERE price BETWEEN %s AND %s HAVING distance<=%s ORDER BY distance ... |
Asynchronous COMET query with Tornado and Prototype | 2,317,501 | 9 | 2010-02-23T11:00:53Z | 2,430,614 | 15 | 2010-03-12T05:05:43Z | [
"python",
"ajax",
"comet",
"long-polling",
"tornado"
] | I'm trying to write simple web application using Tornado and JS Prototype library. So, the client can execute long running job on server. I wish, that this job runs Asynchronously - so that others clients could view page and do some stuff there.
Here what i've got:
```
#!/usr/bin/env/ pytthon
import tornado.httpserv... | Tornado is single-threaded web server. Your while loop in `wait_for_smith` method is blocking Tornado.
You can rewrite that method like this:
```
def wait_for_smth(self, callback, t=10):
if t:
print "Sleeping 2 second, t=%s" % t
tornado.ioloop.IOLoop.instance().add_timeout(time.time() + 2, lambda:... |
How can I use a SOCKS 4/5 proxy with urllib2? | 2,317,849 | 39 | 2010-02-23T11:55:57Z | 2,339,260 | 53 | 2010-02-26T03:06:52Z | [
"python",
"proxy",
"urllib2",
"socks"
] | How can I use a SOCKS 4/5 proxy with urllib2 to download a web page? | You can use [SocksiPy](http://sourceforge.net/projects/socksipy/) module. Simply copy the file "socks.py" to your Python's lib/site-packages directory, and you're ready to go.
You must use **socks** before urllib2. (Try it `pip install PySocks` )
For example:
```
import socks
import socket
socks.setdefaultproxy(sock... |
How can I use a SOCKS 4/5 proxy with urllib2? | 2,317,849 | 39 | 2010-02-23T11:55:57Z | 8,100,870 | 18 | 2011-11-11T22:44:52Z | [
"python",
"proxy",
"urllib2",
"socks"
] | How can I use a SOCKS 4/5 proxy with urllib2 to download a web page? | Adding an alternative to pan's answer when you need to use many different proxies at the same time.
In that case you need to create an opener like you do with a http proxy. There is a code available in GitHub <https://gist.github.com/869791>
```
opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS4, '... |
how to follow meta refreshes in Python | 2,318,446 | 9 | 2010-02-23T13:31:41Z | 3,668,771 | 8 | 2010-09-08T14:30:59Z | [
"python",
"redirect",
"refresh",
"urllib2",
"httplib2"
] | Python's urllib2 follows 3xx redirects to get the final content. Is there a way to make urllib2 (or some other library such as [httplib2](http://code.google.com/p/httplib2/)) also follow [meta refreshes](http://en.wikipedia.org/wiki/Meta_refresh)? Or do I need to parse the HTML manually for the refresh meta tags? | Here is a solution using BeautifulSoup and httplib2 (and certificate based authentication):
```
import BeautifulSoup
import httplib2
def meta_redirect(content):
soup = BeautifulSoup.BeautifulSoup(content)
result=soup.find("meta",attrs={"http-equiv":"Refresh"})
if result:
wait,text=result["conten... |
Plotting only upper/lower triangle of a heatmap | 2,318,529 | 9 | 2010-02-23T13:46:30Z | 2,319,256 | 7 | 2010-02-23T15:22:10Z | [
"python",
"matplotlib",
"plot"
] | In maptplotlib, one can create a heatmap representation of a correlation matrix using the imshow function. By definition, such a matrix is symmetrical around its main diagonal, therefore there is no need to present both the upper and lower triangles. For example:
.reshape(10, 10)
# create an upper triangular 'matrix' from A
A2 = NP.triu(A)
fig = PLT.figure()
ax1 = fig.add_subplot(111)
# use dir(matplotlib.cm) to get a list of the installed colormaps
# ... |
Plotting only upper/lower triangle of a heatmap | 2,318,529 | 9 | 2010-02-23T13:46:30Z | 2,332,520 | 11 | 2010-02-25T08:12:07Z | [
"python",
"matplotlib",
"plot"
] | In maptplotlib, one can create a heatmap representation of a correlation matrix using the imshow function. By definition, such a matrix is symmetrical around its main diagonal, therefore there is no need to present both the upper and lower triangles. For example:
 that I want to store arrays in. These arrays will be 1-dimensional and of length 4096.
So, I want to be able to go something like
```
column = 0 ... | Note that to leverage the full power of numpy, you'd be much better off with a 3-dimensional numpy array. Breaking apart the 3-d array into a 2-d array with 1-d values
may complicate your code and force you to use loops instead of built-in numpy functions.
It may be worth investing the time to refactor your code to us... |
Using regex to remove comments from source files | 2,319,019 | 16 | 2010-02-23T14:52:54Z | 2,319,078 | 14 | 2010-02-23T15:00:10Z | [
"python",
"regex",
"string"
] | I'm making a program to automate the writing of some C code, (I'm writing to parse strings into enumerations with the same name)
C's handling of strings is not that great.
So some people have been nagging me to try python.
I made a function that is supposed to remove C-style `/* COMMENT */` and `//COMMENT`
from a stri... | I would suggest using a REAL parser like [SimpleParse](http://pypi.python.org/pypi/SimpleParse/2.1.1a2) or [PyParsing](http://pypi.python.org/pypi/pyparsing/1.5.2). SimpleParse requires that you actually know EBNF, but is very fast. PyParsing has its own EBNF-like syntax but that is adapted for Python and makes it a br... |
Using regex to remove comments from source files | 2,319,019 | 16 | 2010-02-23T14:52:54Z | 2,319,116 | 17 | 2010-02-23T15:04:47Z | [
"python",
"regex",
"string"
] | I'm making a program to automate the writing of some C code, (I'm writing to parse strings into enumerations with the same name)
C's handling of strings is not that great.
So some people have been nagging me to try python.
I made a function that is supposed to remove C-style `/* COMMENT */` and `//COMMENT`
from a stri... | `re.sub` returns a string, so changing your code to the following will give results:
```
def removeComments(string):
string = re.sub(re.compile("/\*.*?\*/",re.DOTALL ) ,"" ,string) # remove all occurance streamed comments (/*COMMENT */) from string
string = re.sub(re.compile("//.*?\n" ) ,"" ,string) # remove a... |
Using regex to remove comments from source files | 2,319,019 | 16 | 2010-02-23T14:52:54Z | 18,381,470 | 16 | 2013-08-22T13:12:19Z | [
"python",
"regex",
"string"
] | I'm making a program to automate the writing of some C code, (I'm writing to parse strings into enumerations with the same name)
C's handling of strings is not that great.
So some people have been nagging me to try python.
I made a function that is supposed to remove C-style `/* COMMENT */` and `//COMMENT`
from a stri... | Again, an old question and many answers are given already but;
what about `"//comment-like strings inside quotes"`?
OP is asking how to do do it using regular expressions; so:
```
def remove_comments(string):
pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*$)"
# first group captures quoted strings (doubl... |
a == b is false, but id(a) == id(b) is true? | 2,319,107 | 13 | 2010-02-23T15:03:18Z | 2,319,152 | 7 | 2010-02-23T15:08:20Z | [
"python",
"object",
"methods",
"override"
] | Ran into the following:
```
>>> class A:
... def __str__(self):
... return "some A()"
...
>>> class B(A):
... def __str__(self):
... return "some B()"
...
>>> print A()
some A()
>>> print B()
some B()
>>> A.__str__ == B.__str__
False # seems reasonable, since each method is an object
... | The following works:
```
>>> id(A.__str__.im_func) == id(A.__str__.im_func)
True
>>> id(B.__str__.im_func) == id(A.__str__.im_func)
False
``` |
a == b is false, but id(a) == id(b) is true? | 2,319,107 | 13 | 2010-02-23T15:03:18Z | 2,319,238 | 10 | 2010-02-23T15:19:39Z | [
"python",
"object",
"methods",
"override"
] | Ran into the following:
```
>>> class A:
... def __str__(self):
... return "some A()"
...
>>> class B(A):
... def __str__(self):
... return "some B()"
...
>>> print A()
some A()
>>> print B()
some B()
>>> A.__str__ == B.__str__
False # seems reasonable, since each method is an object
... | As the string `id(A.__str__) == id(B.__str__)` is evaluated, `A.__str__` is created, its id taken, and then garbage collected. Then `B.__str__` is created, and happens to end up at the exact same address that `A.__str__` was at earlier, so it gets (in CPython) the same id.
Try assigning `A.__str__` and `B.__str__` to ... |
django and sqlalchemy | 2,319,231 | 7 | 2010-02-23T15:18:46Z | 2,319,331 | 12 | 2010-02-23T15:32:23Z | [
"python",
"django",
"orm"
] | hey,
I'm fairly new to Django and have a basic question: I want to use an ORM that I can work with it for Django and other python projects, so the basic question is Django ORM agnostic and if so how can I use SQLAlchemy with it for example?
If it's not, then what do you suggest for the above problem (using ORM objects... | Option 1: Use the Django ORM for other projects. <http://stackoverflow.com/questions/579511/using-only-the-db-part-of-django>
This works well. I prefer it.
Option 2: Use SQLAlchemy with Django. <http://stackoverflow.com/questions/1154331/sqlalchemy-and-django-is-it-production-ready> and <http://stackoverflow.com/ques... |
Can I run two web servers on the same computer? | 2,319,697 | 12 | 2010-02-23T16:10:40Z | 2,319,706 | 22 | 2010-02-23T16:11:15Z | [
"python",
"apache",
"webserver",
"conflict"
] | I just found out that I can write a really [simple web server](http://fragments.turtlemeat.com/pythonwebserver.php) using Python. I have already an Apache web server I would like to try the Python based web server on this machine. But I am afraid that I can get some kind of conflict if I try it. I mean how two web serv... | Make them listen to different ports and you will be fine.
The default web port is 80. When you open some url in browser without specifying a port, 80 is used by default.
You can configure your web server to listen to a different port but then you will also need to specify it explicitly in the url:
```
http://localho... |
Python and curl question | 2,320,107 | 4 | 2010-02-23T17:05:27Z | 2,320,926 | 10 | 2010-02-23T19:07:21Z | [
"python",
"django",
"curl"
] | I will be transmitting purchase info (like CC) to a bank gateway and retrieve the result by using Django thus via Python.
What would be the efficient and secure way of doing this?
I have read a documentation of this gateway for php, they seem to use this method:
```
$xml= Some xml holding data of a purchase.
$curl =... | Use of the standard library `urllib2` module should be enough:
```
import urllib
import urllib2
request_data = urllib.urlencode({"DATA": xml})
response = urllib2.urlopen("https://url of the virtual bank POS", request_data)
response_data = response.read()
data = response_data.split('\n')
```
I assume that `xml` vari... |
In Python, what's a good pattern for disabling certain code during unit tests? | 2,320,210 | 10 | 2010-02-23T17:20:48Z | 2,320,317 | 7 | 2010-02-23T17:34:13Z | [
"python",
"unit-testing",
"testing",
"dependency-injection"
] | In general I want to disable as little code as possible, and I want it to be explicit: I don't want the code being tested to decide whether it's a test or not, I want the test to tell that code "hey, BTW, I'm running a unit test, can you please not make your call to solr, instead can you please stick what you would sen... | You can use [Mock objects](http://en.wikipedia.org/wiki/Mock_object) to intercept the method calls that you do not want to execute.
E.g. You have some class `A`, where you don't want method `no()` to be called during a test.
```
class A:
def do(self):
print('do')
def no(self):
print('no')
```
A mock objec... |
Remove and ignore all files that have an extension from a git repository | 2,320,895 | 26 | 2010-02-23T19:03:13Z | 2,320,930 | 37 | 2010-02-23T19:07:37Z | [
"python",
"django",
"git",
"github"
] | I'm working on a django project with a few other developers and we have recently realized that all the .pwc files in our app cause the commits and repository to be cluttered.
Is there any way I can remove all .pwc files from all child directories in my git repository and then ignore them for any future commit? | Plenty of ways to remove them:
```
git ls-files | grep '\.pwc$' | xargs git rm
find . -name *.pwc | xargs git rm
```
Note: If you haven't committed them, just use `rm`, not `git rm`.
To ignore them in the future, simply add \*.pwc to the .gitignore. (If you don't have one, create a file named .gitignore at the top ... |
Remove and ignore all files that have an extension from a git repository | 2,320,895 | 26 | 2010-02-23T19:03:13Z | 14,625,656 | 11 | 2013-01-31T12:20:28Z | [
"python",
"django",
"git",
"github"
] | I'm working on a django project with a few other developers and we have recently realized that all the .pwc files in our app cause the commits and repository to be cluttered.
Is there any way I can remove all .pwc files from all child directories in my git repository and then ignore them for any future commit? | You can also use the following:
```
git rm -r '*.pwc'
```
and then make those files ignored by git:
```
echo '*.pwc' >> .gitignore
```
The last one is in case if you already have .gitignore file, if not, us single '>' sign. |
Python: Using vars() to assign a string to a variable | 2,320,945 | 17 | 2010-02-23T19:09:41Z | 2,321,633 | 27 | 2010-02-23T20:53:48Z | [
"python",
"string",
"dictionary",
"variables"
] | I find it very useful to be able to create new variables during runtime and create a dictionary of the results for processing later, i.e. writing to a file:
```
myDict = {}
for i in range (1,10):
temp = "variable"+str(i)
vars()[temp] = myFunctionThatReturnsData() # variable1= data1, variable2 = data2,etc.
... | **The pythonic way to create a sequence of variables**
If you want a sequence of variables, create a sequence. Instead of trying to create independent variables like:
```
variable0
variable1
variable2
variable3
```
You should look at creating a `list`. This is similar to what S.Lott is suggesting (S.Lott usually has... |
How do I render *parts* of a svg file? | 2,321,155 | 7 | 2010-02-23T19:44:54Z | 2,321,909 | 9 | 2010-02-23T21:34:57Z | [
"python",
"gtk",
"svg",
"cairo"
] | I want to render parts of a svg file by name but for the life of me I cannot figure out how to do so (using python + gtk).
Here's the svg file in question: <http://david.bellot.free.fr/svg-cards/files/SVG-cards-2.0.1.tar.gz> (**Update:** this file no longer exists, but you can track it down at <http://svg-cards.source... | The GTK library for rendering SVG is called RSVG. It has python bindings, but they are undocumented, and they don't wrap the `rsvg_handle_get_pixbuf_sub()` and `rsvg_handle_render_cairo_sub()` functions which you would normally use for that purpose in C. Here's what you have to do as far as I can tell. You extract the ... |
Detect mobile browser (not just iPhone) in python view | 2,321,172 | 32 | 2010-02-23T19:47:03Z | 2,321,195 | 19 | 2010-02-23T19:50:17Z | [
"python",
"django",
"mobile",
"user-agent"
] | I have a web application written in Django that has one specific page I'd like to implement a mobile version of the template (and slightly different logic) for. I'd like to be able to implement it ala this sudo code:
```
def(myView)
do some stuff
if user-is-on-a-mobile-device:
do some stuff
return (my ... | Update:
I just found: <http://code.google.com/p/minidetector/>
Which seems to do exactly what I want, I'm going to test now. Feel free to tell me i'm wrong! |
Detect mobile browser (not just iPhone) in python view | 2,321,172 | 32 | 2010-02-23T19:47:03Z | 4,152,306 | 15 | 2010-11-11T07:48:12Z | [
"python",
"django",
"mobile",
"user-agent"
] | I have a web application written in Django that has one specific page I'd like to implement a mobile version of the template (and slightly different logic) for. I'd like to be able to implement it ala this sudo code:
```
def(myView)
do some stuff
if user-is-on-a-mobile-device:
do some stuff
return (my ... | best practice: use [minidetector](http://code.google.com/p/minidetector/) to add the extra info to the request, then use django's built in request context to pass it to your templates like so.
```
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view_on_mobile_and_desk... |
Detect mobile browser (not just iPhone) in python view | 2,321,172 | 32 | 2010-02-23T19:47:03Z | 15,502,709 | 7 | 2013-03-19T14:50:05Z | [
"python",
"django",
"mobile",
"user-agent"
] | I have a web application written in Django that has one specific page I'd like to implement a mobile version of the template (and slightly different logic) for. I'd like to be able to implement it ala this sudo code:
```
def(myView)
do some stuff
if user-is-on-a-mobile-device:
do some stuff
return (my ... | go for the fork of minidetecor called django-mobi, it includes documentation on how to use it.
<https://pypi.python.org/pypi/django-mobi> |
Python passing list as argument | 2,322,068 | 16 | 2010-02-23T21:58:02Z | 2,322,079 | 34 | 2010-02-23T21:59:56Z | [
"python",
"list",
"function",
"arguments"
] | If i were to run this code:
```
def function(y):
y.append('yes')
return y
example = list()
function(example)
print(example)
```
Why would it return ['yes'] even though i am not directly changing the variable 'example', and how could I modify the code so that 'example' is not effected by the function? | Everything is a reference in Python. If you wish to avoid that behavior you would have to create a new copy of the original with `list()`. If the list contains more references, you'd need to use [deepcopy()](http://docs.python.org/library/copy.html)
```
def modify(l):
l.append('HI')
return l
def preserve(l):
t = l... |
Python passing list as argument | 2,322,068 | 16 | 2010-02-23T21:58:02Z | 17,684,311 | 7 | 2013-07-16T18:30:01Z | [
"python",
"list",
"function",
"arguments"
] | If i were to run this code:
```
def function(y):
y.append('yes')
return y
example = list()
function(example)
print(example)
```
Why would it return ['yes'] even though i am not directly changing the variable 'example', and how could I modify the code so that 'example' is not effected by the function? | The easiest way to modify the code will be add the [:] to the function call.
```
def function(y):
y.append('yes')
return y
example = list()
function(example[:])
print(example)
``` |
Should a Python generator raise an exception when there are no more elements to yield? | 2,322,342 | 4 | 2010-02-23T22:47:12Z | 2,322,363 | 8 | 2010-02-23T22:49:45Z | [
"python"
] | Should a Python generator raise an exception when there are no more elements to yield?
Which one? | It doesn't have to, but it can raise a [StopIteration](http://docs.python.org/library/exceptions.html#exceptions.StopIteration).
The more normal way to end the iteration is to let the function end and return naturally, or to use a return statement. This will cause a StopIteration to be raised on your behalf. |
Should a Python generator raise an exception when there are no more elements to yield? | 2,322,342 | 4 | 2010-02-23T22:47:12Z | 2,322,387 | 7 | 2010-02-23T22:53:51Z | [
"python"
] | Should a Python generator raise an exception when there are no more elements to yield?
Which one? | The only time I know that you have to manually raise StopIteration is when you are implementing a next() method on a class to signal that the iterator is terminated. For generators (functions with yield statements in them), the end of the function or a return statement will properly trigger the StopIteration for you. |
How do I change permissions to a socket? | 2,322,349 | 5 | 2010-02-23T22:48:09Z | 2,322,376 | 10 | 2010-02-23T22:51:18Z | [
"python",
"sockets",
"ubuntu",
"webserver",
"firewall"
] | I am trying to run a simple Python based web server given [here](http://fragments.turtlemeat.com/pythonwebserver.php).
And I get the following error message:
```
Traceback (most recent call last):
File "webserver.py", line 63, in <module>
main()
File "webserver.py", line 55, in main
server = HTTPServer(('... | If you want to bind to port numbers < 1024, you need to be root. It's not a firewall
issue; it's enforced by the operating system. Here's [a reference from w3.org](http://www.w3.org/Daemon/User/Installation/PrivilegedPorts.html),
and a [FAQ entry](http://unixguide.net/network/socketfaq/4.8.shtml) specific to Unix. |
SqlAlchemy optimizations for read-only object models | 2,322,437 | 7 | 2010-02-23T23:01:10Z | 2,323,267 | 7 | 2010-02-24T02:27:53Z | [
"python",
"performance",
"sqlalchemy",
"readonly"
] | I have a complex network of objects being spawned from a sqlite database using sqlalchemy ORM mappings. I have quite a few deeply nested:
```
for parent in owner.collection:
for child in parent.collection:
for foo in child.collection:
do lots of calcs with foo.property
```
My profiling is s... | If you reference a single attribute of a single instance lots of times, a simple trick is to store it in a local variable.
If you want a way to create cheap pure python clones, share the dict object with the original object:
```
class CheapClone(object):
def __init__(self, original):
self.__dict__ = origi... |
Index and Slice a Generator in Python | 2,322,642 | 26 | 2010-02-23T23:44:34Z | 2,322,711 | 30 | 2010-02-23T23:58:23Z | [
"python",
"generator"
] | Lets say I have a generator function that looks like this:
```
def fib():
x,y = 1,1
while True:
x, y = y, x+y
yield x
```
Ideally, I could just use *fib()[10]* or *fib()[2:12:2]* to get indexes and slices, but currently I have to use itertools for these things. I can't use a generator for a dr... | ```
import itertools
class Indexable(object):
def __init__(self,it):
self.it = iter(it)
def __iter__(self):
return self.it
def __getitem__(self,index):
try:
return next(itertools.islice(self.it,index,index+1))
except TypeError:
return list(itertools.i... |
How can I disable the webbrowser message in python? | 2,323,080 | 9 | 2010-02-24T01:40:29Z | 2,323,563 | 10 | 2010-02-24T03:53:04Z | [
"python",
"browser"
] | In my python program, when I send the user to create a gmail account by use of the webbrowser module, python displays:
"Please enter your Gmail username: Created new window in existing browser session."
Is there any way to get rid of "created new window in existing browser session", as it takes up the space where the... | As S.Lott hints in a comment, you should probably do the `raw_input` first; however, that, per se, doesn't suppress the message from `webbrowser`, as you ask -- it just postpones it.
To actually *suppress* the message, you can temporarily redirect standard-output or standard-error -- whichever of the two your chosen b... |
Convert string in base64 to image and save on filesystem in Python | 2,323,128 | 34 | 2010-02-24T01:52:32Z | 2,323,212 | 7 | 2010-02-24T02:11:23Z | [
"python",
"image"
] | I have a string in base64 format, which represents PNG image. Is there a way to save this image to the filesystem, as a PNG file?
---
I encoded the image using flex. Actually this is what I get on server
(can't see any image after any of proposed methods :( )
```
iVBORw0KGgoAAAANSUhEUgAABoIAAAaCCAYAAAABZu+EAAAqOElEQ... | If the imagestr was bitmap data (which we now know it isn't) you could use this
`imagestr` is the base64 encoded string
`width` is the width of the image
`height` is the height of the image
```
from PIL import Image
from base64 import decodestring
image = Image.fromstring('RGB',(width,height),decodestring(images... |
Convert string in base64 to image and save on filesystem in Python | 2,323,128 | 34 | 2010-02-24T01:52:32Z | 2,324,133 | 84 | 2010-02-24T06:34:47Z | [
"python",
"image"
] | I have a string in base64 format, which represents PNG image. Is there a way to save this image to the filesystem, as a PNG file?
---
I encoded the image using flex. Actually this is what I get on server
(can't see any image after any of proposed methods :( )
```
iVBORw0KGgoAAAANSUhEUgAABoIAAAaCCAYAAAABZu+EAAAqOElEQ... | Starting with
```
imgData = b'iVBORw0KGgoAAAANSUhEUgAABoIAAAaCCAYAAAABZu+EAAAqOElEQVR42uzBAQEAAACAkP6v7ggK\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.