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
Convert snmp octet string to human readable date format
4,571,899
8
2010-12-31T19:17:14Z
4,572,033
15
2010-12-31T19:50:53Z
[ "python", "decode", "snmp", "pysnmp" ]
Using the pysnmp framework i get some values doing a snmp walk. Unfortunately for the oid > 1.3.6.1.21.69.1.5.8.1.2 (DOCS-CABLE-DEVICE-MIB) i get a weird result which i cant correctly print here since it contains ascii chars like `BEL` `ACK` When doing a repr i get: > OctetString('\x07\xd8\t\x17\x03\x184\x00') But...
The format is [here](http://net-snmp.sourceforge.net/docs/mibs/host.html#DateAndTime). ``` A date-time specification. field octets contents range ----- ------ -------- ----- 1 1-2 year* 0..65536 2 ...
Is there someway I can get specific details about an AttributeError exception in Python?
4,572,362
4
2010-12-31T21:22:35Z
4,572,378
12
2010-12-31T21:26:14Z
[ "python", "exception", "attributes", "error-handling" ]
I'm trying to call a function. One of the parameters is a variable with attributes (which I know because of the AttributeError exception I got). I don't know the exact attributes this variable is supposed to have, so I was wondering if there was some way I can see some extra details about the exception, for example, wh...
`AttributeError` typically identifies the missing attribute. e.g.: ``` class Foo: def __init__(self): self.a = 1 f = Foo() print(f.a) print(f.b) ``` When I run that, I see: ``` $ python foo.py 1 Traceback (most recent call last): File "foo.py", line 10, in <module> print(f.b) AttributeError: Foo i...
Django: How to check if the user left all fields blank (or to initial values)?
4,572,859
13
2011-01-01T00:58:48Z
4,574,902
19
2011-01-01T17:27:26Z
[ "python", "django", "django-forms" ]
I know `is_valid()` on a bounded form checks if all required data is entered. This is not what I want. I want to check if *any* field was filled on the form. Any ideas? **Elaborating:** I want to give the user the choice of not filling in the form at all. However, if they attempt to fill it in (ie: changed a value i...
Guess I have to answer my own question. Apparently, there's an undocumented `Form` function: `has_changed()` ``` >>> f = MyForm({}) >>> f.has_changed() False >>> f = MyForm({}) >>> f.has_changed() False >>> f = MyForm({'name': 'test'}) >>> f.has_changed() True >>> f = MyForm({'name': 'test'}, initial={'name': 'test'}...
How to extract xml attribute using Python ElementTree
4,573,237
10
2011-01-01T05:16:21Z
4,573,304
17
2011-01-01T05:56:58Z
[ "python", "xml", "xpath", "elementtree" ]
For: ``` <foo> <bar key="value">text</bar> </foo> ``` How do I get "value"? ``` xml.findtext("./bar[@key]") ``` Throws an error.
``` In [52]: import xml.etree.ElementTree as ET In [53]: xml=ET.fromstring(contents) In [54]: xml.find('./bar').attrib['key'] Out[54]: 'value' ```
Pitfalls in R for Python programmers
4,574,002
11
2011-01-01T12:11:47Z
4,574,122
13
2011-01-01T13:00:12Z
[ "python" ]
I have mostly programmed in Python, but I am now learning the statistical programming language R. I have noticed some difference between the languages that tend to trip me. Suppose `v` is a vector/array with the integers from 1 to 5 inclusive. ``` v[3] # in R: gives me the 3rd element of the vector: 3 # in Pyt...
This isn't specifically addressing the Python vs. R background, but the [R inferno](http://www.burns-stat.com/pages/Tutor/R_inferno.pdf) is a great resource for programmers coming to R.
Pitfalls in R for Python programmers
4,574,002
11
2011-01-01T12:11:47Z
4,574,180
13
2011-01-01T13:26:06Z
[ "python" ]
I have mostly programmed in Python, but I am now learning the statistical programming language R. I have noticed some difference between the languages that tend to trip me. Suppose `v` is a vector/array with the integers from 1 to 5 inclusive. ``` v[3] # in R: gives me the 3rd element of the vector: 3 # in Pyt...
Having written tens of thousands of lines of code in both languages, R is just a lot more idiosyncratic and less consistent than Python. It's really nice for doing quick plots and investigation on a small to medium size dataset, mainly because its built-in dataframe object is nicer than the numpy/scipy equivalent, but ...
Python Remove Duplicate Chars using Regex
4,574,509
7
2011-01-01T15:26:22Z
4,574,516
30
2011-01-01T15:28:27Z
[ "python", "regex", "string" ]
Let's say I want to remove all duplicate chars (of a particular char) in a string using regular expressions. This is simple - ``` import re re.sub("a*", "a", "aaaa") # gives 'a' ``` What if I want to replace all duplicate chars (i.e. a,z) with that respective char? How do I do this? ``` import re re.sub('[a-z]*', <w...
``` >>> import re >>> re.sub(r'([a-z])\1+', r'\1', 'ffffffbbbbbbbqqq') 'fbq' ``` The `()` around the `[a-z]` specify a *capture group*, and then the `\1` (a *backreference*) in both the pattern and the replacement refer to the contents of the first capture group. Thus, the regex reads "find a letter, followed by one ...
Executing "SELECT ... WHERE ... IN ..." using MySQLdb
4,574,609
39
2011-01-01T16:04:57Z
4,574,647
50
2011-01-01T16:13:07Z
[ "python", "mysql" ]
I'm having a problem executing some SQL from within Python, despite similar SQL working fine from the `mysql` command-line. The table looks like this: ``` mysql> SELECT * FROM foo; +-------+-----+ | fooid | bar | +-------+-----+ | 1 | A | | 2 | B | | 3 | C | | 4 | D | +-------+-----+ 4 row...
Unfortunately, you need to manually construct the query parameters, because as far as I know, there is no built-in `bind` method for binding a `list` to an `IN` clause, similar to Hibernate's `setParameterList()`. However, you can accomplish the same with the following: Python 3: ``` args=['A', 'C'] sql='SELECT fooid...
Executing "SELECT ... WHERE ... IN ..." using MySQLdb
4,574,609
39
2011-01-01T16:04:57Z
10,410,791
20
2012-05-02T09:12:31Z
[ "python", "mysql" ]
I'm having a problem executing some SQL from within Python, despite similar SQL working fine from the `mysql` command-line. The table looks like this: ``` mysql> SELECT * FROM foo; +-------+-----+ | fooid | bar | +-------+-----+ | 1 | A | | 2 | B | | 3 | C | | 4 | D | +-------+-----+ 4 row...
Here is a [similar solution](http://stackoverflow.com/a/589416/391347 "similar solution") which I think is more efficient in building up the list of %s strings in the SQL: > Use the `list_of_ids` directly: > > ``` > format_strings = ','.join(['%s'] * len(list_of_ids)) > cursor.execute("DELETE FROM foo.bar WHERE baz IN...
In Python, can I specify a function argument's default in terms of other arguments?
4,575,326
9
2011-01-01T19:16:10Z
4,575,371
12
2011-01-01T19:26:03Z
[ "python", "function", "default-value", "arguments" ]
Suppose I have a python function that takes two arguments, but I want the second arg to be optional, with the default being whatever was passed as the first argument. So, I want to do something like this: ``` def myfunc(arg1, arg2=arg1): print (arg1, arg2) ``` Except that doesn't work. The only workaround I can t...
As @Ignacio says, you can't do this. In your latter example, you might have a situation where `None` is a valid value for `arg2`. If this is the case, you can use a sentinel value: ``` sentinel = object() def myfunc(arg1, arg2=sentinel): if arg2 is sentinel: arg2 = arg1 print (arg1, arg2) myfunc("foo"...
Different standard deviation for same input from Wolfram and numpy
4,575,645
11
2011-01-01T20:30:46Z
4,575,675
23
2011-01-01T20:39:47Z
[ "java", "python", "statistics" ]
I am currently working on reimplementing some algorithm written in Java in Python. One step is to calculate the standard deviation of a list of values. The original implementation uses [`DescriptiveStatistics.getStandardDeviation`](http://commons.apache.org/math/api-1.1/org/apache/commons/math/stat/descriptive/Descript...
Apache and Wolfram divide by N-1 rather than N. This is a degrees of freedom adjustment, since you estimate μ. By dividing by N-1 you obtain an unbiased estimate of the population standard deviation. You can change NumPy's behavior using the `ddof` option. This is described in the NumPy documentation: > The average ...
Python list comprehension overriding value
4,575,698
17
2011-01-01T20:45:49Z
4,575,707
28
2011-01-01T20:48:08Z
[ "python", "closures", "list-comprehension" ]
have a look at the following piece of code, which shows a list comprehension.. ``` >>> i = 6 >>> s = [i * i for i in range(100)] >>> print(i) ``` When you execute the code example in *Python 2.6* it prints **99**, but when you execute it in **Python 3.x** it prints **6**. What were the reason for changing the behavi...
The old behaviour was a mistake but couldn't easily be fixed as some code relied on it. The variable `i` inside the list comprehension should be a different `i` from the one at the top level. Logically it should have its own scope which does not extend outside the comprehension as its value only makes sense inside the...
Python list comprehension overriding value
4,575,698
17
2011-01-01T20:45:49Z
4,575,708
7
2011-01-01T20:48:30Z
[ "python", "closures", "list-comprehension" ]
have a look at the following piece of code, which shows a list comprehension.. ``` >>> i = 6 >>> s = [i * i for i in range(100)] >>> print(i) ``` When you execute the code example in *Python 2.6* it prints **99**, but when you execute it in **Python 3.x** it prints **6**. What were the reason for changing the behavi...
Yes, there is a reason, and the reason is that they didn't want the temporary variable in a list comprehension to leak into the outer namespace. So it is an intentional change that is a result of list comprehensions now being syntactic sugar for passing a generator expression to list(). Ref: [PEP3100](http://www.pytho...
Get selected subcommand with argparse
4,575,747
53
2011-01-01T20:59:17Z
4,575,792
89
2011-01-01T21:10:50Z
[ "python", "command-line", "argparse" ]
When I use subcommands with python argparse, I can get the selected arguments. ``` parser = argparse.ArgumentParser() parser.add_argument('-g', '--global') subparsers = parser.add_subparsers() foo_parser = subparsers.add_parser('foo') foo_parser.add_argument('-c', '--count') bar_parser = subparsers.add_parser('bar'...
The very bottom of the [Python docs on argparse sub-commands](http://docs.python.org/dev/library/argparse.html#sub-commands) explains how to do this: ``` >>> parser = argparse.ArgumentParser() >>> parser.add_argument('-g', '--global') >>> subparsers = parser.add_subparsers(dest="subparser_name") # this line changed >>...
Python split text on sentences
4,576,077
37
2011-01-01T22:18:59Z
4,576,110
74
2011-01-01T22:27:43Z
[ "python", "text", "split" ]
I have a text file. I need get a list of sentences. How can this be implemented? There are a lot of subtleties, such as dot being used in abbreviations. My old regexp works bad. ``` re.compile('(\. |^|!|\?)([A-Z][^;↑\.<>@\^&/\[\]]*(\.|!|\?) )',re.M) ```
The Natural Language Toolkit (http://www.nltk.org/) has what you need. [This group posting](http://mailman.uib.no/public/corpora/2007-October/005426.html) indicates this does it: ``` import nltk.data tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') fp = open("test.txt") data = fp.read() print '\n-----\n'...
Python split text on sentences
4,576,077
37
2011-01-01T22:18:59Z
31,505,798
9
2015-07-19T20:50:33Z
[ "python", "text", "split" ]
I have a text file. I need get a list of sentences. How can this be implemented? There are a lot of subtleties, such as dot being used in abbreviations. My old regexp works bad. ``` re.compile('(\. |^|!|\?)([A-Z][^;↑\.<>@\^&/\[\]]*(\.|!|\?) )',re.M) ```
This function can split the entire text of Huckleberry Finn into sentences in about 0.1 seconds and handles many of the more painful edge cases that make sentence parsing non-trivial e.g. "*Mr. John Johnson Jr. was born in the U.S.A but earned his Ph.D. in Israel before joining Nike Inc. as an engineer. He also worked ...
Convert a list to a dictionary in Python
4,576,115
78
2011-01-01T22:29:00Z
4,576,128
138
2011-01-01T22:32:19Z
[ "python", "list", "dictionary" ]
Let's say I have a list `a` in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following odd element is the value for example, ``` a = ['hello','world','1','2'] ``` and I'd like to convert it to a dictionary `b`, where ``` b['hello'] = 'world' b...
``` b = dict(zip(a[0::2], a[1::2])) ``` If `a` is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above. ``` from itertools import izip i = iter(a) b = dict(izip(i, i)) ``` In Python 3 you could also use a dict comprehension, but ironically I think th...
Convert a list to a dictionary in Python
4,576,115
78
2011-01-01T22:29:00Z
13,096,454
21
2012-10-27T01:31:16Z
[ "python", "list", "dictionary" ]
Let's say I have a list `a` in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following odd element is the value for example, ``` a = ['hello','world','1','2'] ``` and I'd like to convert it to a dictionary `b`, where ``` b['hello'] = 'world' b...
Another option (courtesy of Alex Martelli <http://stackoverflow.com/a/2597178/104264>): ``` dict(x[i:i+2] for i in range(0, len(x), 2)) ``` Also if you have this: ``` a = ['bi','double','duo','two'] ``` and you want this (each element of the list keying a given value (2 in this case)): ``` {'bi':2,'double':2,'duo'...
Convert a list to a dictionary in Python
4,576,115
78
2011-01-01T22:29:00Z
21,171,892
7
2014-01-16T20:12:53Z
[ "python", "list", "dictionary" ]
Let's say I have a list `a` in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following odd element is the value for example, ``` a = ['hello','world','1','2'] ``` and I'd like to convert it to a dictionary `b`, where ``` b['hello'] = 'world' b...
You can use a dict comprehension for this pretty easily: ``` a = ['hello','world','1','2'] my_dict = {item : a[index+1] for index, item in enumerate(a) if index % 2 == 0} ``` This is equivalent to the for loop below: ``` my_dict = {} for index, item in enumerate(a): if index % 2 == 0: my_dict[item] = a[...
In Django, can you add a method to querysets?
4,576,622
17
2011-01-02T01:10:48Z
7,961,021
13
2011-10-31T23:40:28Z
[ "python", "django", "django-queryset" ]
In Django, if I have a model class, e.g. ``` from django.db import models class Transaction(models.Model): ... ``` then if I want to add methods to the model, to store e.g. reasonably complex filters, I can add a custom model manager, e.g. ``` class TransactionManager(models.Manager): def reasonably_comple...
This is a complete solution that is known to work in Django 1.3, courtesy of [Zach Smith](http://zmsmith.com/2010/04/using-custom-django-querysets/) and Ben. ``` class Entry(models.Model): objects = EntryManager() # don't forget this is_public = models.BooleanField() owner = models.ForeignKey(User) clas...
In Django, can you add a method to querysets?
4,576,622
17
2011-01-02T01:10:48Z
26,646,544
18
2014-10-30T06:36:53Z
[ "python", "django", "django-queryset" ]
In Django, if I have a model class, e.g. ``` from django.db import models class Transaction(models.Model): ... ``` then if I want to add methods to the model, to store e.g. reasonably complex filters, I can add a custom model manager, e.g. ``` class TransactionManager(models.Manager): def reasonably_comple...
As of django 1.7, the ability [to use a query set as a manager](https://docs.djangoproject.com/en/1.7/topics/db/managers/#creating-manager-with-queryset-methods) was added: ``` class PersonQuerySet(models.QuerySet): def authors(self): return self.filter(role='A') def editors(self): return self...
geodjango using mysql
4,578,352
14
2011-01-02T12:25:59Z
4,693,332
30
2011-01-14T16:29:01Z
[ "python", "django", "geodjango" ]
I have been working on an application using django and mysql, am trying now to work on the tutorial from this here <http://docs.djangoproject.com/en/1.2/ref/contrib/gis/tutorial/> but it failed the moment I ran syncdb with the following error ``` AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_t...
set `django.contrib.gis.db.backends.mysql` in your settings.DATABASE engine db config.
python equivalent of filter() getting two output lists (i.e. partition of a list)
4,578,590
31
2011-01-02T13:34:11Z
4,578,605
33
2011-01-02T13:37:49Z
[ "python", "filter", "data-partitioning" ]
Let's say I have a list, and a filtering function. Using something like ``` >>> filter(lambda x: x > 10, [1,4,12,7,42]) [12, 42] ``` I can get the elements matching the criterion. Is there a function I could use that would output two lists, one of elements matching, one of the remaining elements? I could call the `fi...
Try this: ``` def partition(pred, iterable): trues = [] falses = [] for item in iterable: if pred(item): trues.append(item) else: falses.append(item) return trues, falses ``` Usage: ``` >>> trues, falses = partition(lambda x: x > 10, [1,4,12,7,42]) >>> trues [1...
python equivalent of filter() getting two output lists (i.e. partition of a list)
4,578,590
31
2011-01-02T13:34:11Z
4,579,086
11
2011-01-02T15:39:03Z
[ "python", "filter", "data-partitioning" ]
Let's say I have a list, and a filtering function. Using something like ``` >>> filter(lambda x: x > 10, [1,4,12,7,42]) [12, 42] ``` I can get the elements matching the criterion. Is there a function I could use that would output two lists, one of elements matching, one of the remaining elements? I could call the `fi...
``` >>> def partition(l, p): ... return reduce(lambda x, y: (x[0]+[y], x[1]) if p(y) else (x[0], x[1]+[y]), l, ([], [])) ... >>> partition([1, 2, 3, 4, 5], lambda x: x < 3) ([1, 2], [3, 4, 5]) ``` and a little uglier but faster version of the above code: ``` def partition(l, p): return reduce(lambda x, y: x...
Having a problem installing zeormq for python
4,578,672
4
2011-01-02T13:59:14Z
4,578,772
12
2011-01-02T14:24:12Z
[ "python", "zeromq" ]
I'm a beginner on unix so I'm sorry if I post something easy. Also I have to admit that I do not master all the process. I need to install zeromq on my ubuntu. I have python 2.6.6 installed I followed the instructions on the website for UNIX systems : <http://www.zeromq.org/intro:get-the-software> and after <http://...
All the error you gave us is saying that gcc failed. Most likely gcc also gave you a *long* error message telling you *why* it failed. That is more helpful. If I'm going to guess, some sort of development headers is missing. Probably the Python development headers, which you can install with ``` sudo apt-get install ...
Connecting slots and signals in PyQt4 in a loop
4,578,861
5
2011-01-02T14:47:47Z
4,578,943
10
2011-01-02T15:07:52Z
[ "python", "pyqt4", "signals-slots" ]
Im trying to build a calculator with PyQt4 and connecting the 'clicked()' signals from the buttons doesn't as expected. Im creating my buttons for the numbers inside a for loop where i try to connect them afterwards. ``` def __init__(self): for i in range(0,10): self._numberButtons += [QPushButton(str(...
This is just, how scoping, name lookup and closures are defined in Python. Python only introduces new bindings in namespace through assignment and through parameter lists of functions. `i` is therefore not actually defined in the namespace of the `lambda`, but in the namespace of `__init__()`. The name lookup for `i` ...
Replace all accented characters by their LaTeX equivalent
4,578,912
12
2011-01-02T14:59:21Z
4,579,006
9
2011-01-02T15:22:32Z
[ "python", "unicode", "latex", "diacritics" ]
Given a Unicode string, I want to replace non-ASCII characters by LaTeX code producing them (for example, having `é` become `\'e`, and `œ` become `\oe`). I'm incorporating this into a Python code. This should rely on a translation table, and I have come up with the following code, which is simple and seems to work ni...
If you are not in control of LaTeX compilation options, you can use the same table used by the inputenc package, so that the behavior will be the same as if you had used inputenc. [This document](http://www.tug.org/texmf-dist/doc/latex/base/utf8ienc.pdf) explains how inputenc does the mapping, it is a sequence of ```...
Replace all accented characters by their LaTeX equivalent
4,578,912
12
2011-01-02T14:59:21Z
4,580,132
8
2011-01-02T19:41:40Z
[ "python", "unicode", "latex", "diacritics" ]
Given a Unicode string, I want to replace non-ASCII characters by LaTeX code producing them (for example, having `é` become `\'e`, and `œ` become `\oe`). I'm incorporating this into a Python code. This should rely on a translation table, and I have come up with the following code, which is simple and seems to work ni...
OK, so here's the table I've built up for now. Please feel free to edit to add to it! (or comment if you don't have enough reputation to edit) ``` ################################################################ # LaTeX accents replacement latexAccents = [ [ u"à", "\\`a" ], # Grave accent [ u"è", "\\`e" ], [ u...
cross-platform splitting of path in python
4,579,908
15
2011-01-02T18:52:33Z
4,579,972
16
2011-01-02T19:06:48Z
[ "python" ]
I'd like something that has the same effect as this: ``` >>> path = "/foo/bar/baz/file" >>> path_split = path.rsplit('/')[1:] >>> path_split ['foo', 'bar', 'baz', 'file'] ``` But that will work with Windows paths too. I know that there is an `os.path.split()` but that doesn't do what I want, and I didn't see anything...
Someone said "use `os.path.split`". This got deleted unfortunately, but it is the right answer. > os.path.split(path) > > Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a sl...
cross-platform splitting of path in python
4,579,908
15
2011-01-02T18:52:33Z
4,580,931
19
2011-01-02T22:46:13Z
[ "python" ]
I'd like something that has the same effect as this: ``` >>> path = "/foo/bar/baz/file" >>> path_split = path.rsplit('/')[1:] >>> path_split ['foo', 'bar', 'baz', 'file'] ``` But that will work with Windows paths too. I know that there is an `os.path.split()` but that doesn't do what I want, and I didn't see anything...
The OP specified "will work with Windows paths too". There are a few wrinkles with Windows paths. Firstly, Windows has the concept of multiple drives, each with its own current working directory, and `'c:foo'` and `'c:\\foo'` are often not the same. Consequently it is a very good idea to separate out any drive designa...
cross-platform splitting of path in python
4,579,908
15
2011-01-02T18:52:33Z
31,273,488
7
2015-07-07T15:50:40Z
[ "python" ]
I'd like something that has the same effect as this: ``` >>> path = "/foo/bar/baz/file" >>> path_split = path.rsplit('/')[1:] >>> path_split ['foo', 'bar', 'baz', 'file'] ``` But that will work with Windows paths too. I know that there is an `os.path.split()` but that doesn't do what I want, and I didn't see anything...
Python 3.4 introduced a new module [`pathlib`](https://docs.python.org/3/library/pathlib.html#module-pathlib). [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#concrete-paths) provides file system related methods, while [`pathlib.PurePath`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath)...
Python - add PYTHONPATH during command line module run
4,580,101
41
2011-01-02T19:33:20Z
4,580,120
72
2011-01-02T19:38:46Z
[ "python", "pythonpath" ]
I want to run: ``` python somescript.py somecommand ``` But, when I run this I need `PYTHONPATH` to include a certain directory. I can't just add it to my environment variables because the directory I want to add changes based on what project I'm running. Is there a way to alter `PYTHONPATH` while running a script? N...
For Mac/Linux; ``` PYTHONPATH=/foo/bar/baz python somescript.py somecommand ``` For Windows, setup a wrapper `pythonpath.bat`; ``` @ECHO OFF setlocal set PYTHONPATH=%1 python %2 %3 endlocal ``` and call `pythonpath.bat` script file like; ``` pythonpath.bat /foo/bar/baz somescript.py somecommand ```
Python - add PYTHONPATH during command line module run
4,580,101
41
2011-01-02T19:33:20Z
4,580,130
31
2011-01-02T19:41:25Z
[ "python", "pythonpath" ]
I want to run: ``` python somescript.py somecommand ``` But, when I run this I need `PYTHONPATH` to include a certain directory. I can't just add it to my environment variables because the directory I want to add changes based on what project I'm running. Is there a way to alter `PYTHONPATH` while running a script? N...
``` import sys sys.path.append('your certain directory') ``` Basically sys.path is a list with all the search paths for python modules. It is initialized by the interpreter. The content of PYTHONPATH is automatically added to the end of that list.
create missing directories in path
4,580,641
4
2011-01-02T21:35:07Z
4,580,663
7
2011-01-02T21:38:56Z
[ "python" ]
Is there a clean way of taking a path like this: ``` /foo/bar/faz/baz/ ``` where `foo` and `bar` exist, but `faz` and `baz` don't, and create create `faz` and `baz` while leaving `foo` and `bar` alone? (Of course, this should work for something like `exists/exists/exists/doesnt_exist/doesnt_exit/doesnt_exist/doesnt_e...
[`os.makedirs`](http://docs.python.org/library/os.html#os.makedirs) does exactly that.
How to set opacity of background colour of graph wit Matplotlib
4,581,504
34
2011-01-03T01:26:23Z
4,708,018
59
2011-01-16T21:01:42Z
[ "python", "matplotlib", "alpha" ]
I've been playing around with Matplotlib and I can't figure out how to change the background colour of the graph, or how to make the background completely transparent.
If you just want the entire background for both the figure and the axes to be transparent, you can simply specify `transparent=True` when saving the figure with `fig.savefig`. e.g.: ``` import matplotlib.pyplot as plt fig = plt.figure() plt.plot(range(10)) fig.savefig('temp.png', transparent=True) ``` If you want mo...
How to count all elements in a nested dictionary?
4,581,646
10
2011-01-03T02:13:45Z
4,581,706
11
2011-01-03T02:30:08Z
[ "python" ]
How do I count the number of subelements in a nested dictionary in the most efficient manner possible? The len() function doesn't work as I initially expected it to: ``` >>> food_colors = {'fruit': {'orange': 'orange', 'apple': 'red', 'banana': 'yellow'}, 'vegetables': {'lettuce': 'green', 'beet': 'red', 'pumpkin': 'o...
Is it guaranteed that each top-level key has a dictionary as its value, and that no second-level key has a dictionary? If so, this will go as fast as you can hope for: ``` sum(len(v) for v in food_colors.itervalues()) ``` If the data structure is more complicated, it will need more code, of course. I'm not aware of a...
Using pyhook to respond to key combination (not just single keystrokes)?
4,581,772
7
2011-01-03T02:49:31Z
9,122,473
7
2012-02-03T01:16:25Z
[ "python", "windows", "automation", "keyboard", "keyboard-shortcuts" ]
I've been looking around but I can't find an example of how to use pyhook to respond to key **combinations** such as `Ctrl` + `C` whereas it is easy to find examples of how to respond to single keypresses such as `Ctrl` or `C` separately. BTW, I'm talking about Python 2.6 on Windows XP. Any help appreciated.
Actually Ctrl+C have it's own Ascii code (which is 3). Something like this works for me: ``` import pyHook,pythoncom def OnKeyboardEvent(event): if event.Ascii == 3: print "Hello, you've just pressed ctrl+c!" ```
How do I get user IP address in django?
4,581,789
157
2011-01-03T02:55:05Z
4,581,997
222
2011-01-03T04:08:07Z
[ "python", "django" ]
How do I get user's IP in django? I have a view like this: ``` # Create your views from django.contrib.gis.utils import GeoIP from django.template import RequestContext from django.shortcuts import render_to_response def home(request): g = GeoIP() client_ip = request.META['REMOTE_ADDR'] lat,long = g.lat_lon(...
``` def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip ``` Make sure you have reverse proxy (if any) configured correctly (e.g. `mod_rpaf` inst...
How do I get user IP address in django?
4,581,789
157
2011-01-03T02:55:05Z
5,976,065
57
2011-05-12T09:38:47Z
[ "python", "django" ]
How do I get user's IP in django? I have a view like this: ``` # Create your views from django.contrib.gis.utils import GeoIP from django.template import RequestContext from django.shortcuts import render_to_response def home(request): g = GeoIP() client_ip = request.META['REMOTE_ADDR'] lat,long = g.lat_lon(...
Alexander's answer is great, but lacks the handling of proxies that sometimes return multiple IP's in the HTTP\_X\_FORWARDED\_FOR header. The real IP is usually at the end of the list, as explained here: <http://en.wikipedia.org/wiki/X-Forwarded-For> The solution is a simple modification of Alexander's code: ``` def...
How do I get user IP address in django?
4,581,789
157
2011-01-03T02:55:05Z
14,808,613
8
2013-02-11T08:47:26Z
[ "python", "django" ]
How do I get user's IP in django? I have a view like this: ``` # Create your views from django.contrib.gis.utils import GeoIP from django.template import RequestContext from django.shortcuts import render_to_response def home(request): g = GeoIP() client_ip = request.META['REMOTE_ADDR'] lat,long = g.lat_lon(...
I would like to suggest an improvement to yanchenko's answer. Instead of taking the first ip in the X\_FORWARDED\_FOR list, I take the first one which in not a known internal ip, as some routers don't respect the protocol, and you can see internal ips as the first value of the list. ``` PRIVATE_IPS_PREFIX = ('10.', '...
How do I get user IP address in django?
4,581,789
157
2011-01-03T02:55:05Z
16,203,978
105
2013-04-24T23:31:04Z
[ "python", "django" ]
How do I get user's IP in django? I have a view like this: ``` # Create your views from django.contrib.gis.utils import GeoIP from django.template import RequestContext from django.shortcuts import render_to_response def home(request): g = GeoIP() client_ip = request.META['REMOTE_ADDR'] lat,long = g.lat_lon(...
You can stay **DRY** and just use **[django-ipware](https://github.com/un33k/django-ipware)** that supports both **IPv4** and **IPv6** as well as Python **3**. **Install:** ``` pip install django-ipware ``` **In your view or middleware:** ``` from ipware.ip import get_ip ip = get_ip(request) if ip is not None: ...
Python integer ranges
4,581,842
56
2011-01-03T03:13:35Z
4,581,847
101
2011-01-03T03:14:51Z
[ "python", "integer" ]
In Python, is there a way to get the largest integer one can use? Is there some pre-defined constant like INT\_MAX?
Python has arbitrary precision integers so there is no true fixed maximum. You're only limited by available memory. In Python 2, there are two types, `int` and `long`. `int`s use a C type, while `long`s are arbitrary precision. You can use `sys.maxint` to find the maximum `int`. But `int`s are automatically promoted t...
Python SqlAlchemy order_by DateTime?
4,582,264
10
2011-01-03T05:35:13Z
4,582,641
31
2011-01-03T07:07:55Z
[ "python", "sqlalchemy" ]
I'm using SqlAlchemy to store some objects with a DateTime field: ``` my_date = Field(DateTime()) ``` I'd like to run a query to retrieve the most recent few objects (Entities with the my\_date field that are the most recent). I've tried the following: ``` entities = MyEntity.query.order_by(MyEntity.time).limit(3)....
You can do it like this: ``` entities = MyEntity.query.order_by(desc(MyEntity.time)).limit(3).all() ``` You might need to: ``` from sqlalchemy import desc ``` Here's [some documentation](http://docs.sqlalchemy.org/en/rel_0_7/core/expression_api.html#sqlalchemy.sql.expression.desc).
Is there a Django template filter that turns a datetime into "5 hours ago" or "12 days ago"?
4,582,507
2
2011-01-03T06:34:51Z
4,582,617
11
2011-01-03T07:01:47Z
[ "python", "css", "django", "templates", "filter" ]
Let's say I have a datetime. I do this: ``` Submitted on {{ post.date|date:"D. M d, P" }} ``` This actually prints the date. However, what if I want it to say, "4 hours ago" or "55 days ago" or "2 months ago"?
Try the template filter [`timesince`](http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#timesince). Use it like this: ``` {{ mytemplatevar|timesince }} ```
Python : creating dynamic functions
4,582,521
6
2011-01-03T06:38:38Z
4,582,594
23
2011-01-03T06:56:56Z
[ "python" ]
I have issue where i want to create Dynamic function which will do some calculation based to values retrieved from database, i am clear with my internal calculation but question in how to create dynamic class: My Structure is something like this : ``` class xyz: def Project(): start = 2011-01-03 ...
With [**closures**](http://en.wikipedia.org/wiki/Closure_%28computer_programming%29). ``` def makefunc(val): def somephase(): return '%dd' % (val,) return somephase Phase2 = makefunc(2) Phase3 = makefunc(3) ``` [caveats](http://code.activestate.com/recipes/502271/)
file walking in python
4,582,550
5
2011-01-03T06:46:58Z
4,582,729
13
2011-01-03T07:32:28Z
[ "python" ]
So, I've got a working solution, but it's ugly and seems un-idiomatic. The problem is this: For a directory tree, where every directory is set up to have: * 1 `.xc` file * at least 1 `.x` file * any number of directories which follow the same format and nothing else. I'd like to, given the root path and walk the tre...
The function [`os.walk`](http://docs.python.org/library/os.html) recursively walks through a directory tree, returning all file and subdirectory names. So all you have to do is detect the `.x` and `.xc` extensions from the filenames and apply your functions when they do (untested code follows): ``` import os for dir...
Simplejson dump and load not returning valid dictionary
4,582,636
2
2011-01-03T07:06:26Z
4,582,675
9
2011-01-03T07:16:51Z
[ "python", "json", "google-app-engine", "simplejson" ]
I'm trying to store a json result in the GAE datastore, so that I can read it later. I'm dumping it to a String, then storing it, then reading it and loading it back into a dict. But I can no longer read it as a dict after loading. ``` result = freebase.mqlready(query) ``` Print result: ``` [{u'mid': u'/m/095hd', ...
Uh, looks like you're accessing the collection rather than the inner object: Surely you meant: ``` for j in json: name = j['name'] ```
Python - urllib2 & cookielib
4,582,964
22
2011-01-03T08:15:48Z
4,583,415
7
2011-01-03T09:37:42Z
[ "python", "urllib2", "cookielib" ]
I am trying to open the following website and retrieve the initial cookie and use it for the second url-open BUT if you run the following code it outputs 2 different cookies. How do I use the initial cookie for the second url-open? ``` import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener...
Not an actual answer (but far too long for a comment); possibly useful to anyone else trying to answer this. Despite my best attempts, I can't figure this out. Looking in Firebug, the cookie seems to remain the same (works properly) for Firefox. I added `urllib2.HTTPSHandler(debuglevel=1)` to debug what headers Pyth...
Python - urllib2 & cookielib
4,582,964
22
2011-01-03T08:15:48Z
4,589,739
21
2011-01-04T00:48:27Z
[ "python", "urllib2", "cookielib" ]
I am trying to open the following website and retrieve the initial cookie and use it for the second url-open BUT if you run the following code it outputs 2 different cookies. How do I use the initial cookie for the second url-open? ``` import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener...
This is not a problem with urllib. That site does some funky stuff. You need to request a couple of stylesheets for it to validate your session id: ``` import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) # default User-Agent ('Python-urllib/2.6') will *n...
Cryptography tools for python 3
4,583,274
13
2011-01-03T09:15:37Z
8,373,619
15
2011-12-04T06:00:42Z
[ "python", "cryptography", "python-3.x", "pycrypto" ]
I'm writing a program in python 3 which needs encryption functions (at least aes and rsa). I've found [PyCrypto](http://www.dlitz.net/software/pycrypto/) which seems to work only on 2.x versions. Is there any good tool available for python 3 or should I rather start translating my program to be compatible with python ...
PyCrypto 2.4.1 and later now work on Python 3.x (see [changelog diff](https://github.com/dlitz/pycrypto/commit/32114297da2450af00c4612596bc15da4f6256f2#diff-1)).
How to run multiple python version on Windows
4,583,367
75
2011-01-03T09:30:33Z
4,584,180
60
2011-01-03T11:54:11Z
[ "python", "compatibility" ]
I had two versions of Python installed in my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another. How can I specify which I want to use? I am working on Windows XP SP2.
Running a different copy of Python is as easy as starting the correct executable. You mention that you've started a python instance, from the command line, by simply typing `python`. What this does under Windows, is to trawl the %PATH% environment variable, checking for an executable, either batch file (.bat), command...
How to run multiple python version on Windows
4,583,367
75
2011-01-03T09:30:33Z
13,211,456
31
2012-11-03T17:09:20Z
[ "python", "compatibility" ]
I had two versions of Python installed in my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another. How can I specify which I want to use? I am working on Windows XP SP2.
Adding two more solutions to the problem: * Install [pylauncher](https://bitbucket.org/vinay.sajip/pylauncher) and add shebang lines to your scripts; `#! c:\[path to Python 2.5]\python.exe` - for scripts you want to be run with Python 2.5 `#! c:\[path to Python 2.6]\python.exe` - for scripts you want to be run with...
How to run multiple python version on Windows
4,583,367
75
2011-01-03T09:30:33Z
13,953,614
25
2012-12-19T13:37:51Z
[ "python", "compatibility" ]
I had two versions of Python installed in my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another. How can I specify which I want to use? I am working on Windows XP SP2.
As per @alexander you can make a set of symbolic links like below. Put them somewhere which is included in your path so they can be easily invoked ``` > cd c:\bin > mklink python25.exe c:\python25\python.exe > mklink python26.exe c:\python26\python.exe ``` As long as c:\bin or where ever you placed them in is in your...
How to run multiple python version on Windows
4,583,367
75
2011-01-03T09:30:33Z
17,245,619
19
2013-06-21T23:15:20Z
[ "python", "compatibility" ]
I had two versions of Python installed in my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another. How can I specify which I want to use? I am working on Windows XP SP2.
From Python 3.3 on, there is the official *Python launcher for Windows* (<http://www.python.org/dev/peps/pep-0397/>). Now, you can use the `#!pythonX` to determine the wanted version of the interpreter also on Windows. See more details [in my another comment](http://stackoverflow.com/a/17245543/1346705) or read the PEP...
What is the best way to make a shallow copy of a Python dictionary?
4,583,501
7
2011-01-03T09:54:18Z
4,583,594
8
2011-01-03T10:10:01Z
[ "python" ]
Assume we have a simple Python dictionary: ``` dict_ = {'foo': 1, 'bar': 2} ``` Which is the better way to copy this dictionary? ``` copy1 = dict(dict_) copy2 = dict_.copy() ``` Is there a compelling reason to favour one approach over the other?
I always use the `dict` constructor: it makes it obvious that you are creating a new `dict` whereas calling the `copy` method on an object could be copying anything. Similarly for `list` I prefer calling the constructor over copying by slicing. Note that if you use subclasses of `dict` using the `copy` method can get ...
python: nonblocking subprocess, check stdout
4,585,692
4
2011-01-03T15:23:25Z
4,585,898
8
2011-01-03T15:50:08Z
[ "python", "subprocess", "stdout", "popen", "nonblocking" ]
Ok so the problem I'm trying to solve is this: I need to run a program with some flags set, check on its progress and report back to a server. So I need my script to avoid blocking while the program executes, but I also need to be able to read the output. Unfortunately, I don't think any of the methods available from ...
Basically you have 3 options: 1. Use `threading` to read in another thread without blocking the main thread. 2. [`select`](http://docs.python.org/library/select.html?highlight=select#module-select) on stdout, stderr instead of `communicate`. This way you can read just when data is available and avoid blocking. 3. Let ...
Splitting a string into an iterator
4,586,026
22
2011-01-03T16:04:54Z
4,586,073
14
2011-01-03T16:10:01Z
[ "python", "string", "iterator", "split" ]
Does python have a build-in (meaning in the standard libraries) to do a split on strings that produces an iterator rather than a list? I have in mind working on very long strings and not needing to consume most of the string.
Not directly splitting strings as such, but the `re` module has [`re.finditer()`](http://docs.python.org/2/library/re.html#re.finditer) (and corresponding `finditer()` method on any compiled regular expression). @Zero asked for an example: ``` >>> import re >>> s = "The quick brown\nfox" >>> for m in re.finditer('...
Windows XP , Python 2.7 and Pygame
4,587,018
3
2011-01-03T18:11:30Z
4,588,698
7
2011-01-03T21:52:48Z
[ "python", "windows-xp", "pygame", "python-2.7" ]
How can I make pygame work with Python 2.7 under Windows XP? I think I need to compile it, but I'm not sure. Thank you.
Try the pygame-1.9.2pre.win32-py2.7 installer from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame>
Return list of items in list greater than some value
4,587,915
21
2011-01-03T20:09:25Z
4,587,920
30
2011-01-03T20:10:19Z
[ "python" ]
I have the following list ``` j=[4,5,6,7,1,3,7,5] ``` What's the simplest way to return `[5,5,6,7,7]` being the elements in j greater or equal to 5?
You can use a list comprehension to filter it: ``` j2 = [i for i in j if i >= 5] ``` If you actually want it sorted like your example was, you can use `sorted`: ``` j2 = sorted(i for i in j if i >= 5) ``` or call `sort` on the final list: ``` j2 = [i for i in j if i >= 5] j2.sort() ```
Python objects confusion: a=b, modify b and a changes!
4,588,100
5
2011-01-03T20:31:12Z
4,588,110
10
2011-01-03T20:32:19Z
[ "python", "variables", "reference" ]
I thought i knew Python until tonight. What is the correct way to do something like this? Here's my code: ``` a = ["one", "two", "three"] b = a # here I want a complete copy that when b is changed, has absolutely no effect on a b.append["four"] print a # a now has "four" in it ``` Basically i want to know, instead ...
What you are experiencing is the concept of references. All objects in Python have a reference and when you assign one to two names `a` and `b`, this results in both `a` and `b` pointing to the *same* object. ``` >>> a = range(3) >>> b = a # same object >>> b.append(3) >>> a, b ...
Obfuscating Strings with ASCII and base 128
4,588,612
2
2011-01-03T21:37:52Z
4,588,637
7
2011-01-03T21:41:39Z
[ "python", "encoding", "obfuscation", "ascii" ]
Suppose a string is a number system where each thing, it can be a char, DEL or any ASCII thing, has a corresponding number according to this ASCII [table](http://web.eecs.utk.edu/~pham/ascii_table.jpg). How can you convert arbitrary string of the property to number in Python? **An example** ``` #car = 35*128**3+99*12...
Try this: ``` total = 0 for c in "#car": total <<= 7 total += ord(c) print total ``` Result: ``` 75034866 ``` To get back the original string: ``` result = [] while total: result.append(chr(total % 128)) total >>= 7 print ''.join(reversed(result)) ``` Result: ``` #car ```
Find indices of elements equal to zero from numpy array
4,588,628
51
2011-01-03T21:40:08Z
4,588,654
84
2011-01-03T21:44:00Z
[ "python", "numpy" ]
NumPy has the efficient function/method [`nonzero()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html) to identify the indices of non-zero elements in an `ndarray` object. What is the most efficient way to obtain the indices of the elements that *do* have a value of zero?
[numpy.where()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) is my favorite. ``` >>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8]) >>> numpy.where(x == 0)[0] array([1, 3, 5]) ```
Find indices of elements equal to zero from numpy array
4,588,628
51
2011-01-03T21:40:08Z
4,588,744
14
2011-01-03T21:59:06Z
[ "python", "numpy" ]
NumPy has the efficient function/method [`nonzero()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html) to identify the indices of non-zero elements in an `ndarray` object. What is the most efficient way to obtain the indices of the elements that *do* have a value of zero?
You can search for any scalar condition with: ``` >>> a = np.asarray([0,1,2,3,4]) >>> a == 0 # or whatver array([ True, False, False, False, False], dtype=bool) ``` Which will give back the array as an boolean mask of the condition.
Python windows 7 screenshot without PIL
4,589,206
15
2011-01-03T23:00:14Z
4,589,290
26
2011-01-03T23:15:00Z
[ "python", "image", "windows-7", "screenshot" ]
I want to take a screenshot using python. I have tried using PIL, but since I am using 64bit windows and python PIL does not work (I could only find 32bit PIL versions). I am using python 2.7.1 by the way. I want to take a screenshot, it doesn't really matter how, as long as it can take more than 1 per second in spee...
Get PIL for win-amd64-py2.7 at <http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil>. ``` from PIL import ImageGrab im = ImageGrab.grab() im.save('screenshot.png') ``` Update: use pywin32 (<http://sourceforge.net/projects/pywin32/>) instead of PIL to take screenshots of multiple virtual screens: ``` import win32gui, win3...
What is the equivalent of ruby's string inspect() in python
4,589,696
9
2011-01-04T00:39:28Z
4,589,703
11
2011-01-04T00:40:41Z
[ "python", "ruby", "string" ]
I apologize up front for the dumbness of this question, but I can't figure it out and its driving me crazy. In ruby I can do: ``` irb(main):001:0> s = "\t\t\n" => "\t\t\n" irb(main):003:0> puts s => nil irb(main):004:0> puts s.inspect "\t\t\n" ``` Is there an equivalent of ruby's `inspect` function in pyt...
[`repr()`](http://docs.python.org/library/functions.html#repr): ``` >>> print repr('\t\t\n') '\t\t\n' ```
Pass errors in Django using HttpResponseRedirect
4,590,149
3
2011-01-04T02:21:55Z
4,590,362
8
2011-01-04T03:18:29Z
[ "python", "django", "django-sessions" ]
I know that HttpResponseRedirect only takes one parameter, a URL. But there are cases when I want to redirect with an error message to display. I was reading this post: [How to pass information using an http redirect (in Django)](http://stackoverflow.com/questions/599280/how-to-pass-information-using-an-http-redirect-...
You are right about the auth messages. They are deprecated but as the [docs](http://docs.djangoproject.com/en/dev/topics/auth/#messages) suggest you should use the [django messages framework](http://docs.djangoproject.com/en/dev/ref/contrib/messages/) instead, which I think is the exact soultion for your case.
_sha import in python hashlib
4,590,242
3
2011-01-04T02:44:26Z
4,590,370
7
2011-01-04T03:19:44Z
[ "python", "hashlib" ]
Well, today I was checking the hashlib module in python, but then I found something that I still can't figure out. Inside this python module, there is an import that I can't follow. I goes like this: ``` def __get_builtin_constructor(name): if name in ('SHA1', 'sha1'): import _sha return _sha.new ...
Actually, the \_sha module is provided by shamodule.c and \_md5 is provided by md5module.c and md5.c and both will be built only when your Python is not compiled with OpenSSL by default. You can find the details in `setup.py` in your Python Source tarball. ``` if COMPILED_WITH_PYDEBUG or not have_usable_openssl: ...
Is it safe to replace '==' with 'is' to compare Boolean-values
4,591,125
18
2011-01-04T06:16:50Z
4,591,139
22
2011-01-04T06:19:28Z
[ "python" ]
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return ...
You shouldn't ever need to compare booleans. If you are doing something like: ``` if(some_bool == True): ... ``` ...just change it to: ``` if(some_bool): ... ``` No `is` or `==` needed. **Added:** okay, if it's simply about knowing more about the internals: there should only ever be [two boolean literal object...
Is it safe to replace '==' with 'is' to compare Boolean-values
4,591,125
18
2011-01-04T06:16:50Z
4,591,142
17
2011-01-04T06:20:50Z
[ "python" ]
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return ...
Watch out for what else you may be comparing. ``` >>> 1 == True True >>> 1 is True False ``` True and False will have stable object ids for their lifetime in your python instance. ``` >>> id(True) 4296106928 >>> id(True) 4296106928 ``` `is` compares the id of an object EDIT: adding `or` Since OP is using `or` in ...
Templating system for both Python and Javascript?
4,591,318
20
2011-01-04T07:03:39Z
4,591,402
11
2011-01-04T07:20:57Z
[ "javascript", "python", "templates", "google-closure-templates" ]
A nice feature of Google's Soy templates is that you can use the same templates on the client (JS) and on the server (Java). Currently I plan to render most pages client-side using Soy templates compiled to JS. However, my backend is written in Python (using Tornado), so I can't easily use the same templates server-si...
Mustache is a template engine that has been implemented in both Python and JavaScript (and many other languages). <http://mustache.github.com/>
Templating system for both Python and Javascript?
4,591,318
20
2011-01-04T07:03:39Z
6,716,248
7
2011-07-16T08:20:31Z
[ "javascript", "python", "templates", "google-closure-templates" ]
A nice feature of Google's Soy templates is that you can use the same templates on the client (JS) and on the server (Java). Currently I plan to render most pages client-side using Soy templates compiled to JS. However, my backend is written in Python (using Tornado), so I can't easily use the same templates server-si...
Michael Kerrin has created a project called [pwt.jinja2js](http://pypi.python.org/pypi/pwt.jinja2js/) Project description: > pwt.jinja2js is an extension to the Jinja2 template engine that compiles valid Jinja2 templates containing macros to JavaScript. The JavaScript output can be included via script tags or can be ...
python exception handling
4,592,162
4
2011-01-04T09:32:49Z
4,592,220
13
2011-01-04T09:39:58Z
[ "python" ]
I am developing a Django site and have been having trouble trying to work out the best way to do exception handling. I have been doing ``` try: Some code except: log error in my own words, i.e 'Some code' failed to execute Some other code ``` This catches all exceptions thus ensuring my site does not deli...
You catch the exception in an exception variable: ``` try: # some code except Exception, e: # Log the exception. ``` There are various ways to format the exception, the logging module (which I assume you/Django uses) has support to format exceptions, and the exceptions themselves usually render useful message...
Is it possible to make an option in optparse a mandatory?
4,592,922
6
2011-01-04T11:08:20Z
4,592,938
8
2011-01-04T11:09:43Z
[ "python", "optparse" ]
Is it possible to make an option in optparse a mandatory?
option is by defeinition optional :-) If you need to make something mandatory, use `argparse` and set a positional argument. <http://docs.python.org/dev/library/argparse.html>
Is it possible to make an option in optparse a mandatory?
4,592,922
6
2011-01-04T11:08:20Z
4,593,005
16
2011-01-04T11:18:35Z
[ "python", "optparse" ]
Is it possible to make an option in optparse a mandatory?
I posted a comment earlier, but given that many other answers say `No, not possible`, here is how to do it: ``` parser = OptionParser(usage='usage: %prog [options] arguments') parser.add_option('-f', '--file', dest='filename', help='foo help') (options, args) = parser.p...
How would I use django.forms to prepopulate a choice field with rows from a model?
4,593,292
3
2011-01-04T11:55:06Z
4,593,322
14
2011-01-04T11:59:23Z
[ "python", "django", "django-models", "django-forms" ]
I have a ChoiceField in my form class, presumably a list of users. How do I prepopulate this with a list of users from my User model? What I have now is: ``` class MatchForm(forms.Form): choices = [] user1_auto = forms.CharField() user1 = forms.ChoiceField(choices=choices) user2_auto = forms.CharField() u...
It looks like you may be looking for [`ModelChoiceField`](http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField). ``` user2 = forms.ModelChoiceField(queryset=User.objects.all()) ``` This won't show fullnames, though, it'll just call `__unicode__` on each object to get the displayed valu...
List of all words matching regular expression
4,594,161
2
2011-01-04T13:33:54Z
4,594,238
11
2011-01-04T13:41:35Z
[ "python", "regex" ]
Let assume that I have some string: "Lorem ipsum dolor sit amet" I need a list of all words with lenght more than 3. Can I do it with regular expressions? e.g. ``` pattern = re.compile(r'some pattern') result = pattern.search('Lorem ipsum dolor sit amet').groups() ``` result contains 'Lorem', 'ipsum', 'dolor' and 'a...
``` >>> import re >>> myre = re.compile(r"\w{4,}") >>> myre.findall('Lorem, ipsum! dolor sit? amet...') ['Lorem', 'ipsum', 'dolor', 'amet'] ``` Take note that in Python 3, where all strings are Unicode, this will also find words that use non-ASCII letters: ``` >>> import re >>> myre = re.compile(r"\w{4,}") >>> myre.f...
How to reformat URLs to be more restful (from .../?id=123 to .../123)?
4,594,602
3
2011-01-04T14:21:42Z
4,594,758
13
2011-01-04T14:39:28Z
[ "python", "google-app-engine", "url", "restful-url" ]
Currently I have pages accessed via: ``` www.foo.com/details.html?id=123 ``` I'd like to make them more restful-like, such as by the following: ``` www.foo.com/details/123 ``` I'm using Google App Engine. Currently the URL's are mapped in the `html-mappings` file: ``` ('/details.html*', DetailsPage), ``` And the...
Rewrite your URL mapping like this: ``` ('/details/(\d+)', DetailsPage), ``` (this requires that there be a trailing part of the URL that contains one or more digits and nothing else). Then modify your `DetailsPage::get()` method to accept that id parameter, like: ``` class DetailsPage(webapp.RequestHandler): d...
Wrapping a C++ class in Python using SWIG
4,596,484
5
2011-01-04T17:22:10Z
4,597,631
10
2011-01-04T19:38:35Z
[ "c++", "python", "swig" ]
**example.h**: ``` #ifndef EXAMPLE_H #define EXAMPLE_H class Math { public: int pi() const; void pi(int pi); private: int _pi; }; #endif ``` **example.cpp**: ``` #include "example.h" int Math::pi() const { return this->_pi; } void Math::pi(int pi) { this->_pi = pi; } ``` **example.swig**:...
I think the swig command should be "swig -c++ -python example.swig"
Display graph without saving using pydot
4,596,962
8
2011-01-04T18:19:40Z
18,522,941
12
2013-08-30T00:13:23Z
[ "python", "pydot" ]
I am trying to display a simple graph using pydot. My question is that is there any way to display the graph without writing it to a file as currently I use write function to first draw and then have to use the Image module to show the files. However is there any way that the graph directly gets printed on the screen...
You can render the image from `pydot` by calling `GraphViz`'s `dot` without writing any files to the disk. Then just plot it. This can be done as follows, assuming `g` is a `pydot` graph: ``` from cStringIO import StringIO import matplotlib.pyplot as plt import matplotlib.image as mpimg import networkx as nx # creat...
how to rewrite python dicts to get default values
4,596,994
3
2011-01-04T18:24:39Z
4,597,005
11
2011-01-04T18:27:06Z
[ "python", "dictionary" ]
I want to rewrite Python's dictionary access mechanism "**getitem**" to be able to return default values. The functionality I am looking for is something like ``` a = dict() a.setdefault_value(None) print a[100] #this would return none ``` any hints ? Thanks
There is already a [`collections.defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict): ``` from collections import defaultdict a = defaultdict(lambda:None) print a[100] ```
How to statically link a library when compiling a python module extension
4,597,228
15
2011-01-04T18:53:04Z
4,600,466
7
2011-01-05T03:01:44Z
[ "python", "static", "compilation" ]
I would like to modify a setup.py file such that the command "python setup.py build" compiles a C-based extension module that is statically (rather than dynamically) linked to a library. The extension is currently dynamically linked to a number of libraries. I would like to leave everything unchanged except for static...
If all else fails, there's always the little-documented [`extra_compile_args`](http://docs.python.org/distutils/setupscript.html#other-options) and `extra_link_args` options to the [`Extension`](http://docs.python.org/distutils/setupscript.html#describing-extension-modules) builder. (See also [here](http://docs.python....
Django - user permissions to certain views?
4,597,401
13
2011-01-04T19:11:36Z
4,597,437
15
2011-01-04T19:15:17Z
[ "python", "django", "django-authentication", "django-permissions", "django-login" ]
From the admin I see that you can allocate permissions to a user or a user group to :allow add, change or delete data from a model. That is great, but I also need to allow a user or a user group to access or not a group of views. I have certain type of services on my web site so I want to allow some users to access a ...
Users that cannot add or change etc. a certain model, will not be able to see it in the admin. If we are talking about your custom created views then you could create something which checks a user for a permission and returns a 404 if they do not have that permission. Permissions are linked to models and a group can b...
Django - user permissions to certain views?
4,597,401
13
2011-01-04T19:11:36Z
4,597,516
8
2011-01-04T19:23:59Z
[ "python", "django", "django-authentication", "django-permissions", "django-login" ]
From the admin I see that you can allocate permissions to a user or a user group to :allow add, change or delete data from a model. That is great, but I also need to allow a user or a user group to access or not a group of views. I have certain type of services on my web site so I want to allow some users to access a ...
You need to manage that manually, but it's pretty easy. Presumably there's an attribute that determines whether or not a group has permission to see a view: then you just decorate that view with either the `permission_required` decorator, if it's a simple question of whether the user has a particular Permission, or `us...
Installing lxml module in python
4,598,229
45
2011-01-04T20:45:13Z
4,598,317
45
2011-01-04T20:54:53Z
[ "python", "lxml", "python-import" ]
while running a python script, I got this error ``` from lxml import etree ImportError: No module named lxml ``` now I tried to install lxml ``` sudo easy_install lmxl ``` but it gives me the following error ``` Building lxml version 2.3.beta1. NOTE: Trying to build without Cython, pre-generated 'src/lxml/lxml.e...
You need to install Python's header files (python-dev package in debian/ubuntu) to compile lxml. As well as libxml2, libxslt, libxml2-dev, and libxslt-dev: ``` apt-get install python-dev libxml2 libxml2-dev libxslt-dev ```
Installing lxml module in python
4,598,229
45
2011-01-04T20:45:13Z
4,598,340
72
2011-01-04T20:57:27Z
[ "python", "lxml", "python-import" ]
while running a python script, I got this error ``` from lxml import etree ImportError: No module named lxml ``` now I tried to install lxml ``` sudo easy_install lmxl ``` but it gives me the following error ``` Building lxml version 2.3.beta1. NOTE: Trying to build without Cython, pre-generated 'src/lxml/lxml.e...
Just do: ``` sudo apt-get install python-lxml ``` If you are planning to install from source, then [albertov's answer](http://stackoverflow.com/questions/4598229/installing-lxml-module-in-python/4598317#4598317) will help. But unless there is a reason, don't, just install it from the repository.
Installing lxml module in python
4,598,229
45
2011-01-04T20:45:13Z
19,035,201
17
2013-09-26T17:51:58Z
[ "python", "lxml", "python-import" ]
while running a python script, I got this error ``` from lxml import etree ImportError: No module named lxml ``` now I tried to install lxml ``` sudo easy_install lmxl ``` but it gives me the following error ``` Building lxml version 2.3.beta1. NOTE: Trying to build without Cython, pre-generated 'src/lxml/lxml.e...
I solved it upgrading the lxml version with: ``` pip install --upgrade lxml ```
How to pass unicode keywords to **kwargs
4,598,604
6
2011-01-04T21:27:29Z
4,598,644
15
2011-01-04T21:32:05Z
[ "python", "unicode", "kwargs" ]
I was exception the following to work. ``` def foo(**kwargs): print kwargs foo(**{'a':'b'}) foo(**{u'a':'b'}) ``` > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: m() keywords must be strings Am I doing something wrong or I should I fix it?
Upgrade to Python 2.6.5 or later.
Are the python built-in methods available in an alternative namespace anywhere?
4,599,016
5
2011-01-04T22:13:59Z
4,599,044
11
2011-01-04T22:18:06Z
[ "python", "built-in" ]
Are the python [built-in](http://docs.python.org/library/functions.html#built-in-functions) methods available to reference in a package somewhere? Let me explain. In my early(ier) days of python I made a django model similar to this: ``` class MyModel(models.Model): first_name = models.CharField(max_length=100, n...
Use `__builtin__`. ``` def open(): pass import __builtin__ print open print __builtin__.open ``` This gives you: ``` <function open at 0x011E8670> <built-in function open> ```
Textually diffing JSON
4,599,456
12
2011-01-04T23:19:41Z
4,599,500
21
2011-01-04T23:27:37Z
[ "python", "json", "text", "diff" ]
As part of my release processes, I have to compare some JSON configuration data used by my application. As a first attempt, I just pretty-printed the JSON and diff'ed them (using kdiff3 or just diff). As that data has grown, however, kdiff3 confuses different parts in the output, making additions look like giant modif...
If any of your tool has the option, [Patience Diff](http://bramcohen.livejournal.com/73318.html) could work a lot better for you. I'll try to find a tool with it (other tha Git and Bazaar) and report back. Edit: It seems that [the implementation in Bazaar](http://bazaar.launchpad.net/~bzr-pqm/bzr/bzr.dev/annotate/head...
Handling \r\n vs \n newlines in python on Mac vs Windows
4,599,936
17
2011-01-05T00:54:01Z
4,599,970
16
2011-01-05T01:02:04Z
[ "python", "windows", "osx", "python-2.x" ]
I have a python script that gave different output when run on a Windows machine and when run on a Mac. On digging deeper, I discovered that it was because when Python read in line breaks on the Mac (from a file), it read in `\r\n`, while somehow in Windows the `\r` disappears. Thus, if I change every `\n` in the scrip...
I guess it may depend on what you're reading from, but the built-in open() function takes a 'mode' parameter, and if you pass 'U' for the mode, Python will take care of the newlines in a cross-platform way transparently. It requires that Python be built with universal newline support, but test it out! <http://docs.pyt...
Handling \r\n vs \n newlines in python on Mac vs Windows
4,599,936
17
2011-01-05T00:54:01Z
4,601,716
27
2011-01-05T07:24:59Z
[ "python", "windows", "osx", "python-2.x" ]
I have a python script that gave different output when run on a Windows machine and when run on a Mac. On digging deeper, I discovered that it was because when Python read in line breaks on the Mac (from a file), it read in `\r\n`, while somehow in Windows the `\r` disappears. Thus, if I change every `\n` in the scrip...
Different platforms have different codes for "new line". Windows have \r\n, Unix has \n, Old macs have \r and yes there are some systems that have \n\r too. When you open a file in text mode in Python 3, it will convert all newlines to '\n' and be done with it. ``` infile = open("filename", 'r') ``` Text mode is def...
python close file descriptor question
4,599,980
15
2011-01-05T01:04:59Z
4,600,010
32
2011-01-05T01:10:05Z
[ "python", "file-io", "coding-style" ]
I think this question is more of a "coding style" rather than technical issue. Said I have a line of code: ``` buf = open('test.txt','r').readlines() ... ``` Will the file descriptor automatically close, or will it stay in the memory? If the file descriptor is not closed, what is the prefer way to close it?
If you assign the file object to a variable, you can explicitly close it using `.close()` ``` f = open('test.txt','r') buf = f.readlines() f.close() ``` Alternatively (and more generally preferred), you can use the `with` keyword (Python 2.5 and greater) as mentioned in the [Python docs](http://docs.python.org/tutori...
python close file descriptor question
4,599,980
15
2011-01-05T01:04:59Z
4,600,163
12
2011-01-05T01:49:11Z
[ "python", "file-io", "coding-style" ]
I think this question is more of a "coding style" rather than technical issue. Said I have a line of code: ``` buf = open('test.txt','r').readlines() ... ``` Will the file descriptor automatically close, or will it stay in the memory? If the file descriptor is not closed, what is the prefer way to close it?
Usually in CPython, the file is closed right away when the reference count drops to zero (although this behaviour is not guaranteed for future versions of CPython) In other implementations, such as Jython, the file won't be closed until it is garbarge collected, which can be a long time later. It's poor style to have...
Django datefield filter by weekday/weekend
4,600,325
6
2011-01-05T02:27:13Z
4,600,359
7
2011-01-05T02:34:07Z
[ "python", "django", "datetime", "django-models" ]
I've got a date\_created field in my database: `date_created = models.DateField(auto_now_add=True)` Is there some way I could filter date\_created by weekend/weekday? I know that python's date.weekday() returns 0 - 6 depending on days of the week, so I'd like to use something like: ``` apps.objects.filter(date_creat...
Django comes with a weekday field lookup. * <http://docs.djangoproject.com/en/dev/ref/models/querysets/#week-day>
Can SQLAlchemy eager/joined loads be suppressed once set up?
4,600,683
10
2011-01-05T03:52:40Z
4,601,258
17
2011-01-05T06:05:09Z
[ "python", "sqlalchemy", "lazy-loading", "eager-loading" ]
I've got a case where most of the time the relationships between objects was such that pre-configuring an eager (joined) load on the relationship made sense. However now I've got a situation where I really don't want the eager load to be done. Should I be removing the joined load from the relationship and changing all...
You may override eagerness of properties on query-by-query basis, as far as I remember. Will this work? ``` from sqlalchemy.orm import lazyload joe = (s2.query(User) .options(lazyload('addresses')) .filter_by(name = "Joe").one()) for addr in joe.addresses: print addr.address ``` See [the docs.](http://doc...
Better way to shuffle two numpy arrays in unison
4,601,373
48
2011-01-05T06:23:56Z
4,602,224
58
2011-01-05T08:52:04Z
[ "python", "random", "numpy", "shuffle" ]
I have two numpy arrays of different shapes, but with the same length (leading dimension). I want to shuffle each of them, such that corresponding elements continue to correspond -- i.e. shuffle them in unison with respect to their leading indices. This code works, and illustrates my goals: ``` def shuffle_in_unison(...
Your can use NumPy's [array indexing](https://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html): ``` def unison_shuffled_copies(a, b): assert len(a) == len(b) p = numpy.random.permutation(len(a)) return a[p], b[p] ``` This will result in creation of separate unison-shuffled arrays.
Better way to shuffle two numpy arrays in unison
4,601,373
48
2011-01-05T06:23:56Z
4,603,609
22
2011-01-05T11:35:28Z
[ "python", "random", "numpy", "shuffle" ]
I have two numpy arrays of different shapes, but with the same length (leading dimension). I want to shuffle each of them, such that corresponding elements continue to correspond -- i.e. shuffle them in unison with respect to their leading indices. This code works, and illustrates my goals: ``` def shuffle_in_unison(...
Your "scary" solution does not appear scary to me. Calling `shuffle()` for two sequences of the same length results in the same number of calls to the random number generator, and these are the only "random" elements in the shuffle algorithm. By resetting the state, you ensure that the calls to the random number genera...
Better way to shuffle two numpy arrays in unison
4,601,373
48
2011-01-05T06:23:56Z
30,633,632
33
2015-06-04T01:46:55Z
[ "python", "random", "numpy", "shuffle" ]
I have two numpy arrays of different shapes, but with the same length (leading dimension). I want to shuffle each of them, such that corresponding elements continue to correspond -- i.e. shuffle them in unison with respect to their leading indices. This code works, and illustrates my goals: ``` def shuffle_in_unison(...
``` X = np.array([[1., 0.], [2., 1.], [0., 0.]]) y = np.array([0, 1, 2]) from sklearn.utils import shuffle X, y = shuffle(X, y, random_state=0) ``` To learn more, see <http://scikit-learn.org/stable/modules/generated/sklearn.utils.shuffle.html>
Reflection in python
4,601,571
2
2011-01-05T06:58:44Z
4,601,590
8
2011-01-05T07:03:26Z
[ "python", "django", "reflection" ]
I'm trying to find some info on reflection in python. I found a wikipedia article which gave this as a code snippet: ``` # without reflection Foo().hello() # with reflection getattr(globals()['Foo'](), 'hello')() ``` I wasn't able to get this to work. What I really need is a way to just instantiate the object. So if...
> What I really need is a way to just instantiate the object. That's what the `globals()['Foo']()` part does. And it works for me: ``` >>> class Foo: ... def __init__(self): print "Created a Foo!" ... >>> globals()['Foo']() Created a Foo! <__main__.Foo instance at 0x02A33350> >>> ```
Importing and using modules in python
4,601,697
2
2011-01-05T07:21:29Z
4,601,725
9
2011-01-05T07:26:44Z
[ "python", "import" ]
New to python and trying to do a random number generator. However, I am having trouble importing the random module. I get a AttributeError when I try to use anything from the random module. Thanks for your help. ``` #!/usr/bin/python -tt import random def main(): x = random.randint(1,1000) print x if __name__ =...
You probably have a file named random.py (or pyc) in your current directory. You can find out where the random module you're using comes from by doing this: ``` import random print(random.__file__) ```