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 |
|---|---|---|---|---|---|---|---|---|---|
Does Python have a built in function for string natural sort? | 4,836,710 | 113 | 2011-01-29T11:55:53Z | 18,415,320 | 73 | 2013-08-24T05:38:42Z | [
"python",
"sorting",
"python-3.x"
] | Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort.
**Natural sort:** The order by which files in Windows are sorted.
For instance, the following list is naturally sorted (what I want):
```
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
```
... | There is a third party library for this on PyPI called [natsort](https://pypi.python.org/pypi/natsort) (full disclosure, I am the package's author). For your case, you can do either of the following:
```
>>> from natsort import natsorted, ns
>>> x = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
... |
Does Python have a built in function for string natural sort? | 4,836,710 | 113 | 2011-01-29T11:55:53Z | 31,432,964 | 8 | 2015-07-15T14:16:56Z | [
"python",
"sorting",
"python-3.x"
] | Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort.
**Natural sort:** The order by which files in Windows are sorted.
For instance, the following list is naturally sorted (what I want):
```
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
```
... | ```
data = ['elm13', 'elm9', 'elm0', 'elm1', 'Elm11', 'Elm2', 'elm10']
```
Let's analyse the data. The digit capacity of all elements is 2. And there are 3 letters in common literal part `'elm'`.
So, the maximal length of element is 5. We can increase this value to make sure (for example, to 8).
**Bearing that in mi... |
Some basic clarifications about Python? | 4,837,218 | 11 | 2011-01-29T13:55:02Z | 4,837,242 | 11 | 2011-01-29T13:59:41Z | [
"python",
"jython"
] | Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
1. `Python is implemented in C` - Does that mean that the interpreter was writ... | "Python" is the name of the language itself, not of a particular interpreter implementation, just as "C" is the name of a programming language and not of a particular compiler.
"CPython" is an implementation of an interpreter of the Python language written in C. It compiles Python source code to byte code and interpre... |
Some basic clarifications about Python? | 4,837,218 | 11 | 2011-01-29T13:55:02Z | 4,837,294 | 7 | 2011-01-29T14:07:44Z | [
"python",
"jython"
] | Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
1. `Python is implemented in C` - Does that mean that the interpreter was writ... | 1. The former.
2. I suppose yes. Strictly speaking, "Python" refers only to the language (regardless of the implementation) - but unless the distinction important (e.g. when discussing implementations details), it can also refer to implementations. "CPython" is an unambiguous name for the oldest, most widely-used imple... |
pythonrc.py is not loading in interactive mode | 4,837,237 | 4 | 2011-01-29T13:58:42Z | 4,837,309 | 10 | 2011-01-29T14:10:08Z | [
"python",
"shell",
"ubuntu"
] | I've added a .pythonrc.py script to my home directory with the commands below:
```
import os
import sys
print 'Welcome'
```
I've confirmed that it is actually executable by running `python .pythonrc.py` and by loading the python interpreter and running `execfile('.pythonrc.py')`. However, when I start interactive mod... | You should set the Environment variable [PYTHONSTARTUP](http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP) to point to the start up script that you created.
In Ubuntu you can edit the ~/.bashrc file and add this line in the end:
```
export PYTHONSTARTUP=~/.pythonrc.py
```
Now you **should** start a new ... |
django-admin.py and virtualenv issue on Windows | 4,837,632 | 11 | 2011-01-29T15:18:06Z | 4,837,967 | 19 | 2011-01-29T16:28:52Z | [
"python",
"windows",
"django",
"django-admin",
"virtualenv"
] | In my system there is Django 1.2.3 installed system wide:
```
C:\>python -c "import django; print django.get_version()"
1.2.3
C:\>django-admin.py --version
1.2.3
```
Then there is a virtual environment called *venv* in C:\dev where I installed Django 1.2.4:
```
C:\> dev\venv\Scripts\activate.bat
(venv) C:\> python -... | This is because your windows has associated `.py` extension with the globally installed `python.exe`. Therefore when you type `django-admin.py`, even though you're in a virtualenv, the global python is invoked, and it in turn finds your global django installation in its own site-packages. Try `python django-admin.py` t... |
django-admin.py and virtualenv issue on Windows | 4,837,632 | 11 | 2011-01-29T15:18:06Z | 7,168,905 | 17 | 2011-08-23T23:55:17Z | [
"python",
"windows",
"django",
"django-admin",
"virtualenv"
] | In my system there is Django 1.2.3 installed system wide:
```
C:\>python -c "import django; print django.get_version()"
1.2.3
C:\>django-admin.py --version
1.2.3
```
Then there is a virtual environment called *venv* in C:\dev where I installed Django 1.2.4:
```
C:\> dev\venv\Scripts\activate.bat
(venv) C:\> python -... | As shanyu already explained, it is because of \*.py file associations made to your Python install executable instead of your virtualenv. However, to answer your second question differently, I solved this problem by creating a `django-admin.bat` in my virtualenv's `Scripts` directory. Its contents?
```
@echo off
python... |
Assigning to an instance's __class__ attribute in Python | 4,838,145 | 19 | 2011-01-29T17:04:05Z | 4,838,197 | 12 | 2011-01-29T17:12:05Z | [
"python",
"metaprogramming"
] | Under what circumstances is it possible, and when is it impossible, to assign to an instance's `__class__` attribute in Python?
Error messages such as `TypeError: __class__ assignment: only for heap types` don't really do it for me. | You can only assign to the `__class__` attribute of an instance of a user-defined class (i.e. defined using the `class` keyword), and the new value must also be a user-defined class. Whether the classes are new-style or old-style does not matter. (You can't mix them, though. You can't turn an old-style class instance i... |
How do I truncate a list? | 4,838,504 | 21 | 2011-01-29T18:04:49Z | 4,838,509 | 9 | 2011-01-29T18:06:11Z | [
"python",
"list"
] | If I have a list and want to truncate it so it is no more than 100 items, how do I do this? | You can use list slicing:
```
a = a[0:100]
``` |
How do I truncate a list? | 4,838,504 | 21 | 2011-01-29T18:04:49Z | 4,838,541 | 44 | 2011-01-29T18:11:01Z | [
"python",
"list"
] | If I have a list and want to truncate it so it is no more than 100 items, how do I do this? | To modify the list in place (rather than make a shorter copy of the list), use:
```
del l[100:]
``` |
Python: PyQt Popup Window | 4,838,890 | 15 | 2011-01-29T19:14:11Z | 4,839,239 | 29 | 2011-01-29T20:27:39Z | [
"python",
"pyqt"
] | So I've been creating my GUI with Qt for my Python application. I've now come to a situation where after a button has been pushed the appropriate deferred gets executed, we perform some tasks then I need to open up a separate window that contains one or two things. But I can't seem to figure out how to create this new ... | A common error that can drive you crazy is forgetting to store the handle of the popup window you create in some python variable that will remain alive (e.g. in a data member of the main window).
The following is a simple program that creates a main window with a button where pressing the button opens a popup
```
#!/... |
Float to binary | 4,838,994 | 5 | 2011-01-29T19:34:50Z | 4,839,134 | 13 | 2011-01-29T20:08:10Z | [
"python",
"binary",
"floating-point"
] | I'm trying to convert a floating point number to binary representation; how can I achieve this?
My goal is, however, not to be limited by 2m so I'm hoping for something that could be easily extended to any base (3, 4, 8) ecc.
I've got a straightforward implementation so far for integers:
```
import string
LETTER = '... | For floats there is built-in method hex().
<http://docs.python.org/library/stdtypes.html#float.hex>
It gives you the hexadecimal representation of a given number. And translation form hex to binary is trivial.
For example:
```
In [15]: float.hex(1.25)
Out[15]: '0x1.4000000000000p+0'
In [16]: float.hex(8.25)
Out[16... |
Float to binary | 4,838,994 | 5 | 2011-01-29T19:34:50Z | 4,842,624 | 9 | 2011-01-30T11:23:22Z | [
"python",
"binary",
"floating-point"
] | I'm trying to convert a floating point number to binary representation; how can I achieve this?
My goal is, however, not to be limited by 2m so I'm hoping for something that could be easily extended to any base (3, 4, 8) ecc.
I've got a straightforward implementation so far for integers:
```
import string
LETTER = '... | Next answer with a bit of theory.
***Explanation below does not explain IEEE Floating Point standard only general ideas concerning representation of floating point numbers***
Every float number is represented as a fractional part multiplied by an exponent multiplied by a sign. Additionally there is so called bias for... |
How to make sure buildout doesn't use the already installed packages? | 4,839,194 | 7 | 2011-01-29T20:20:31Z | 4,844,911 | 9 | 2011-01-30T19:18:12Z | [
"python",
"django",
"virtualenv",
"buildout"
] | I am trying to switch fully to buildout - but our development environment already has lot of stuff installed in `/usr/lib/pythonxx/`
How can I make sure that buildout doesn't use the libraries installed on the system already - eventually without virtualenv ?
For example - how to avoid this behavior ? :
```
> cat bui... | You can tell buildout if you want to use site-pakages or not with one of these two directives: `include-site-packages` and `allowed-eggs-from-site-packages`
From buildout [documentation](http://pypi.python.org/pypi/zc.buildout/1.5.2#working-with-a-system-python):
> You can then use include-site-packages
> = false and... |
How do I use Django's logger to log a traceback when I tell it to? | 4,839,762 | 21 | 2011-01-29T22:07:25Z | 4,839,831 | 37 | 2011-01-29T22:22:16Z | [
"python",
"django",
"logging",
"traceback"
] | ```
try:
print blah
except KeyError:
traceback.print_exc()
```
I used to debug like this. I'd print to the console. Now, I want to log everything instead of print, since Apache doesn't allow printing. So, how do I log this entire traceback? | You can use python's logging mechanism:
```
import logging
...
logger = logging.getLogger("blabla")
...
try:
print blah # You can use logger.debug("blah") instead of print
except KeyError:
logger.exception("An error occurred")
```
This will print the stack trace and will work with apache. |
How do I use Django's logger to log a traceback when I tell it to? | 4,839,762 | 21 | 2011-01-29T22:07:25Z | 4,840,030 | 7 | 2011-01-29T23:07:46Z | [
"python",
"django",
"logging",
"traceback"
] | ```
try:
print blah
except KeyError:
traceback.print_exc()
```
I used to debug like this. I'd print to the console. Now, I want to log everything instead of print, since Apache doesn't allow printing. So, how do I log this entire traceback? | If you're running Django's trunk version (or 1.3 when it's released), there are a number of default logging configurations built in which are integrated with Python's standard logging module. For that, all you need to do is `import logging`, call `logger = logging.getLogger(__name__)` and then call `logger.exception(ms... |
Why don't my south migrations work? | 4,840,102 | 78 | 2011-01-29T23:23:13Z | 4,840,247 | 8 | 2011-01-29T23:55:37Z | [
"python",
"django",
"migration",
"django-south"
] | First, I create my database.
```
create database mydb;
```
I add "south" to installed Apps. Then, I go to this tutorial: <http://south.aeracode.org/docs/tutorial/part1.html>
The tutorial tells me to do this:
```
$ py manage.py schemamigration wall --initial
>>> Created 0001_initial.py. You can now apply this migra... | The tutorial you're using states:
> (If this fails complaining that
> south\_migrationhistory does not exist,
> you forgot to run syncdb [after you
> installed
> South](http://south.aeracode.org/docs/installation.html#installation-configure).)
Assuming that your post accurately details the steps you've taken, followi... |
Why don't my south migrations work? | 4,840,102 | 78 | 2011-01-29T23:23:13Z | 4,840,262 | 173 | 2011-01-29T23:58:36Z | [
"python",
"django",
"migration",
"django-south"
] | First, I create my database.
```
create database mydb;
```
I add "south" to installed Apps. Then, I go to this tutorial: <http://south.aeracode.org/docs/tutorial/part1.html>
The tutorial tells me to do this:
```
$ py manage.py schemamigration wall --initial
>>> Created 0001_initial.py. You can now apply this migra... | South allows you to create migrations when you first start out with a new app and the tables haven't been added to the database yet, as well as creating migrations for legacy apps that already have tables in the database. The key is to know when to do what.
Your first mistake was when you deleted your migrations, as s... |
Why don't my south migrations work? | 4,840,102 | 78 | 2011-01-29T23:23:13Z | 8,717,288 | 10 | 2012-01-03T19:05:26Z | [
"python",
"django",
"migration",
"django-south"
] | First, I create my database.
```
create database mydb;
```
I add "south" to installed Apps. Then, I go to this tutorial: <http://south.aeracode.org/docs/tutorial/part1.html>
The tutorial tells me to do this:
```
$ py manage.py schemamigration wall --initial
>>> Created 0001_initial.py. You can now apply this migra... | This is how I get things working.
```
pip install South
# add 'south', to INSTALL_APPS, then
python manage.py syncdb
# For existing project + database
python manage.py convert_to_south app_name
# Thereafter, call them per model changes
python manage.py schemamigration app_name --auto
python manage.py migrate app_na... |
setup.py and adding file to /bin/ | 4,840,182 | 23 | 2011-01-29T23:41:21Z | 4,840,212 | 7 | 2011-01-29T23:47:48Z | [
"python"
] | I can't figure out how to make `setup.py` add a scrip to the the user's `/bin` or `/usr/bin` or whatever.
E.g., I'd like to add a `myscript.py` to `/usr/bin` so that the user can call `myscript.py` from any directory. | The Python documentation explains it under the [installing scripts](http://docs.python.org/distutils/setupscript.html#installing-scripts) section.
> Scripts are files containing Python source code, intended to be started from the command line. |
setup.py and adding file to /bin/ | 4,840,182 | 23 | 2011-01-29T23:41:21Z | 9,478,011 | 8 | 2012-02-28T07:29:03Z | [
"python"
] | I can't figure out how to make `setup.py` add a scrip to the the user's `/bin` or `/usr/bin` or whatever.
E.g., I'd like to add a `myscript.py` to `/usr/bin` so that the user can call `myscript.py` from any directory. | If you're willing to build and install the entire python package, this is how I would go about it:
* Edit the setup() function in setup.py to contain a parameter named *scripts* and set its argument as the location of the file(s) you wish to run from anywhere. e.g.
`setup(name='myproject',author='',author_email='',sc... |
setup.py and adding file to /bin/ | 4,840,182 | 23 | 2011-01-29T23:41:21Z | 11,717,581 | 26 | 2012-07-30T08:08:52Z | [
"python"
] | I can't figure out how to make `setup.py` add a scrip to the the user's `/bin` or `/usr/bin` or whatever.
E.g., I'd like to add a `myscript.py` to `/usr/bin` so that the user can call `myscript.py` from any directory. | Consider using `console_scripts`:
```
from setuptools import setup
setup(name='some-name',
...
entry_points = {
'console_scripts': [
'command-name = package.module:main_func_name',
],
},
)
```
Where `main_func_name` is... |
wxPython GridSizer - dealing with empty cells | 4,840,224 | 4 | 2011-01-29T23:50:14Z | 4,840,272 | 9 | 2011-01-29T23:59:23Z | [
"python",
"user-interface",
"layout",
"wxpython",
"wxglade"
] | I'm making my first foray into GUI programming, and I'm trying to get to grips with wxPython. I'm trying to use wxGlade, but it's turning out to be a bit buggy.
I'm making a layout using GridSizer.
I've worked out that every time you add something to the sizer, it gets put in the next cell. This means if you have an ... | As you said... adding a dummy widget (blank static text) works well. You can also use AddMany() instead of multiple add()'s.
```
grid_sizer_1 = wx.GridSizer(3, 3, 0, 0)
grid_sizer_1.AddMany( [
(self.button_last_page, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL),
(self.button_up, 0, wx.ALIGN_BOTTOM|wx.AL... |
Can a value in a Python Dictionary have two values? | 4,840,249 | 5 | 2011-01-29T23:55:49Z | 4,840,271 | 15 | 2011-01-29T23:59:12Z | [
"python",
"dictionary"
] | For a test program I'm making a simple model of the NFL. I'd like to assign a record (wins and losses) to a team as a value in a dictionary? Is that possible?
For example:
```
afcNorth = ["Baltimore Ravens", "Pittsburgh Steelers", "Cleveland Browns", "Cincinatti Bengals"]
```
If the Ravens had 13 wins and 3 loses, c... | sure, just make the value a list or tuple:
```
afc = {'Baltimore Ravens': (10,3), 'Pb Steelers': (3,4)}
```
If it gets more complicated, you might want to make a more complicated structure than a tuple - for example if you like dictionaries, you can put a dictionary in your dictionary so you can dictionary while you ... |
Alias expressions inside Python list comprehensions | 4,840,392 | 9 | 2011-01-30T00:31:47Z | 4,840,429 | 8 | 2011-01-30T00:41:24Z | [
"python",
"alias",
"list-comprehension"
] | I find myself often wanting to write Python list comprehensions like this:
```
nearbyPoints = [(n, delta(n,x)) for n in allPoints if delta(n,x)<=radius]
```
That hopefully gives some context as to why I would want to do this, but there
are also cases where multiple values need to be computed/compared per
element:
``... | In regards to #1, yes, they will be evaluated multiple times.
In regards to #2, the way to do it is to calculate and filter in separate comprehensions:
Condensed version:
```
[(x,fx,gx) for (x,fx,gx) in ((x,fx,g(fx)) for (x,fx) in ((x,f(x)) for x in bigList) if fx < p) if gx<q]
```
Longer version expanded to make i... |
Which way to go with twisted and web-programming? | 4,840,444 | 9 | 2011-01-30T00:45:59Z | 4,840,841 | 9 | 2011-01-30T02:49:13Z | [
"python",
"django",
"twisted",
"twisted.web",
"nevow"
] | So, I programmed this twisted application a few months ago, which I now would like to extend with a web-based user interface for configuration.
The Twisted website recommends Nevow, but I am not really sure if this is a good choice. Their website is down for a while it seems and their launchpad page hadn't seen any up... | First, let me address the perception that Nevow is dead. The launchpad project containing the code for Nevow (and the rest of the Divmod projects) is [divmod.org on launchpad](http://launchpad.net/divmod.org). A hardware failure has badly impacted the project's public presence, but it's still there, and other things (l... |
How do I use Python to easily expand variables to strings? | 4,840,580 | 10 | 2011-01-30T01:21:31Z | 4,840,617 | 16 | 2011-01-30T01:33:05Z | [
"python",
"string",
"variables",
"idioms",
"expand"
] | What's a nice idiom to do this:
Instead of:
`print "%s is a %s %s that %s" % (name, adjective, noun, verb)`
I want to be able to do something to the effect of:
`print "{name} is a {adjective} {noun} that {verb}"` | ```
"{name} is a {adjective} {noun} that {verb}".format(**locals())
```
* `locals()` gives a reference to the current namespace (as a dictionary).
* `**locals()` unpacks that dictionary into keyword arguments (`f(**{'a': 0, 'b': 1})` is `f(a=0, b=1)`).
* `.format()` is ["the new string formatting"](http://www.python.o... |
How to use cursor() for pagination? | 4,840,731 | 4 | 2011-01-30T02:17:36Z | 4,841,125 | 7 | 2011-01-30T04:20:44Z | [
"python",
"google-app-engine",
"pagination",
"cursor"
] | Can anyone point me to a practical application of `cursor()` to do pagination?
I am not clear how to use `cursor()` as given in the [documentation](https://code.google.com/appengine/docs/python/datastore/gqlqueryclass.html#GqlQuery_cursor).
This is my query:
```
items = db.GqlQuery("SELECT * FROM Item ORDER BY date ... | Here's a simple example to get you started...
```
query = db.GqlQuery("SELECT * FROM Item ORDER BY date DESC")
cursor = self.request.get('cursor')
if cursor: query.with_cursor(cursor)
items = query.fetch(30)
cursor = query.cursor()
... your regular output ...
self.response.out.write('<a href="yoururl?cursor=%s">Next... |
python sqlite3 update not updating | 4,840,772 | 4 | 2011-01-30T02:30:12Z | 4,840,786 | 8 | 2011-01-30T02:34:31Z | [
"python",
"sqlite3"
] | Question: Why is this sqlite3 statement not updating the record?
---
Info:
```
cur.execute('UPDATE workunits SET Completed=1 AND Returns=(?) WHERE PID=(?) AND Args=(?)',(pickle.dumps(Ret),PID,Args))
```
I'm using python and sqlite3. this statement does not throw an error, it just seems like it is out right ignored.... | don't use 'AND', use a ','.
```
cur.execute('UPDATE workunits SET Completed=1, Returns=? WHERE PID=? AND Args=?',
(pickle.dumps(Ret), PID, Args)
)
``` |
python sqlite3 update not updating | 4,840,772 | 4 | 2011-01-30T02:30:12Z | 16,665,112 | 7 | 2013-05-21T08:10:23Z | [
"python",
"sqlite3"
] | Question: Why is this sqlite3 statement not updating the record?
---
Info:
```
cur.execute('UPDATE workunits SET Completed=1 AND Returns=(?) WHERE PID=(?) AND Args=(?)',(pickle.dumps(Ret),PID,Args))
```
I'm using python and sqlite3. this statement does not throw an error, it just seems like it is out right ignored.... | If the problem persists after you fixed your syntax. Please make sure you're using:
```
conn.commit()
```
After cur.execute, UPDATES and INSERTS require COMMIT. |
How Do I Keep Python Code Under 80 Chars Without Making It Ugly? | 4,841,226 | 33 | 2011-01-30T04:52:28Z | 4,841,262 | 9 | 2011-01-30T05:00:33Z | [
"python"
] | This is a question that keeps recurring in all of my programming, python and otherwise. I really like to keep my code under 80 chars if at all possible/not horribly ugly. In a language like Perl, this isn't too hard since white space doesn't matter. In Python, where it does, I wind up knocking my head against the wall ... | ```
self.SomeLongLongName = SomeLongLongName.\
SomeLongLongName(some_obj, self.user1, self.user2)
```
'\' is your friend. Of course, you already know that you can split lines in an argument list at commas, without using '\'. Also, if you have long strings:
```
myLongString = "This is a really long string that is ... |
How Do I Keep Python Code Under 80 Chars Without Making It Ugly? | 4,841,226 | 33 | 2011-01-30T04:52:28Z | 4,841,486 | 15 | 2011-01-30T06:15:19Z | [
"python"
] | This is a question that keeps recurring in all of my programming, python and otherwise. I really like to keep my code under 80 chars if at all possible/not horribly ugly. In a language like Perl, this isn't too hard since white space doesn't matter. In Python, where it does, I wind up knocking my head against the wall ... | > The preferred way of wrapping long
> lines is by using Python's implied
> line continuation inside parentheses,
> brackets and braces. Long lines can
> be broken over multiple lines by
> wrapping expressions in parentheses.
> These should be used in preference to
> using a backslash for line
> continuation. Make sure... |
How Do I Keep Python Code Under 80 Chars Without Making It Ugly? | 4,841,226 | 33 | 2011-01-30T04:52:28Z | 4,841,642 | 27 | 2011-01-30T07:02:01Z | [
"python"
] | This is a question that keeps recurring in all of my programming, python and otherwise. I really like to keep my code under 80 chars if at all possible/not horribly ugly. In a language like Perl, this isn't too hard since white space doesn't matter. In Python, where it does, I wind up knocking my head against the wall ... | Your code style seems to insist that if you break a line inside a parenthesis, lines below need to line up with it:
```
self.SomeLongLongName = SomeLongLongName.SomeLongLongName(some_obj,
self.user1
self... |
What exactly does += do in python? | 4,841,436 | 14 | 2011-01-30T06:00:29Z | 4,841,440 | 24 | 2011-01-30T06:02:28Z | [
"python",
"notation",
"shorthand"
] | > **Possible Duplicate:**
> [What does plus equals (+=) do in Python?](http://stackoverflow.com/questions/2347265/what-does-plus-equals-do-in-python)
I need to know what += does in python. It's that simple. I also would appreciate links to definitions of other short hand tools in python. | `+=` adds another value with the variable's value and assigns the new value to the variable.
```
>>> x = 3
>>> x += 2
>>> print x
5
```
`-=`, `*=`, `/=` does similar for subtraction, multiplication and division. |
What exactly does += do in python? | 4,841,436 | 14 | 2011-01-30T06:00:29Z | 4,841,443 | 8 | 2011-01-30T06:03:06Z | [
"python",
"notation",
"shorthand"
] | > **Possible Duplicate:**
> [What does plus equals (+=) do in Python?](http://stackoverflow.com/questions/2347265/what-does-plus-equals-do-in-python)
I need to know what += does in python. It's that simple. I also would appreciate links to definitions of other short hand tools in python. | It adds the right operand to the left. `x += 2` means `x = x + 2`
It can also add elements to a list -- see [this SO thread](http://stackoverflow.com/questions/2347265/what-does-plus-equals-do-in-python). |
What exactly does += do in python? | 4,841,436 | 14 | 2011-01-30T06:00:29Z | 4,841,451 | 9 | 2011-01-30T06:05:29Z | [
"python",
"notation",
"shorthand"
] | > **Possible Duplicate:**
> [What does plus equals (+=) do in Python?](http://stackoverflow.com/questions/2347265/what-does-plus-equals-do-in-python)
I need to know what += does in python. It's that simple. I also would appreciate links to definitions of other short hand tools in python. | `+=` adds a number to a variable, changing the variable itself in the process (whereas `+` would not). Similar to this, there are the following that also modifies the variable:
* `-=`, subtracts a value from variable, setting the variable to the result
* `*=`, multiplies the variable and a value, making the outcome th... |
What exactly does += do in python? | 4,841,436 | 14 | 2011-01-30T06:00:29Z | 4,845,327 | 19 | 2011-01-30T20:31:48Z | [
"python",
"notation",
"shorthand"
] | > **Possible Duplicate:**
> [What does plus equals (+=) do in Python?](http://stackoverflow.com/questions/2347265/what-does-plus-equals-do-in-python)
I need to know what += does in python. It's that simple. I also would appreciate links to definitions of other short hand tools in python. | In Python, += is sugar coating for the **iadd** special method. The **iadd** method of a class can do anything it wants. The list object implements it and uses it to iterate over an iterable object appending each element to itself in the same way that the list's extend method does.
Here's a simple custom class that im... |
convert matrix to image | 4,841,611 | 14 | 2011-01-30T06:55:35Z | 4,841,667 | 10 | 2011-01-30T07:10:49Z | [
"python",
"image",
"matrix"
] | How would I go about going converting a list of lists of ints into a matrix plot in Python?
The example data set is:
```
[[3, 5, 3, 5, 2, 3, 2, 4, 3, 0, 5, 0, 3, 2],
[5, 2, 2, 0, 0, 3, 2, 1, 0, 5, 3, 5, 0, 0],
[2, 5, 3, 1, 1, 3, 3, 0, 0, 5, 4, 4, 3, 3],
[4, 1, 4, 2, 1, 4, 5, 1, 2, 2, 0, 1, 2, 3],
[5, 1, 1, 1, 5, ... | You may try
```
from pylab import *
A = rand(5,5)
figure(1)
imshow(A, interpolation='nearest')
grid(True)
```

[source](http://matplotlib.sourceforge.net/examples/pylab_examples/image_interp.html) |
Python Convert fraction to decimal | 4,841,732 | 6 | 2011-01-30T07:33:28Z | 4,842,318 | 17 | 2011-01-30T10:14:10Z | [
"python"
] | I want to convert 1/2 in python so that when i say print x (where x = 1/2) it returns 0.5
I am looking for the most basic way of doing this, without using any split functions, loops or maps
I have tried float(1/2) but I get 0...
can someone explain me why and how to fix it?
Is it possible to do this without modifyin... | in python 3.x any division returns a float;
```
>>> 1/2
0.5
```
to achieve that in python 2.x, you have to force float conversion:
```
>>> 1.0/2
0.5
```
or to import the division from the "future"
```
>>> from __future__ import division
>>> 1/2
0.5
```
An extra: there is no a built-in fraction type, but there is ... |
Python constructor and default value | 4,841,782 | 48 | 2011-01-30T07:48:22Z | 4,841,812 | 12 | 2011-01-30T07:56:10Z | [
"python",
"constructor",
"default-value"
] | Somehow, in the Node class below, the wordList and adjacencyList variable is shared between all instances of Node.
```
>>> class Node:
... def __init__(self, wordList = [], adjacencyList = []):
... self.wordList = wordList
... self.adjacencyList = adjacencyList
...
>>> a = Node()
>>> b = Node()
>>... | I would try:
```
self.wordList = list(wordList)
```
to force it to make a copy instead of referencing the same object. |
Python constructor and default value | 4,841,782 | 48 | 2011-01-30T07:48:22Z | 4,841,855 | 63 | 2011-01-30T08:06:36Z | [
"python",
"constructor",
"default-value"
] | Somehow, in the Node class below, the wordList and adjacencyList variable is shared between all instances of Node.
```
>>> class Node:
... def __init__(self, wordList = [], adjacencyList = []):
... self.wordList = wordList
... self.adjacencyList = adjacencyList
...
>>> a = Node()
>>> b = Node()
>>... | Mutable default arguments don't generally do what you want. Instead, try this:
```
class Node:
def __init__(self, wordList=None, adjacencyList=None):
if wordList is None:
self.wordList = []
else:
self.wordList = wordList
if adjacencyList is None:
self.... |
Python constructor and default value | 4,841,782 | 48 | 2011-01-30T07:48:22Z | 4,841,873 | 18 | 2011-01-30T08:14:07Z | [
"python",
"constructor",
"default-value"
] | Somehow, in the Node class below, the wordList and adjacencyList variable is shared between all instances of Node.
```
>>> class Node:
... def __init__(self, wordList = [], adjacencyList = []):
... self.wordList = wordList
... self.adjacencyList = adjacencyList
...
>>> a = Node()
>>> b = Node()
>>... | Let's illustrate what's happening here:
```
Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
... def __init__(self, x=[]):
... x.append(1)
...
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> ... |
Python: Easiest way to ignore blank lines when reading a file | 4,842,057 | 20 | 2011-01-30T09:05:20Z | 4,842,070 | 10 | 2011-01-30T09:08:39Z | [
"python"
] | I have some code that reads a file of names and creates a list:
```
names_list = open("names", "r").read().splitlines()
```
Each name is separated by a newline, like so:
```
Allman
Atkinson
Behlendorf
```
I want to ignore any lines that contain only whitespace. I know I can do this by by creating a loop and checki... | You could use list comprehension:
```
with open("names", "r") as f:
names_list = [line.strip() for line in f if line.strip()]
```
**Updated:** Removed unnecessary `readlines()`.
To avoid calling `line.strip()` twice, you can use a generator:
```
names_list = [l for l in (line.strip() for line in f) if l]
``` |
Python: Easiest way to ignore blank lines when reading a file | 4,842,057 | 20 | 2011-01-30T09:05:20Z | 4,842,095 | 31 | 2011-01-30T09:13:49Z | [
"python"
] | I have some code that reads a file of names and creates a list:
```
names_list = open("names", "r").read().splitlines()
```
Each name is separated by a newline, like so:
```
Allman
Atkinson
Behlendorf
```
I want to ignore any lines that contain only whitespace. I know I can do this by by creating a loop and checki... | I would stack generator expressions:
```
with open(filename) as f_in:
lines = (line.rstrip() for line in f_in) # All lines including the blank ones
lines = (line for line in lines if line) # Non-blank lines
```
Now, `lines` is all of the non-blank lines. This will save you from having to call strip on the lin... |
Getting processor information in Python | 4,842,448 | 12 | 2011-01-30T10:44:19Z | 4,842,467 | 18 | 2011-01-30T10:47:26Z | [
"python",
"processor"
] | Using Python is there any way to find out the processor information... (I need the name)
I need the name of the processor that the interpreter is running on. I checked the sys module but it has no such function.
I can use an external library also if required. | The [platform.processor()](http://docs.python.org/library/platform.html#platform.processor) function returns the processor name as a string.
```
>>> import platform
>>> platform.processor()
'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel'
``` |
Merge lists that share common elements | 4,842,613 | 17 | 2011-01-30T11:21:15Z | 4,842,897 | 10 | 2011-01-30T12:31:16Z | [
"python",
"list",
"join",
"merge",
"boolean-expression"
] | My input is a list of lists. Some of them share common elements, eg.
```
L = [['a','b','c'],['b','d','e'],['k'],['o','p'],['e','f'],['p','a'],['d','g']]
```
I need to merge all lists, that share a common element, and repeat this procedure as long as there are no more lists with the same item. I thought about using bo... | Algorithm:
1. take first set A from list
2. for each other set B in the list do if B has common element(s) with A join B into A; remove B from list
3. repeat 2. until no more overlap with A
4. put A into outpup
5. repeat 1. with rest of list
So you might want to use sets instead of list. The following program should ... |
Merge lists that share common elements | 4,842,613 | 17 | 2011-01-30T11:21:15Z | 4,843,408 | 15 | 2011-01-30T14:29:37Z | [
"python",
"list",
"join",
"merge",
"boolean-expression"
] | My input is a list of lists. Some of them share common elements, eg.
```
L = [['a','b','c'],['b','d','e'],['k'],['o','p'],['e','f'],['p','a'],['d','g']]
```
I need to merge all lists, that share a common element, and repeat this procedure as long as there are no more lists with the same item. I thought about using bo... | You can see your list as a notation for a Graph, ie `['a','b','c']` is a graph with 3 nodes connected to each other. The problem you are trying to solve is finding [connected components in this graph](http://en.wikipedia.org/wiki/Connectivity_%28graph_theory%29).
You can use [NetworkX](http://networkx.lanl.gov/index.h... |
Boxplot with variable length data in matplotlib | 4,842,805 | 6 | 2011-01-30T12:10:24Z | 4,843,662 | 12 | 2011-01-30T15:24:31Z | [
"python",
"matplotlib",
"boxplot"
] | I have collected some data in a textfile and want to create a boxplot.
But this datafile contains rows of variable length, for example.
1.2, 2.3, 3.0, 4.5
1.1, 2.2, 2.9
for equal length I could just do
PW = numpy.loadtxt("./learning.dat")
matplotlib.boxplot(PW.T);
How do I handle variable lenght data lines? | Just use a list of arrays or lists. `boxplot` will take any sort of sequence (Well, anything that has a `__len__`, anyway. It won't work with generators, etc.).
E.g.:
```
import matplotlib.pyplot as plt
x = [[1.2, 2.3, 3.0, 4.5],
[1.1, 2.2, 2.9]]
plt.boxplot(x)
plt.show()
```
 but that doesn't work. | Try
```
list2 = [x for x in list1 if x != []]
```
If you want to get rid of everything that is "falsy", e.g. empty strings, empty tuples, zeros, you could also use
```
list2 = [x for x in list1 if x]
``` |
Python: How to remove empty lists from a list? | 4,842,956 | 18 | 2011-01-30T12:49:03Z | 4,843,063 | 26 | 2011-01-30T13:10:48Z | [
"python",
"list"
] | I have a list with empty lists in it:
```
list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
```
How can I remove the empty lists so that I get:
```
list2 = ['text', 'text2', 'moreText']
```
I tried list.remove('') but that doesn't work. | You can use `filter()` instead of a list comprehension:
```
list2 = filter(None, list1)
```
If `None` is used as first argument to `filter()`, it filters out every value in the given list, which is `False` in a boolean context. This includes empty lists.
It might be slightly faster than the list comprehension, becau... |
What's the Python equivalent of x = (10<n) ? 10 : n; | 4,843,058 | 4 | 2011-01-30T13:09:59Z | 4,843,075 | 7 | 2011-01-30T13:12:36Z | [
"python",
"ternary"
] | I was wondering what the equivalent in python to this would be:
```
n = 100
x = (10 < n) ? 10 : n;
print x;
```
For some reason this does not work in Python. I know I can use an if statement but I was just curious if there is some shorter syntax.
Thanks. | Here is the [ternary operator](http://en.wikipedia.org/wiki/Ternary_operation#Python) in Python (also know as [conditional expressions](http://docs.python.org/reference/expressions.html#conditional-expressions) in the docs).
```
x if cond else y
``` |
What's the Python equivalent of x = (10<n) ? 10 : n; | 4,843,058 | 4 | 2011-01-30T13:09:59Z | 4,843,077 | 17 | 2011-01-30T13:13:03Z | [
"python",
"ternary"
] | I was wondering what the equivalent in python to this would be:
```
n = 100
x = (10 < n) ? 10 : n;
print x;
```
For some reason this does not work in Python. I know I can use an if statement but I was just curious if there is some shorter syntax.
Thanks. | ```
x = min(n, 10)
```
Or, more generally:
```
x = 10 if 10<n else n
``` |
Check if a Python list item contains a string inside another string | 4,843,158 | 238 | 2011-01-30T13:29:48Z | 4,843,170 | 7 | 2011-01-30T13:31:58Z | [
"python"
] | I have a list:
```
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
```
and want to search for items that contain the string `'abc'`. How can I do that?
```
if 'abc' in my_list:
```
would check if `'abc'` exists in the list but it is a part of `'abc-123'` and `'abc-456'`, `'abc'` does not exist on its own. So... | ```
x = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]
``` |
Check if a Python list item contains a string inside another string | 4,843,158 | 238 | 2011-01-30T13:29:48Z | 4,843,172 | 403 | 2011-01-30T13:32:06Z | [
"python"
] | I have a list:
```
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
```
and want to search for items that contain the string `'abc'`. How can I do that?
```
if 'abc' in my_list:
```
would check if `'abc'` exists in the list but it is a part of `'abc-123'` and `'abc-456'`, `'abc'` does not exist on its own. So... | If you only want to check for the presence of `abc` in any string in the list, you could try
```
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
# whatever
```
If you really want to get all the items containing `abc`, use
```
matching = [s for s in some_list if "ab... |
Check if a Python list item contains a string inside another string | 4,843,158 | 238 | 2011-01-30T13:29:48Z | 4,843,190 | 41 | 2011-01-30T13:34:52Z | [
"python"
] | I have a list:
```
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
```
and want to search for items that contain the string `'abc'`. How can I do that?
```
if 'abc' in my_list:
```
would check if `'abc'` exists in the list but it is a part of `'abc-123'` and `'abc-456'`, `'abc'` does not exist on its own. So... | Use `filter` to get at the elements that have `abc`.
```
>>> lst = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> print filter(lambda x: 'abc' in x, lst)
['abc-123', 'abc-456']
```
You can also use a list comprehension.
```
>>> [x for x in lst if 'abc' in x]
```
By the way, don't use the word `list` as a variable... |
Check if a Python list item contains a string inside another string | 4,843,158 | 238 | 2011-01-30T13:29:48Z | 4,843,206 | 7 | 2011-01-30T13:38:19Z | [
"python"
] | I have a list:
```
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
```
and want to search for items that contain the string `'abc'`. How can I do that?
```
if 'abc' in my_list:
```
would check if `'abc'` exists in the list but it is a part of `'abc-123'` and `'abc-456'`, `'abc'` does not exist on its own. So... | ```
for item in my_list:
if item.find("abc") != -1:
print item
``` |
Check if a Python list item contains a string inside another string | 4,843,158 | 238 | 2011-01-30T13:29:48Z | 7,836,601 | 15 | 2011-10-20T13:24:03Z | [
"python"
] | I have a list:
```
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
```
and want to search for items that contain the string `'abc'`. How can I do that?
```
if 'abc' in my_list:
```
would check if `'abc'` exists in the list but it is a part of `'abc-123'` and `'abc-456'`, `'abc'` does not exist on its own. So... | This is quite an old question, but I offer this answer because the previous answers do not cope with items in the list that are not strings (or some kind of iterable object). Such items would cause the entire list comprehension to fail with an exception.
To gracefully deal with such items in the list by skipping the n... |
Check if a Python list item contains a string inside another string | 4,843,158 | 238 | 2011-01-30T13:29:48Z | 25,102,099 | 12 | 2014-08-03T06:00:27Z | [
"python"
] | I have a list:
```
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
```
and want to search for items that contain the string `'abc'`. How can I do that?
```
if 'abc' in my_list:
```
would check if `'abc'` exists in the list but it is a part of `'abc-123'` and `'abc-456'`, `'abc'` does not exist on its own. So... | Just throwing this out there: if you happen to need to match against more than one string, for example `abc` and `def`, you can put combine two list comprehensions as follows:
```
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
```
Output:
```
['abc-123', 'def-456', 'abc-4... |
How to check if type of a variable is string? | 4,843,173 | 266 | 2011-01-30T13:32:19Z | 4,843,178 | 387 | 2011-01-30T13:33:17Z | [
"python",
"string",
"variables",
"types"
] | Is there a way to check if the type of a variable in python is string.. like
```
isinstance(x,int);
```
for integer values? | In Python 2.x, you would do
```
isinstance(s, basestring)
```
`basestring` is the [abstract superclass](https://docs.python.org/2/library/functions.html#basestring) of `str` and `unicode`. It can be used to test whether an object is an instance of `str` or `unicode`.
Equivalent code:
```
isinstance(s, (str, unicode... |
How to check if type of a variable is string? | 4,843,173 | 266 | 2011-01-30T13:32:19Z | 4,847,186 | 9 | 2011-01-31T02:40:45Z | [
"python",
"string",
"variables",
"types"
] | Is there a way to check if the type of a variable in python is string.. like
```
isinstance(x,int);
```
for integer values? | The type module also exists if you are checking more than ints and strings.
<http://docs.python.org/library/types.html> |
How to check if type of a variable is string? | 4,843,173 | 266 | 2011-01-30T13:32:19Z | 13,467,120 | 10 | 2012-11-20T05:30:13Z | [
"python",
"string",
"variables",
"types"
] | Is there a way to check if the type of a variable in python is string.. like
```
isinstance(x,int);
```
for integer values? | Edit based on better answer below. Go down about 3 answers and find out about the coolness of basestring.
Old answer:
Watch out for unicode strings, which you can get from several places, including all COM calls in Windows.
```
if isinstance(target, str) or isinstance(target, unicode):
``` |
How to check if type of a variable is string? | 4,843,173 | 266 | 2011-01-30T13:32:19Z | 20,612,311 | 108 | 2013-12-16T13:36:49Z | [
"python",
"string",
"variables",
"types"
] | Is there a way to check if the type of a variable in python is string.. like
```
isinstance(x,int);
```
for integer values? | I know this is an old topic, but being the first one shown on google and given that I don't find any of the answers satisfactory, I'll leave this here for future reference:
[six](https://pypi.python.org/pypi/six) is a Python 2 and 3 compatibility library which already covers this issue. You can then do something like ... |
How to check if type of a variable is string? | 4,843,173 | 266 | 2011-01-30T13:32:19Z | 26,828,432 | 14 | 2014-11-09T12:57:50Z | [
"python",
"string",
"variables",
"types"
] | Is there a way to check if the type of a variable in python is string.. like
```
isinstance(x,int);
```
for integer values? | In Python 3.x or Python 2.7.6
```
if type(x) == str:
``` |
Any pointers on using Ropevim? Is it a usable library? | 4,843,493 | 27 | 2011-01-30T14:47:47Z | 7,509,343 | 12 | 2011-09-22T03:48:59Z | [
"python",
"vim",
"refactoring",
"rope"
] | Rope is a refactoring library for Python and RopeVim is a Vim plugin which calls into Rope.
The idea of using RopeVim seems great to me, ***is there any documentation on "getting started" with RopeVim?***
I've followed what documentation there is: <https://bitbucket.org/agr/ropevim/src/tip/README.txt>
I suppose I'm ... | For basic renaming, hover your vim cursor over the variable/method/etc that you wish to rename and then type:
```
:RopeRename <enter>
```
From there it should be self-explanatory. It asks for the root path to the project you wish to do the renaming in. Then it asks you for the new name. Then you can preview/confirm c... |
python string splitting | 4,843,841 | 7 | 2011-01-30T16:00:26Z | 4,843,861 | 13 | 2011-01-30T16:04:43Z | [
"python",
"string",
"split"
] | I have an input string like this: `a1b2c30d40` and I want to tokenize the string to: `a, 1, b, 2, c, 30, d, 40`.
I know I can read each character one by one and keep track of the previous character to determine if I should tokenize it or not (2 digits in a row means don't tokenize it) but is there a more pythonic way ... | ```
>>> re.split(r'(\d+)', 'a1b2c30d40')
['a', '1', 'b', '2', 'c', '30', 'd', '40', '']
```
On the pattern: as the comment says, `\d` means "match one digit", `+` is a modifier that means "match one or more", so `\d+` means "match as much digits as possible". This is put into a group `()`, so the entire pattern in con... |
Python: the mechanism behind list comprehension | 4,844,010 | 6 | 2011-01-30T16:33:04Z | 4,844,442 | 9 | 2011-01-30T17:47:29Z | [
"python",
"implementation",
"list-comprehension",
"language-implementation"
] | When using list comprehension or the `in` keyword in a for loop context, i.e:
```
for o in X:
do_something_with(o)
```
or
```
l=[o for o in X]
```
* How does the mechanism behind `in` works?
* Which functions\methods within `X` does it call?
* If `X` can comply to more than one method, what's the precedence?
* ... | The, afaik, complete and correct answer.
`for`, both in for loops and list comprehensions, calls `iter()` on `X`. `iter()` will return an iterable if `X` either has an `__iter__` method or a `__getitem__` method. If it implements both, `__iter__` is used. If it has neither you get `TypeError: 'Nothing' object is not i... |
What's wrong with this cumulative sum? | 4,844,399 | 4 | 2011-01-30T17:40:10Z | 4,844,420 | 7 | 2011-01-30T17:43:01Z | [
"python"
] | I'm trying to get [1,3,6] as the result. Am I missing something really obvious? The error I got is: `IndexError: list index out of range`
```
def cumulative_sum(n):
cum_sum = []
y = 0
for i in n:
y += n[i]
cum_sum.append(y)
print cum_sum
a = [1,2,3]
cumulative_sum(a)
``` | The problem is with your loop:
```
for i in n:
y += n[i]
```
The `for` loop is iterating over the *values* of `n`, not the indexes. Change `y += n[i]` to `y += i`.
The exception is raised on the third pass through the loop (when i is 3), since 3 is not in the bounds of the array (valid indexes are [0-2]).
If yo... |
What's wrong with this cumulative sum? | 4,844,399 | 4 | 2011-01-30T17:40:10Z | 4,844,424 | 8 | 2011-01-30T17:44:28Z | [
"python"
] | I'm trying to get [1,3,6] as the result. Am I missing something really obvious? The error I got is: `IndexError: list index out of range`
```
def cumulative_sum(n):
cum_sum = []
y = 0
for i in n:
y += n[i]
cum_sum.append(y)
print cum_sum
a = [1,2,3]
cumulative_sum(a)
``` | ```
def cumulative_sum(n):
cum_sum = []
y = 0
for i in n: # <--- i will contain elements (not indices) from n
y += i # <--- so you need to add i, not n[i]
cum_sum.append(y)
print cum_sum
a = [1,2,3]
cumulative_sum(a)
```
Arrays are zero-based in Python, so when you confused `n[i]`... |
How can I disable Django's admin in a deployed project, but keep it for local development? | 4,845,239 | 16 | 2011-01-30T20:17:06Z | 4,845,279 | 28 | 2011-01-30T20:23:56Z | [
"python",
"django"
] | I am currently working in a Django project for which I need access to the admin area for local development, but want to disable it in the deployed site (for security reasons, among others).
How can I achieve this programmatically (*ie* using `settings.py`).
Many thanks. | First, establish a scheme so that your production server can have different settings than your development servers. A simple way to do that is with a source-control-ignored local\_settings.py file, but there are many fancier ways to do it.
Then, in your settings.py file, put:
```
ADMIN_ENABLED = True
```
and in your... |
Hide curly braces in C# | 4,846,359 | 4 | 2011-01-30T23:38:34Z | 4,846,412 | 9 | 2011-01-30T23:46:48Z | [
"c#",
"python",
"coding-style"
] | After getting back into Python, I'm starting to notice and be annoyed more and more by my C# coding style requiring braces everywhere
```
if (...)
{
return ...;
}
else
{
return ...;
}
```
preferring the (subjective) much cleaner looking python counter-part
```
if ...:
return ...
else
return .... | Sorry, but if you're coding in C# and doing more than just simple single-expression blocks, you're going to have to suck it up. Python's "indent-denotes-scope" grammar may be nice, but it's Python, not C#. |
Maketrans in Python 2.6 | 4,846,802 | 8 | 2011-01-31T01:08:24Z | 4,846,810 | 13 | 2011-01-31T01:09:39Z | [
"python",
"python-3.x"
] | I have got this nice little method to remove control characters from a string. Unfortunatelly, it does not work in Python 2.6 (only in Python 3.1). It states:
> ```
> mpa = str.maketrans(dict.fromkeys(control_chars))
> ```
>
> AttributeError: type object 'str' has no attribute 'maketrans'
```
def removeControlCharact... | In Python 2.6, `maketrans` is in [the string module](http://docs.python.org/library/string.html#string.maketrans). Same with Python 2.7.
So instead of `str.maketrans`, you'd first `import string` and then use `string.maketrans`. |
Maketrans in Python 2.6 | 4,846,802 | 8 | 2011-01-31T01:08:24Z | 4,847,311 | 7 | 2011-01-31T03:14:59Z | [
"python",
"python-3.x"
] | I have got this nice little method to remove control characters from a string. Unfortunatelly, it does not work in Python 2.6 (only in Python 3.1). It states:
> ```
> mpa = str.maketrans(dict.fromkeys(control_chars))
> ```
>
> AttributeError: type object 'str' has no attribute 'maketrans'
```
def removeControlCharact... | For this instance, there is no need for `maketrans` for either byte strings or Unicode strings:
```
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> delete_chars=''.join(chr(i) for i in xrange(32))
>>> '\x00... |
Embedding an Image in a Tkinter Canvas widget using PIL | 4,846,838 | 4 | 2011-01-31T01:16:28Z | 4,847,113 | 7 | 2011-01-31T02:22:03Z | [
"python",
"image",
"embed",
"tkinter",
"python-imaging-library"
] | I'm trying to embed an image in a Tkinter canvas using PIL, and for some reason it's not displaying. Any Ideas?
There are no errors or warnings. Just a blank Tk window.
My code:
```
import Tkinter
from PIL import ImageTk, Image
class image_manip(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init... | My guess is that the image is getting garbage-collected. Try saving a reference to "i" (eg: self.image=i) |
Python piping output between two subprocesses | 4,846,891 | 7 | 2011-01-31T01:27:04Z | 4,846,923 | 11 | 2011-01-31T01:35:33Z | [
"python",
"unix",
"subprocess"
] | I'm working on some code that will DD a block device over SSH, and I'm wanting to do this with subprocess so that I can monitor the status of DD during the transfer (killing the dd process with SIGUSR1 to get its current state, and reading that using selects).
The command that I'm trying to implement would be somethin... | ```
from subprocess import Popen, PIPE
dd_process = Popen(['dd', 'if=/dev/sda'], stdout=PIPE)
ssh_process = Popen(['ssh', 'root@example.com', 'dd','of=/dev/sda'],stdin=dd_process.stdout, stdout=PIPE)
dd_process.stdout.close() # enable write error in dd if ssh dies
out, err = ssh_process.communicate()
```
This is way t... |
assign a attribute using getattr | 4,847,177 | 7 | 2011-01-31T02:39:11Z | 4,847,197 | 9 | 2011-01-31T02:43:25Z | [
"python",
"getattr"
] | I try to assign value to attributes of some calss
like the following:
```
for name in dir(modelType):
if request.get(name):
getattr(model, name) = request.get(name)
```
but get the excption:
"can't assign to function call"
how can I change attributes without knowing them at complie time? | You use `setattr()` to assign values to attributes.
See: <http://docs.python.org/library/functions.html#setattr> |
Creating Blank Images in Python (allowing pixel by pixel manipulation) | 4,847,287 | 6 | 2011-01-31T03:06:02Z | 4,847,408 | 10 | 2011-01-31T03:37:09Z | [
"python",
"image-processing",
"image-manipulation",
"tkinter",
"python-imaging-library"
] | I have this code here that creates a Tkinter Canvas widget, then embeds an image within it.
```
import Tkinter
from PIL import ImageTk, Image
class image_manip(Tkinter.Tk):
def __init__(self):
Tkinter.Tk.__init__(self)
self.configure(bg='red')
self.ImbImage = Tkinter.Canvas(self, highl... | To create a new blank image (other than opening one), you can use the `Image.new(...)` method in place of your `Image.open(...)`. It is described [here](http://effbot.org/imagingbook/image.htm).
Then call `self.i.put(...)` to do pixel-by-pixel manipulation. (i is the PhotoImage object as in your example)
Here's some ... |
use django: from "python manage.py shell" to python script | 4,847,469 | 28 | 2011-01-31T03:52:46Z | 4,847,493 | 20 | 2011-01-31T03:59:28Z | [
"python",
"django"
] | I can move to a python project directory (say c:\www\myproject) and then issue
```
python manage.py shell
```
and then I can use all modules from django project, say the following piece of commands from the shell command:
```
import settings
from django.template import Template, Context
t=Template("My name is {... | Try using a [Django management command](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#writing-custom-django-admin-commands) instead.
```
# myproject/myapp/management/commands/my_command.py
from django.core.management.base import NoArgsCommand
from django.template import Template, Context
from... |
use django: from "python manage.py shell" to python script | 4,847,469 | 28 | 2011-01-31T03:52:46Z | 4,847,676 | 10 | 2011-01-31T04:38:24Z | [
"python",
"django"
] | I can move to a python project directory (say c:\www\myproject) and then issue
```
python manage.py shell
```
and then I can use all modules from django project, say the following piece of commands from the shell command:
```
import settings
from django.template import Template, Context
t=Template("My name is {... | Try put these two lines at the beginning of your script:
```
from django.conf import settings
settings.configure() # check django source for more detail
# now you can import other django modules
from django.template import Template, Context
``` |
use django: from "python manage.py shell" to python script | 4,847,469 | 28 | 2011-01-31T03:52:46Z | 5,334,927 | 22 | 2011-03-17T04:40:39Z | [
"python",
"django"
] | I can move to a python project directory (say c:\www\myproject) and then issue
```
python manage.py shell
```
and then I can use all modules from django project, say the following piece of commands from the shell command:
```
import settings
from django.template import Template, Context
t=Template("My name is {... | This method is [deprecated](https://docs.djangoproject.com/en/dev/releases/1.4/#django-core-management-setup-environ) in Django 1.4. Use `django.conf.settings.configure()` instead
(see @adiew's answer for example code).
Old method follows.
Put this at the beginning of your script
```
from django.core.management impo... |
Copying a symbolic link in Python | 4,847,615 | 15 | 2011-01-31T04:24:42Z | 4,847,660 | 24 | 2011-01-31T04:33:47Z | [
"python",
"symlink"
] | I want to copy a file `src` to the destination `dst`, but if `src` happens to be a symbolic link, preserve the link instead of copying the contents of the file. After the copy is performed, `os.readlink` should return the same for both `src` and `dst`.
The module `shutil` has several functions, such as `copyfile`, `co... | Just do
```
def copy(src, dst):
if os.path.islink(src):
linkto = os.readlink(src)
os.symlink(linkto, dst)
else:
shutil.copy(src,dst)
```
[shutil.copytree](http://docs.python.org/library/shutil.html#shutil.copytree) does something similar, but as senderle noted, it's picky about copying... |
Using PIL's ImageDraw Module | 4,847,706 | 2 | 2011-01-31T04:44:23Z | 4,847,755 | 7 | 2011-01-31T04:57:34Z | [
"python",
"image-processing",
"image-manipulation",
"tkinter",
"python-imaging-library"
] | I'm trying to do individual pixel manipulation using PIL's ImageDraw Module. The code bellow is supposed to create Tkinter canvas widget. Then open an image, change one pixel's color to red, then embed the image in the canvas widget. However, it doesn't seem to be working.
My Code:
```
import Tkinter
from PIL import ... | Your problem is you're reassigning `im` to multiple things.
```
im = Image.open(r'C:\Python26\Suite\test.png')
im = ImageDraw.Draw(im)
im = im.point((0, 0), fill="red")
```
When you call `ImageTk.PhotoImage(im)`, the function expects a PIL image object, but you've already assigned `im` to the result of the `point()` ... |
Adding css class to field on validation error in django | 4,847,913 | 8 | 2011-01-31T05:32:12Z | 4,850,577 | 10 | 2011-01-31T11:57:47Z | [
"python",
"django",
"django-forms",
"django-validation",
"django-media"
] | I am using Django's modelform and its really good. How can I highlight the actual text box (e.g. border:red ) if there is a validation error associated with it. Basically what i want is to add a class (error) if there is a validation error to a field. | What about defining error\_css\_class?
<http://docs.djangoproject.com/en/dev/ref/forms/api/#styling-required-or-erroneous-form-rows>?
```
class MyForm(ModelForm):
error_css_class = 'error'
``` |
How to move a local django made site into another machine? | 4,850,311 | 7 | 2011-01-31T11:25:16Z | 4,850,611 | 12 | 2011-01-31T12:01:52Z | [
"python",
"django"
] | I have tried hard searching for the solution to my query but with no luck. I have made a website using django in my local machine. Now i want to install the same django made website in another machine. MySQL is the database i am using. How do i move the local django made website into another machine? If this question h... | To set up the same Django site on a different machine, you can just copy the code across. When you try and run it, you'll get errors if anything isn't set up correctly which you can resolve one by one. A few errors you are likely to get are:
1. Make sure Python is installed on the new box
2. Make sure Django and any o... |
PyQt4 : How can i toggle the "Stay On Top" behavior? | 4,850,584 | 3 | 2011-01-31T11:58:51Z | 4,850,757 | 10 | 2011-01-31T12:18:47Z | [
"python",
"pyqt4",
"stayontop"
] | I want to create an app, where the user will decide it the main window will stay always on top of the other apps.
In PyQt4 it is easy to create a window that will stay always on top. This is covered here : [PyQt: Always on top](http://stackoverflow.com/questions/1925015/pyqt-always-on-top)
What I want to have a widge... | This should disable it:
```
window.setWindowFlags(window.windowFlags() & ~QtCore.Qt.WindowStaysOnTopHint)
```
This should enable it:
```
window.setWindowFlags(window.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
``` |
Connecting to MySQL from Django | 4,851,138 | 4 | 2011-01-31T12:59:30Z | 4,851,180 | 7 | 2011-01-31T13:04:55Z | [
"python",
"mysql",
"django"
] | its my first project with django..i already tried the connection with sqlite.but now m using django's connection with mysql n m getting following error...
```
D:\project\wogma>manage.py syncdb
Traceback (most recent call last):
File "D:\project\wogma\manage.py", line 11, in <module>
execute_manager(settings)
... | You are trying to specify a database at a file path (which would work for SQLite). MySQL needs a database name (e.g. 'wogma'). You'll have to follow the instructions to install MySQL, create a new user and database etc. It appears you're on Windows, so I can't help any more than that. |
Python closure: Write to variable in parent scope | 4,851,463 | 48 | 2011-01-31T13:37:55Z | 4,851,555 | 53 | 2011-01-31T13:45:18Z | [
"python",
"closures",
"scope",
"python-2.x"
] | I have the following code inside a function:
```
stored_blocks = {}
def replace_blocks(m):
block = m.group(0)
block_hash = sha1(block)
stored_blocks[block_hash] = block
return '{{{%s}}}' % block_hash
num_converted = 0
def convert_variables(m):
name = m.group(1)
num_converted += 1
return '<... | **Problem:** This is because Python's scoping rules are demented. The presence of the `+=` assignment operator marks the target, `num_converted`, as local to the enclosing function's scope, and there is no sound way in Python 2.x to access just one scoping level out from there. Only the `global` keyword can lift variab... |
Python closure: Write to variable in parent scope | 4,851,463 | 48 | 2011-01-31T13:37:55Z | 4,852,073 | 19 | 2011-01-31T14:34:22Z | [
"python",
"closures",
"scope",
"python-2.x"
] | I have the following code inside a function:
```
stored_blocks = {}
def replace_blocks(m):
block = m.group(0)
block_hash = sha1(block)
stored_blocks[block_hash] = block
return '{{{%s}}}' % block_hash
num_converted = 0
def convert_variables(m):
name = m.group(1)
num_converted += 1
return '<... | (see below for the edited answer)
You can use something like:
```
def convert_variables(m):
name = m.group(1)
convert_variables.num_converted += 1
return '<%%= %s %%>' % name
convert_variables.num_converted = 0
```
This way, `num_converted` works as a C-like "static" variable of the convert\_variable me... |
String of values separated by commas or semicolons into a Python list | 4,854,341 | 3 | 2011-01-31T18:02:53Z | 4,854,402 | 10 | 2011-01-31T18:09:06Z | [
"python",
"string",
"list"
] | I'm reading a list of email addresses from a config file. The addresses can be delimited by comma or semicolon - e.g.,
```
billg@microsoft.com,steve@apple.com, dhh@37signals.com
billg@microsoft.com;steve@apple.com; dhh@37signals.com
```
I'd like to get rid of any whitespace around the email addresses too.
I need to... | In this case I whould use the re module
```
>>> import re
>>>
>>> data = "billg@microsoft.com;steve@apple.com; dhh@37signals.com"
>>> stuff = re.split(r"\s*[,;]\s*", data.strip())
``` |
Parsing CSV data from memory in Python | 4,855,523 | 5 | 2011-01-31T20:07:16Z | 4,855,569 | 7 | 2011-01-31T20:11:47Z | [
"python",
"csv"
] | Is there a way to parse CSV data in Python when the data is not in a file? I'm storing CSV data in my database and I'd like to parse it. I'm looking for something analogous to Ruby's `CSV.parse`. I know Python has a `CSV` class but everything I've seen in the docs seems to deal with files as opposed to in-memory CSV da... | There is no special distinction for files about the python [csv](http://docs.python.org/library/csv.html) module. You can use [StringIO](http://docs.python.org/library/stringio.html) to wrap your strings as file-like objects. |
How to turn Unicode strings into regular strings? | 4,855,645 | 80 | 2011-01-31T20:18:39Z | 4,855,663 | 105 | 2011-01-31T20:19:54Z | [
"python",
"string",
"type-conversion"
] | How do I remove the `u'` in `u'somestring'` in the printed output in Python?
Assuming that 'a' is a Unicode string 'Hello World',
```
print a
```
prints the following message:
```
u'Hello World'
``` | Call `str()` on a unicode string to create a regular string. String literals with a `u` prepended e.g. `u'string'` are unicode strings.
Example:
```
>>> a = u'hello'
>>> a
u'hello'
>>> str(a)
'hello'
``` |
How to turn Unicode strings into regular strings? | 4,855,645 | 80 | 2011-01-31T20:18:39Z | 4,855,717 | 37 | 2011-01-31T20:27:34Z | [
"python",
"string",
"type-conversion"
] | How do I remove the `u'` in `u'somestring'` in the printed output in Python?
Assuming that 'a' is a Unicode string 'Hello World',
```
print a
```
prints the following message:
```
u'Hello World'
``` | Encode your unicode string to convert to type str in the encoding you want to use:
```
>>> u'hello world'.encode('utf-8')
'hello world'
>>>> u'hellò world'.encode('utf-8')
'hell\xc3\xb2 world'
>>> u'hellò world'.encode('latin-1')
'hell\xf2 world'
``` |
Get mouse deltas using Python! (in Linux) | 4,855,823 | 5 | 2011-01-31T20:38:24Z | 12,286,738 | 7 | 2012-09-05T17:27:10Z | [
"python",
"linux",
"mouse",
"hid"
] | I know that Linux gives out a 9-bit 2's compliment data out of the /dev/input/mice. I also know that you can get that data via /dev/hidraw0 where hidraw is your USB device giving out raw data from the HID. I know the data sent is the delta of the movement (displacement) rather than position. By the by I can also view g... | I'm on a basic device and not having access to X or ... so event.py doesn't works.
So here's my simpler decode code part to interpret from "deprecated" '/dev/input/mice':
```
import struct
file = open( "/dev/input/mice", "rb" );
def getMouseEvent():
buf = file.read(3);
button = ord( buf[0] );
bLeft = button &... |
When will Django support Python 3.x? | 4,855,997 | 26 | 2011-01-31T20:55:56Z | 8,460,547 | 28 | 2011-12-10T22:49:20Z | [
"python",
"django",
"python-3.x"
] | I understand Django can only be run on Python 2.7 or below. When will it run on Python 3.1 or above? I see that Django 1.3 is coming out, does that support Python 3.x? | Currently Django has passed py3k test.
The last port has been made available at [Vinay Sajip repository in BitBucket](https://bitbucket.org/vinay.sajip/django/)
Check also news at [PortingDjangoTo3k](http://wiki.python.org/moin/PortingDjangoTo3k)
And, finally, news from PyCon 2012:
[Django 1.5 will bring experime... |
How do I pipe a subprocess call in Python to a text file? | 4,856,583 | 35 | 2011-01-31T21:54:25Z | 4,856,655 | 12 | 2011-01-31T22:01:45Z | [
"python",
"linux",
"shell",
"unix",
"subprocess"
] | ```
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])
```
RIght now I have a script that I run. When I run it and it hits this line, it starts printing stuff because run.sh has prints in it.
How do I pipe this to a text file also? (And also print, if possible) | The options for `popen` can be used in `call`
```
args,
bufsize=0,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=None,
close_fds=False,
shell=False,
cwd=None,
env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0
```
So...
```
subprocess.call(["/home/myuser/run.sh", "... |
How do I pipe a subprocess call in Python to a text file? | 4,856,583 | 35 | 2011-01-31T21:54:25Z | 4,856,684 | 57 | 2011-01-31T22:04:47Z | [
"python",
"linux",
"shell",
"unix",
"subprocess"
] | ```
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])
```
RIght now I have a script that I run. When I run it and it hits this line, it starts printing stuff because run.sh has prints in it.
How do I pipe this to a text file also? (And also print, if possible) | If you want to write the output to a file you can use the [stdout](http://docs.python.org/library/subprocess.html#subprocess.Popen)-argument of `subprocess.call`.
It takes `None`, `subprocess.PIPE`, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The sec... |
Javascript equivalent of Python's zip function | 4,856,717 | 92 | 2011-01-31T22:08:11Z | 7,260,572 | 21 | 2011-08-31T16:53:42Z | [
"javascript",
"python",
"functional-programming",
"transpose"
] | Is there a javascript equivalent of Python's zip function? That is, given two arrays of equal lengths create an array of pairs.
For instance, if I have three arrays that look like this:
```
var array1 = [1, 2, 3];
var array2 = ['a','b','c'];
var array3 = [4, 5, 6];
```
The output array should be:
```
var output arr... | Check out the library [Underscore](http://underscorejs.org/).
> Underscore provides over 100 functions that support both your favorite workaday functional helpers: map, filter, invoke â as well as more specialized goodies: function binding, javascript templating, creating quick indexes, deep equality testing, and so... |
Javascript equivalent of Python's zip function | 4,856,717 | 92 | 2011-01-31T22:08:11Z | 10,284,006 | 93 | 2012-04-23T15:58:42Z | [
"javascript",
"python",
"functional-programming",
"transpose"
] | Is there a javascript equivalent of Python's zip function? That is, given two arrays of equal lengths create an array of pairs.
For instance, if I have three arrays that look like this:
```
var array1 = [1, 2, 3];
var array2 = ['a','b','c'];
var array3 = [4, 5, 6];
```
The output array should be:
```
var output arr... | **2016 update:**
Here's a snazzier Ecmascript 6 version:
```
zip= rows=>rows[0].map((_,c)=>rows.map(row=>row[c]))
```
Illustration:
```
> zip([['row0col0', 'row0col1', 'row0col2'],
['row1col0', 'row1col1', 'row1col2']]);
[["row0col0","row1col0"],
["row0col1","row1col1"],
["row0col2","row1col2"]]
```
(and ... |
Javascript equivalent of Python's zip function | 4,856,717 | 92 | 2011-01-31T22:08:11Z | 17,907,974 | 9 | 2013-07-28T11:58:58Z | [
"javascript",
"python",
"functional-programming",
"transpose"
] | Is there a javascript equivalent of Python's zip function? That is, given two arrays of equal lengths create an array of pairs.
For instance, if I have three arrays that look like this:
```
var array1 = [1, 2, 3];
var array2 = ['a','b','c'];
var array3 = [4, 5, 6];
```
The output array should be:
```
var output arr... | In addition to ninjagecko's excellent and comprehensive answer, all it takes to zip two JS-arrays into a "tuple-mimic" is:
```
//Arrays: aIn, aOut
Array.prototype.map( aIn, function(e,i){return [e, aOut[i];]})
```
**Explanation:**
Since Javascript doesn't have a `tuples` type, functions for tuples, lists and sets w... |
Limiting Memory Use in a *Large* Django QuerySet | 4,856,882 | 16 | 2011-01-31T22:31:37Z | 5,188,179 | 14 | 2011-03-04T00:01:25Z | [
"python",
"django",
"memory-management",
"django-queryset"
] | I have a task which needs to be run on 'most' objects in my database once every some period of time (once a day, once a week, whatever). Basically this means that I have some query that looks like this running in it's own thread.
```
for model_instance in SomeModel.objects.all():
do_something(model_instance)
```
... | So what I actually ended up doing is building something that you can 'wrap' a QuerySet in. It works by making a deepcopy of the QuerySet, using the slice syntax--e.g., `some_queryset[15:45]`--but then it makes another deepcopy of the original QuerySet when the slice has been completely iterated through. This means that... |
Limiting Memory Use in a *Large* Django QuerySet | 4,856,882 | 16 | 2011-01-31T22:31:37Z | 9,328,492 | 8 | 2012-02-17T12:48:57Z | [
"python",
"django",
"memory-management",
"django-queryset"
] | I have a task which needs to be run on 'most' objects in my database once every some period of time (once a day, once a week, whatever). Basically this means that I have some query that looks like this running in it's own thread.
```
for model_instance in SomeModel.objects.all():
do_something(model_instance)
```
... | You can't simply use Model.objects.all().iterator() because it will fetch all the elements on you table at once. You can't also simply go with the Model.objects.all()[offset:offset+pagesize] way, because it will catch your results. Any of those will exceed your memory limit.
I've tried to mix both solutions, and it wo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.