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 |
|---|---|---|---|---|---|---|---|---|---|
Find all files in directory with extension .txt in Python | 3,964,681 | 696 | 2010-10-19T01:09:13Z | 3,971,553 | 11 | 2010-10-19T18:41:18Z | [
"python",
"file-io"
] | How can I find all files in directory with the extension `.txt` in python? | Here's more versions of the same that produce slightly different results:
### [glob.iglob()](http://docs.python.org/library/glob.html#glob.iglob)
```
import glob
for f in glob.iglob("/mydir/*/*.txt"): # generator, search immediate subdirectories
print f
```
### glob.glob1()
```
print glob.glob1("/mydir", "*.tx... |
Find all files in directory with extension .txt in Python | 3,964,681 | 696 | 2010-10-19T01:09:13Z | 14,001,395 | 14 | 2012-12-22T08:47:24Z | [
"python",
"file-io"
] | How can I find all files in directory with the extension `.txt` in python? | path.py is another alternative: <https://github.com/jaraco/path.py>
```
from path import path
p = path('/path/to/the/directory')
for f in p.files(pattern='*.txt'):
print f
``` |
Find all files in directory with extension .txt in Python | 3,964,681 | 696 | 2010-10-19T01:09:13Z | 24,743,304 | 14 | 2014-07-14T18:29:41Z | [
"python",
"file-io"
] | How can I find all files in directory with the extension `.txt` in python? | ```
import os
path = 'mypath/path'
files = os.listdir(path)
files_txt = [i for i in files if i.endswith('.txt')]
``` |
Polymorphism in Python | 3,964,929 | 3 | 2010-10-19T02:32:20Z | 3,964,946 | 7 | 2010-10-19T02:37:20Z | [
"python",
"methods",
"polymorphism"
] | ```
class File(object):
def __init__(self, filename):
if os.path.isfile(filename):
self.filename = filename
self.file = open(filename, 'rb')
self.__read()
else:
raise Exception('...')
def __read(self):
raise NotImplementedError('Abstract m... | Prefixing an attribute with double underscores doesn't make the attribute private, it simply makes polymorphism impossible because the attribute name gets mangled with the *current* class name. Change it to a single underscore prefix instead. |
Python: determine length of sequence of equal items in list | 3,964,963 | 6 | 2010-10-19T02:44:47Z | 3,964,975 | 10 | 2010-10-19T02:48:33Z | [
"python",
"list",
"count"
] | I have a list as follows:
```
l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
```
I want to determine the length of a sequence of equal items, i.e for the given list I want the output to be:
```
[(0, 6), (1, 6), (0, 4), (2, 3)]
```
(or a similar format).
I thought about using a `defaultdict` but it counts the occurren... | You almost surely want to use [itertools.groupby](http://docs.python.org/library/itertools.html#itertools.groupby):
```
l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
answer = []
for key, iter in itertools.groupby(l):
answer.append((key, len(list(iter))))
# answer is [(0, 6), (1, 6), (0, 4), (2, 3)]
```
If you want... |
Python - Function has a list as argument. How to return another list without changing the first? | 3,964,967 | 2 | 2010-10-19T02:45:59Z | 3,964,980 | 10 | 2010-10-19T02:49:21Z | [
"python",
"return-value",
"function-declaration"
] | I'm pretty new in Python (and programming as a whole). I'm pretty sure the answer to this is obvious, but I really don't know what to do.
```
def do_play(value, slot, board):
temp=board
(i,j) = slot
temp[i][j] = value
return temp
```
board is a list of lists. value is an integer. slot is and integer t... | `temp=board` does not make a new board. It makes the `temp` variable reference the very same list as `board`. So changing `temp[i][j]` changes `board[i][j]` too.
To make a copy, use
```
import copy
temp=copy.deepcopy(board)
```
---
Note that `temp=board[:]` makes `temp` refer to a new list (different than `board`, ... |
NetworkX (Python): how to change edges' weight by designated rule | 3,965,360 | 7 | 2010-10-19T04:35:01Z | 4,098,021 | 18 | 2010-11-04T15:05:29Z | [
"python",
"edge",
"networkx",
"weight"
] | I have a weighted graph:
```
F=nx.path_graph(10)
G=nx.Graph()
for (u, v) in F.edges():
G.add_edge(u,v,weight=1)
```
get the nodes list:
```
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
```
I want to change each edge's weight by this rule:
remove one node, such as node 5, clearly, ed... | You can access the edge weight as G[u][v]['weight'] or by iterating over the edge data. So you can e.g.
```
In [1]: import networkx as nx
In [2]: G=nx.DiGraph()
In [3]: G.add_edge(1,2,weight=10)
In [4]: G.add_edge(2,3,weight=20)
In [5]: G[2][3]['weight']
Out[5]: 20
In [6]: G[2][3]['weight']=200
In [7]: G[2][3]['... |
method signature for jacobian func in scipy least squares | 3,965,404 | 8 | 2010-10-19T04:48:03Z | 3,965,515 | 12 | 2010-10-19T05:15:06Z | [
"python",
"numpy",
"scipy",
"least-squares"
] | Can anyone provide an example of providing a Jacobian to a least squares function in scipy? ( <http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html#scipy.optimize.leastsq> )
I can't figure out the method signature they want - they say it should be a function, yet it's very hard to figure out ... | Here's the exponential decay fitting that I got to work with this:
```
import numpy as np
from scipy.optimize import leastsq
def f(var,xs):
return var[0]*np.exp(-var[1]*xs)+var[2]
def func(var, xs, ys):
return f(var,xs) - ys
def dfunc(var,xs,ys):
v = np.exp(-var[1]*xs)
return [v,-var[0]*xs*v,np.ones... |
Using Python's re to swap case | 3,965,880 | 2 | 2010-10-19T06:37:40Z | 3,965,906 | 7 | 2010-10-19T06:41:43Z | [
"python",
"regex"
] | I'm using the re library to normalize some text. One of the things I want to do is replace all uppercase letters in a string with their lower case equivalents. What is the easiest way to do this? | ```
>>> s = "AbcD"
>>> s.lower()
'abcd'
```
There is also a swapcase method if you want that.
See: <http://docs.python.org/library/stdtypes.html#string-methods> |
How to do a multi-level CLI in Python? | 3,966,187 | 4 | 2010-10-19T07:39:18Z | 3,969,818 | 10 | 2010-10-19T15:08:26Z | [
"python",
"command-line-interface",
"tab-completion"
] | I'm trying to do a CLI, preferrably written in Python. I need a multi-level CLI, and I want tab completion.
I looked at the cmd module (from the Python standard library) and readline with the "complete" function (for tab completion).
They both lacked at something, i.e. I haven't figured out how to handle multiple lev... | It works perfectly fine for me with the `cmd` module in Python 2.6.5. Here is the sample code I was using to test this:
```
import cmd
class MyInterpreter(cmd.Cmd):
def do_level1(self, args):
pass
def do_level2_subcommand_1(self, args):
pass
def do_level2_subcommand_2(self, args):
... |
TkInter, slider: how to trigger the event only when the iteraction is complete? | 3,966,303 | 3 | 2010-10-19T07:57:37Z | 16,970,862 | 11 | 2013-06-06T19:45:25Z | [
"python",
"tkinter"
] | I'm using the slider to update my visualization, but the command updateValue is sent everytime I move the slider thumb, even for intermediate values.
Instead I want to trigger it only when I release the mouse button and the interaction is complete.
```
self.slider = tk.Scale(self.leftFrame, from_=0, to=256, orient=tk... | This is quite an ancient question now, but in case anyone stumbles upon this particular problem just use the bind() function and the "ButtonRelease-1" event like so:
```
import Tkinter as tk
class App:
def __init__(self):
self.root = tk.Tk()
self.slider = tk.Scale(self.root, from_=0, to=256,
... |
Difference between "grid" and "pack" geometry managers | 3,966,367 | 7 | 2010-10-19T08:09:25Z | 3,968,033 | 16 | 2010-10-19T11:55:59Z | [
"python",
"python-3.x",
"layout",
"tkinter"
] | What's the main difference between the Tkinter geometry managers `grid` and `pack`?
What do you use for your projects ?
If `grid` is better to align object, what the main purpose of `pack`? | [grid](http://effbot.org/tkinterbook/grid.htm) is used to lay out widgets in a grid. Another answer says it "overlays a graph" which is a bit of a misnomer. It doesn't overlay anything, it merely arranges widgets along row and column boundaries. It is great for creating tables and other structured types of layouts.
[p... |
Meaning of "AttributeError: NoneType object has no attribute tk"? | 3,966,475 | 4 | 2010-10-19T08:24:30Z | 19,165,597 | 8 | 2013-10-03T17:36:27Z | [
"python",
"tkinter"
] | What does the following error message mean?
```
AttributeError: 'NoneType' object has no attribute 'tk'
``` | I have had this problem but found the solution. This problem arises when you declare the variable before you make an instance of Tk().
For example, this will bring the error
```
count = IntVar()
....
....
app = Tk()
```
Solution!! Make the declarations after creating a tkinter application window
```
app = Tk()
....... |
cp -r from_dir/* to_dir with python | 3,966,863 | 5 | 2010-10-19T09:15:14Z | 3,966,941 | 7 | 2010-10-19T09:24:22Z | [
"python",
"directory",
"shutil"
] | Is there an easy way to emulate the command `cp -r from_dir/* to_dir` with python? `shutil.copytree` is not suitable because `to_dir` exists. | Have a look at the source code of `shutil.copytree`, adapt it and use:
```
def copytree(src, dst, symlinks=False, ignore=None):
"""Recursively copy a directory tree using copy2().
The destination directory must not already exist.
If exception(s) occur, an Error is raised with a list of reasons.
If th... |
What's the meaning of '_' in python? | 3,967,231 | 21 | 2010-10-19T10:05:45Z | 3,967,260 | 27 | 2010-10-19T10:08:36Z | [
"python",
"django",
"syntax"
] | When reading source code of Django, I find some statements:
```
class Field(object):
"""Base class for all field types"""
__metaclass__ = LegacyConnection
# Generic field type description, usually overriden by subclasses
def _description(self):
return _(u'Field of type: %(field_type)s') ... | Please read up on Internationalization (i18n)
<http://docs.djangoproject.com/en/dev/topics/i18n/>
The `_` is a commonly-used name for the function that translates strings to another language.
<http://docs.djangoproject.com/en/dev/topics/i18n/translation/#standard-translation>
Also, read all of these related questio... |
What's the meaning of '_' in python? | 3,967,231 | 21 | 2010-10-19T10:05:45Z | 3,969,587 | 13 | 2010-10-19T14:45:50Z | [
"python",
"django",
"syntax"
] | When reading source code of Django, I find some statements:
```
class Field(object):
"""Base class for all field types"""
__metaclass__ = LegacyConnection
# Generic field type description, usually overriden by subclasses
def _description(self):
return _(u'Field of type: %(field_type)s') ... | Not an answer to your case but the more general "What's the meaning of '\_' in python?":
In *interactive mode*, a `_` will return the last result that wasn't assigned to a variable
```
>>> 1 # _ = 1
1
>>> _ # _ = _
1
>>> a = 2
>>> _
1
>>> a # _ = a
2
>>> _ # _ = _
2
>>> list((3,)) # _ = list((3,))
[3]
>>> _ # _ = _
[... |
How to optimize operations on large (75,000 items) sets of booleans in Python? | 3,967,566 | 9 | 2010-10-19T10:51:29Z | 3,967,628 | 7 | 2010-10-19T10:59:26Z | [
"python",
"optimization",
"python-2.6",
"large-data"
] | There's this script called [svnmerge.py](http://svn.apache.org/repos/asf/subversion/trunk/contrib/client-side/svnmerge/svnmerge.py) that I'm trying to tweak and optimize a bit. I'm completely new to Python though, so it's not easy.
The current problem seems to be related to a class called `RevisionSet` in the script. ... | You could try doing it with numpy instead of plain python. I found it to be *very* fast for operations like these.
For example:
```
# Create 1000000 numbers between 0 and 1000, takes 21ms
x = numpy.random.randint(0, 1000, 1000000)
# Get all items that are larger than 500, takes 2.58ms
y = x > 500
# Add 10 to those ... |
Can I gzip JavaScript and CSS files in Django? | 3,968,650 | 4 | 2010-10-19T13:09:25Z | 3,968,792 | 14 | 2010-10-19T13:23:05Z | [
"python",
"django",
"compression",
"gzip",
"static-files"
] | I tried profiling my web application and one of the bottlenecks reported was the lack of gzip compression. I proceeded to install the gzip middleware in Django and got a bit of a boost but a new report shows that it is only gzipping the HTML files i.e. any content processed by Django. Is there a way I could kludge/hack... | Your CSS and JS should *not* be going through Django on your production system. You need to configure Apache (or Nginx, or whatever) to serve these, and when you do so you'll be able to set up gzip compression there, rather than in Django.
And no, compressing and minifying are not the same thing. GZip compression is d... |
How to configure logging to syslog in python? | 3,968,669 | 73 | 2010-10-19T13:11:38Z | 3,968,713 | 8 | 2010-10-19T13:15:29Z | [
"python",
"logging",
"syslog"
] | I can't get my head around Python's `logging` module. My needs are very simple: I just want to log everything to syslog. After reading documentation I came up with this simple test script:
```
import logging
import logging.handlers
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler =... | Is your syslog.conf set up to handle facility=user?
You can set the facility used by the python logger with the facility argument, something like this:
```
handler = logging.handlers.SysLogHandler(facility=SysLogHandler.LOG_DAEMON)
``` |
How to configure logging to syslog in python? | 3,968,669 | 73 | 2010-10-19T13:11:38Z | 3,969,772 | 88 | 2010-10-19T15:03:39Z | [
"python",
"logging",
"syslog"
] | I can't get my head around Python's `logging` module. My needs are very simple: I just want to log everything to syslog. After reading documentation I came up with this simple test script:
```
import logging
import logging.handlers
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler =... | Change the line to this:
```
handler = SysLogHandler(address='/dev/log')
```
This works for me
```
import logging
import logging.handlers
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
my_logger.addHandler(handler)
my_log... |
How to configure logging to syslog in python? | 3,968,669 | 73 | 2010-10-19T13:11:38Z | 9,632,868 | 10 | 2012-03-09T10:56:09Z | [
"python",
"logging",
"syslog"
] | I can't get my head around Python's `logging` module. My needs are very simple: I just want to log everything to syslog. After reading documentation I came up with this simple test script:
```
import logging
import logging.handlers
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler =... | I add a little extra comment just in case it helps anyone because I found this exchange useful but needed this little extra bit of info to get it all working.
To log to a specific facility using SysLogHandler you need to specify the facility value.
Say for example that you have defined:
`local3.* /var/log/mylog`
in ... |
How to configure logging to syslog in python? | 3,968,669 | 73 | 2010-10-19T13:11:38Z | 14,384,415 | 11 | 2013-01-17T17:12:36Z | [
"python",
"logging",
"syslog"
] | I can't get my head around Python's `logging` module. My needs are very simple: I just want to log everything to syslog. After reading documentation I came up with this simple test script:
```
import logging
import logging.handlers
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler =... | You should *always* use the local host for logging, whether to /dev/log or localhost through the TCP stack. This allows the fully RFC compliant and featureful system logging daemon to handle syslog. This eliminates the need for the remote daemon to be functional and provides the enhanced capabilities of syslog daemon's... |
Python: how to substitute and know whether it matched | 3,969,519 | 6 | 2010-10-19T14:39:38Z | 3,969,655 | 12 | 2010-10-19T14:52:34Z | [
"python",
"regex"
] | I know that `re.sub(pattern, repl,text)` can substitute when pattern matches, and then return the substitute
my code is
```
text = re.sub(pattern, repl, text1)
```
I have to define another variable to to check whether it modified
```
text2 = re.sub(pattern, repl, text1)
matches = text2 != text1
text1 = text2
```
an... | Use [`re.subn`](http://docs.python.org/library/re.html#re.subn)
> Perform the same operation as sub(), but return a tuple (new\_string, number\_of\_subs\_made).
and then check the number of replacements that were made. For example:
```
text2, numReplacements = re.subn(pattern, repl, text1)
if numReplacements:
# ... |
AttributeError: 'module' object has no attribute 'urlopen' | 3,969,726 | 43 | 2010-10-19T14:59:01Z | 3,969,809 | 67 | 2010-10-19T15:07:00Z | [
"python",
"python-3.x",
"urllib"
] | I'm trying to use Python to download the HTML source code of a website but I'm receiving this error.
> Traceback (most recent call last):
> File
> "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\DICParser\src\WebDownload.py",
> line 3, in
> file = urllib.urlopen("http://www.python.org")
> AttributeError: 'module' ... | This works in Python 2.x.
For Python 3 look here:
<http://docs.python.org/py3k/library/urllib.request.html?highlight=urllib#urllib.request.urlopen>
```
import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
s = url.read()
#I'm guessing this would output the html source code?
print(s)
... |
How do I return a list as a variable in Python and use in Jinja2? | 3,970,420 | 6 | 2010-10-19T16:19:06Z | 3,971,100 | 9 | 2010-10-19T17:40:36Z | [
"python",
"flask",
"jinja2"
] | I am a very young programmer and I am trying to do something in Python but I'm stuck. I have a list of users in Couchdb (using python couchdb library & Flask framework) who have a username (which is the \_id) and email. I want to use the list of email addresses in a select box in a jinja2 template.
My first problem is... | ```
# assuming you have something such as this:
class User(Document):
email = TextField()
# you can use the .load() method of the User class
users = [User.load(db, uid) for uid in db]
# now you can do this:
for user in users:
print user.id, user.email
# but you're using it in flask so, in your view you can... |
All possible paths from one node to another in a directed tree (igraph) | 3,971,876 | 10 | 2010-10-19T19:17:43Z | 3,973,287 | 12 | 2010-10-19T22:27:05Z | [
"python",
"algorithm",
"igraph",
"directed-acyclic-graphs"
] | I use [python binding](http://igraph.sourceforge.net/doc/python/index.html) to [igraph](http://igraph.sourceforge.net) to represent a directed tree. I would like to find all possible paths from one node in that graph to another one. Unfortunately, I couldn't find a ready to use function in igraph that performs this tas... | You are looking for all paths between one node and another in a directed acyclic graph (DAG).
A tree is always a DAG, but a DAG isn't always a tree. The difference is that a tree's branches are not allowed to join, only divide, while a DAG's branches can flow together, so long as no cycles are introduced.
Your soluti... |
In Python, identify parts of an e-mail address | 3,972,128 | 2 | 2010-10-19T19:47:42Z | 3,972,170 | 9 | 2010-10-19T19:51:53Z | [
"python",
"email"
] | Given a list of e-mail addresses:
```
list = ('First Last <first@example.com>' , 'name@example.org')
```
some of which contain first and last name, others which just contain an e-mail address, how can I loop through the list and extract a first and last name (if they exist), and the email address?
Thanks. | ```
import email.utils
map(email.utils.parseaddr, email_list)
``` |
How to plot on my GUI | 3,972,158 | 7 | 2010-10-19T19:50:38Z | 15,715,828 | 12 | 2013-03-30T06:47:22Z | [
"python",
"matplotlib",
"pyqt",
"pyside",
"qthread"
] | I'm designing a GUI with `PyQt` where I need to display a matplotlib/pylab window when I click on a button that makes the plot of the data from a function I've created. It's like a runtime used in Matlab. I want to keep the matplotlib/pylab window as my window everytime I press that button. | Here is a basic example that will plot three different samples using a `QThread`:
```
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import random
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
from PyQt4 import QtGui, QtCore
class MatplotlibWidget(QtGui.QWidget)... |
How can I get the argument spec on a decorated function? | 3,972,290 | 19 | 2010-10-19T20:09:03Z | 3,972,426 | 11 | 2010-10-19T20:23:28Z | [
"python"
] | I need to determine the argspec (inspect.getargspec) of a function within a decorator:
```
def decor(func):
@wraps(func)
def _decor(*args, **kwargs):
return func(*args, **kwargs)
return _decor
@decor
def my_func(key=1, value=False):
pass
```
I need to be able to inspect the wrapped "my\_func"... | If you use Michele Simionato's [decorator module](http://pypi.python.org/pypi/decorator) to decorate your function,
its `decorator.decorator` will preserve the original function's signature.
```
import inspect
import decorator
@decorator.decorator
def decor(my_func,*args,**kw):
result=my_func(*args,**kw)
retu... |
Multiple constructor with Python | 3,972,333 | 8 | 2010-10-19T20:13:22Z | 3,972,349 | 7 | 2010-10-19T20:15:26Z | [
"python",
"constructor"
] | I have a class A that can be generated from two different ways.
* a = A(path\_to\_xml\_file)
* a = A(listA, listB)
The first method has file path as an input to parse from XML file to get listA, and listB. The second method is given two lists.
I can think of two ways to implement multiple constructor. What do you th... | Make the constructor take the two lists. Write a factory classmethod that parses the XML and returns the object. |
Python variables as keys to dict | 3,972,872 | 27 | 2010-10-19T21:21:47Z | 3,972,978 | 29 | 2010-10-19T21:33:47Z | [
"python",
"dictionary"
] | Is there an easier way to do this in Python (2.7)?: Note: This isn't anything fancy, like putting all local variables into a dictionary. Just the ones I specify in a list.
```
apple = 1
banana = 'f'
carrot = 3
fruitdict = {}
# I want to set the key equal to variable name, and value equal to variable value
# is there ... | ```
for i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]
``` |
Does Python Pickle have an illegal character/sequence I can use as a separator? | 3,973,252 | 5 | 2010-10-19T22:18:22Z | 3,973,289 | 8 | 2010-10-19T22:27:46Z | [
"python",
"pickle"
] | I want to make (and decode) a single string composed of several python pickles.
Is there a character or sequence that is safe to use as a separator in this string?
I should be able to make the string like so:
```
s = pickle.dumps(o1) + PICKLE_SEPARATOR + pickle.dumps(o2) + PICKLE_SEPARATOR + pickle.dumps(o3) ...
```... | It's fine to just catenate the pickles together, Python knows where each one ends
```
>>> import cStringIO as stringio
>>> import cPickle as pickle
>>> o1 = {}
>>> o2 = []
>>> o3 = ()
>>> p = pickle.dumps(o1)+pickle.dumps(o2)+pickle.dumps(o3)
>>> s = stringio.StringIO(p)
>>> pickle.load(s)
{}
>>> pickle.load(s)
[]
>>>... |
Python pretty XML printer for XML string | 3,973,819 | 5 | 2010-10-20T00:04:28Z | 3,974,112 | 10 | 2010-10-20T01:27:01Z | [
"python",
"xml",
"pretty-print"
] | I generate a long and ugly XML string with python, and I need to filter it through pretty printer to look better.
I found [this post](http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python) for python pretty printers, but I have to write the XML string to a file to be read back to use the tools, which... | Here's how to parse from a text string to the lxml structured data type.
```
from lxml import etree
xml_str = "<parent><child>text</child><child>other text</child></parent>"
root = etree.fromstring(xml_str)
print etree.tostring(root, pretty_print=True)
```
Outputs:
```
<parent>
<child>text</child>
<child>other t... |
Understanding dict.copy() - shallow or deep? | 3,975,376 | 200 | 2010-10-20T06:51:25Z | 3,975,388 | 485 | 2010-10-20T06:54:38Z | [
"python"
] | While reading up the documentation for `dict.copy()`, it says that it makes a shallow copy of the dictionary. Same goes for the book I am following (Beazley's Python Reference), which says:
> The m.copy() method makes a shallow
> copy of the items contained in a
> mapping object and places them in a
> new mapping obje... | By "shallow copying" it means the *content* of the dictionary is not copied by value, but just creating a new reference.
```
>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
```
In contrast, a deep copy will copy all con... |
Understanding dict.copy() - shallow or deep? | 3,975,376 | 200 | 2010-10-20T06:51:25Z | 3,975,423 | 12 | 2010-10-20T07:01:02Z | [
"python"
] | While reading up the documentation for `dict.copy()`, it says that it makes a shallow copy of the dictionary. Same goes for the book I am following (Beazley's Python Reference), which says:
> The m.copy() method makes a shallow
> copy of the items contained in a
> mapping object and places them in a
> new mapping obje... | Take this example:
```
original = dict(a=1, b=2, c=dict(d=4, e=5))
new = original.copy()
```
Now let's change a value in the 'shallow' (first) level:
```
new['a'] = 10
# new = {'a': 10, 'b': 2, 'c': {'d': 4, 'e': 5}}
# original = {'a': 1, 'b': 2, 'c': {'d': 4, 'e': 5}}
# no change in original, since ['a'] is an immu... |
Understanding dict.copy() - shallow or deep? | 3,975,376 | 200 | 2010-10-20T06:51:25Z | 3,975,468 | 21 | 2010-10-20T07:09:20Z | [
"python"
] | While reading up the documentation for `dict.copy()`, it says that it makes a shallow copy of the dictionary. Same goes for the book I am following (Beazley's Python Reference), which says:
> The m.copy() method makes a shallow
> copy of the items contained in a
> mapping object and places them in a
> new mapping obje... | It's not a matter of deep copy or shallow copy, none of what you're doing is deep copy.
Here:
```
>>> new = original
```
you're creating a new reference to the the list/dict referenced by original.
while here:
```
>>> new = original.copy()
>>> # or
>>> new = list(original) # dict(original)
```
you're creating a n... |
How to handle multiple forms in google app engine? | 3,976,368 | 2 | 2010-10-20T09:23:58Z | 3,976,759 | 7 | 2010-10-20T10:15:55Z | [
"python",
"google-app-engine",
"web-applications"
] | Say if I have multiple forms with multiple submit button in a single page, can I somehow make all of these buttons work using webapp as backend handler? If not, what are the alternatives? | The framework you use is irrelevant to how you handle forms. You have a couple of options: you can distinguish the forms by changing the URL they submit to - in which case, you can use the same handler or a different handler for each form - or you can distinguish them based on the contents of the form. The easiest way ... |
CSVWriter not saving data to file - WHY? | 3,976,711 | 18 | 2010-10-20T10:09:10Z | 3,976,765 | 27 | 2010-10-20T10:16:40Z | [
"python",
"csv"
] | Python newbie getting a bit frustrated with the csv module. At this rate, it would have been easier if I wrote the file parser myself, but I want to do things the Pythonic way ....
I have written a little python script that should save my data into a CSV file.
Here is a snippet of my code:
```
import csv
wrtr = csv... | Use
```
with open('myfile.csv','wb') as myfile:
wrtr = csv.writer(myfile, delimiter=',', quotechar='"')
for row in rows:
wrtr.writerow([row.field1,row.field2,row.field3])
myfile.flush() # whenever you want
```
or
```
myfile = open('myfile.csv','wb')
wrtr = csv.writer(myfile, delimiter=',', qu... |
App Engine Version, Memcache | 3,976,772 | 5 | 2010-10-20T10:17:30Z | 3,976,845 | 11 | 2010-10-20T10:29:04Z | [
"python",
"google-app-engine"
] | I am developing an App Engine App that uses memcache. Since there is only a single memcache shared among all versions of your app I am potentially sending bad data from a new version to the production version memcache. To prevent this, I think I may append the app version to the memcache key string to allow various ver... | The `os.environ` variable contains a key called `CURRENT_VERSION_ID` that you can use. It's value is composed of the `version` from app.yaml concatenated together with a period and what I suspect is the `api_version`. If I set `version` to 42 it gives me the value of `42.1`. You should have no problems extracting the v... |
NameError: global name is not defined | 3,977,167 | 22 | 2010-10-20T11:17:36Z | 3,977,194 | 29 | 2010-10-20T11:20:04Z | [
"python",
"class",
"namespaces"
] | I'm using Python 2.6.1 on Mac OS X.
I have two simple Python files (below), but when I run
```
python update_url.py
```
I get on the terminal:
```
Traceback (most recent call last):
File "update_urls.py", line 7, in <module>
main()
File "update_urls.py", line 4, in main
db = SqliteDBzz()
NameError: glob... | You need to do:
```
import sqlitedbx
def main():
db = sqlitedbx.SqliteDBzz()
db.connect()
if __name__ == "__main__":
main()
``` |
Sorting a dictionary (with date keys) in Python | 3,977,310 | 10 | 2010-10-20T11:34:39Z | 3,977,387 | 11 | 2010-10-20T11:44:44Z | [
"python",
"dictionary"
] | I have a dictionary. The keys are dates (datetime). I need to sort the dictionary so that the values in the dictionary are sorted by date - so that by iterating through the dictionary, I am processing items in the desired chronological (i.e. date/time) order.
How may I sort such a dictionary by date?
Example:
```
my... | If you're using Python 2.7+ or 3.1+ you could create an [`OrderedDict` from `collections`](http://docs.python.org/library/collections.html#collections.OrderedDict) from a sort of your dictionary and then iterate through that.
```
ordered = OrderedDict(sorted(mydict.items(), key=lambda t: t[0]))
```
However, depending... |
How to delete record from table? | 3,977,570 | 9 | 2010-10-20T12:07:15Z | 30,985,809 | 9 | 2015-06-22T17:05:09Z | [
"python",
"sqlite3",
"python-3.x"
] | I have a problem with deleting a record from sqlite3 database:
```
conn = sqlite3.connect('databaza.db')
c = conn.cursor()
data3 = str(input('Please enter name: '))
mydata = c.execute('DELETE FROM Zoznam WHERE Name=?', (data3,))
conn.commit()
c.close
```
All is good, but delete doesn't work!
Have anybody some idea? | The correct syntax for a [parameterized](https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute) query is:
```
mydata = c.execute("DELETE FROM Zoznam WHERE Name=?", (data3,))
```
Make sure the parameter uses the comma, to make it a python tuple.
This will help prevent SQL Injection which is possible w... |
How to check if the two XML files are equivalent with Python? | 3,978,068 | 3 | 2010-10-20T12:59:40Z | 3,979,895 | 7 | 2010-10-20T16:02:25Z | [
"python",
"xml"
] | How to check if two XML files are equivalent?
For example, the two XML files are the same even though the ordering is different. I need to check if the two XML files content the same textual info disregarding the order.
```
<a>
<b>hello</b>
<c><d>world</d></c>
</a>
<a>
<c><d>world</d></c>
<b>hello</b>
</... | It all depends on your definition of "equivalent".
Assuming you really only care about the text nodes (for example: the `d` tags in your example do not even matter, you only care about the content `word`), you can just make a set of the text nodes of each document, and compare the sets. Using lxml, this could look lik... |
How can I convert a string to an int in Python? | 3,979,077 | 6 | 2010-10-20T14:43:17Z | 3,979,113 | 10 | 2010-10-20T14:45:54Z | [
"python",
"string",
"int"
] | The output I'm getting for my little example app is the following:
```
Welcome to the Calculator!
Please choose what you'd like to do:
0: Addition
1: Subtraction
2: Multiplication
3: Division
4: Quit Application
0
Enter your first number: 1
Enter your second number: 1
Your result is:
11
```
This is because the additi... | ```
>>> a = "123"
>>> int(a)
123
```
Here's some freebie code:
```
def getTwoNumbers():
numberA = raw_input("Enter your first number: ")
numberB = raw_input("Enter your second number: ")
return int(numberA), int(numberB)
``` |
How can I convert a string to an int in Python? | 3,979,077 | 6 | 2010-10-20T14:43:17Z | 3,979,149 | 14 | 2010-10-20T14:49:57Z | [
"python",
"string",
"int"
] | The output I'm getting for my little example app is the following:
```
Welcome to the Calculator!
Please choose what you'd like to do:
0: Addition
1: Subtraction
2: Multiplication
3: Division
4: Quit Application
0
Enter your first number: 1
Enter your second number: 1
Your result is:
11
```
This is because the additi... | Since you're writing a calculator that would presumably also accept floats (`1.5, 0.03`), a more robust way would be to use this simple helper function:
```
def convertStr(s):
"""Convert string to either int or float."""
try:
ret = int(s)
except ValueError:
#Try float.
ret = float(s... |
python: how to sort a complex list on two different keys | 3,979,872 | 5 | 2010-10-20T16:00:18Z | 3,979,919 | 16 | 2010-10-20T16:04:40Z | [
"python",
"sorting"
] | I have a weird list built in the following way:
```
[[name_d, 5], [name_e, 10], [name_a, 5]]
```
and I want to sort it first by the number (desc) and then, if the number is the same, by the name (asc). So the result I would like to have is:
```
[[name_e, 10], [name_a, 5], [name_d, 5]]
```
I tried to think to a lamb... | Sort functions in python allow to pass a function as sort key:
```
l = [[name_d, 5], [name_e, 10], [name_a, 5]]
# copy
l_sorted = sorted(l, key=lambda x: (x[1] * -1, x[0]))
# in place
l.sort(key=lambda x: (x[1] * -1, x[0])
```
*Edits:* 1. Sort order 2. demonstrate copy and in place sorting |
in Python scipting, how do I capture output from subprocess.call to a file | 3,979,888 | 10 | 2010-10-20T16:01:59Z | 3,980,080 | 9 | 2010-10-20T16:23:31Z | [
"python"
] | In my code I have a line similar to this:
```
rval = subprocess.call(["mkdir",directoryName], shell=True)
```
and I can check `rval` to see if it is `0` or `1`, but if it is `1`, I would like to have the text from the command `"A subdirectory or file ben already exists."` in a file format, so I can compare it to anot... | ```
import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()
``` |
in Python scipting, how do I capture output from subprocess.call to a file | 3,979,888 | 10 | 2010-10-20T16:01:59Z | 12,927,564 | 12 | 2012-10-17T05:18:07Z | [
"python"
] | In my code I have a line similar to this:
```
rval = subprocess.call(["mkdir",directoryName], shell=True)
```
and I can check `rval` to see if it is `0` or `1`, but if it is `1`, I would like to have the text from the command `"A subdirectory or file ben already exists."` in a file format, so I can compare it to anot... | The subprocess module has a built in 'check\_output' function for doing this:
```
In [11]: result = subprocess.check_output(['pwd'])
In [12]: print result
/home/vagrant
``` |
How do I use an external .py file? | 3,980,059 | 4 | 2010-10-20T16:19:55Z | 3,980,072 | 8 | 2010-10-20T16:22:20Z | [
"python"
] | I downloaded beautifulsoup.py for use on a little project I'm making. Do I need to import this .py file in my project?
Do I just copy and paste the code somewhere inside my current python script?
Thank you for the help.
I found this but it doesn't say anything regarding Windows.
<http://mail.python.org/pipermail/tut... | If it's in the same directory as your little project, all you should need to do is:
```
import BeautifulSoup
```
If you are keeping it in some other directory, the easiest way to do it is:
```
from sys import path
path.append(path_to_Beautiful_Soup)
import BeautifulSoup
```
Python keeps track of where it is curren... |
How can I use valgrind with Python C++ extensions? | 3,982,036 | 26 | 2010-10-20T20:32:43Z | 6,037,350 | 36 | 2011-05-17T21:26:34Z | [
"c++",
"python",
"valgrind"
] | I have Python extensions implemented on C++ classes. I don't have a C++ target to run valgrind with. I want to use valgrind for memory check.
Can I use valgrind with Python? | Yes, you can use `valgrind` with Python. You just need to use the valgrind suppression file provided by the Python developers, so you don't get a bunch of false positives due to Python's custom memory allocation/reallocation functions.
The valgrind suppression file can be found here: <http://svn.python.org/projects/py... |
How can I use valgrind with Python C++ extensions? | 3,982,036 | 26 | 2010-10-20T20:32:43Z | 7,856,043 | 8 | 2011-10-21T22:38:39Z | [
"c++",
"python",
"valgrind"
] | I have Python extensions implemented on C++ classes. I don't have a C++ target to run valgrind with. I want to use valgrind for memory check.
Can I use valgrind with Python? | In Python 2.7 and 3.2 there is now a `--with-valgrind` compile-time flag that allows the Python interpreter to detect when it runs under valgrind and disables PyMalloc. This should allow you to more accurately monitor your memory allocations than otherwise, as PyMalloc just allocates memory in big chunks. |
Python: How do I redirect this output? | 3,982,577 | 4 | 2010-10-20T21:42:54Z | 3,982,683 | 13 | 2010-10-20T21:58:20Z | [
"python",
"subprocess"
] | I'm calling rtmpdump via subprocess and trying to redirect its output to a file. The problem is that I simply can't redirect it.
I tried first setting up the sys.stdout to the opened file. This works for, say, ls, but not for rtmpdump. I also tried setting the sys.stderr just to make sure and it also didn't work.
I t... | sys.stdout is the python's idea of the parent's output stream.
In any case you want to change the child's output stream.
subprocess.call and subprocess.Popen take named parameters for the output streams.
So open the file you want to output to and then pass that as the appropriate argument to subprocess.
```
f = ope... |
Python Class Decorator | 3,983,378 | 3 | 2010-10-21T00:26:36Z | 3,983,420 | 11 | 2010-10-21T00:34:51Z | [
"python",
"decorator"
] | I am trying to decorate an actual class, using this code:
```
def my_decorator(cls):
def wrap(*args, **kw):
return object.__new__(cls)
return wrap
@my_decorator
class TestClass(object):
def __init__(self):
print "__init__ should run if object.__new__ correctly returns an instance of cls"
... | `__init__` isn't running because `object.__new__` doesn't know to call it. If you change it to
`cls.__call__(*args, **kwargs)`, or better, `cls(*args, **kwargs)`, it should work. Remember that a class is a callable: calling it produces a new instance. Just calling `__new__` returns an instance but doesn't go through th... |
Is there any reason for using classes in Python if there is only one class in the program? | 3,983,520 | 7 | 2010-10-21T00:58:43Z | 3,983,545 | 7 | 2010-10-21T01:08:44Z | [
"python",
"class",
"oop"
] | I've seen some people writing Python code by creating one class and then an object to call all the methods. Is there any advantage of using classes if we don't make use of inheritance, encapsulation etc? Such code seems to me less clean with all these 'self' arguments, which we could avoid. Is this practice an influenc... | One advantage, though not always applicable, is that it makes it easy to extend the program by subclassing the one class. For example I can subclass it and override the method that reads from, say, a csv file to reading an xml file and then instantiate the subclass or original class based on run-time information. From ... |
Django template: Why block in included template can't be overwritten by child template? | 3,983,872 | 9 | 2010-10-21T02:31:10Z | 3,983,977 | 12 | 2010-10-21T03:01:35Z | [
"python",
"django",
"templates",
"include",
"extend"
] | To illustrate my question more clearly, let's suppose I have a include.html template with content:
```
{% block test_block %}This is include{% endblock %}
```
I have another template called parent.html with content like this:
```
This is parent
{% include "include.html" %}
```
Now I create a templated called child... | When you include a template, it renders the template, then includes the rendered content.
From the django docs:
> The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This... |
How to extract PDF fields from a filled out form in Python? | 3,984,003 | 17 | 2010-10-21T03:08:57Z | 3,985,696 | 16 | 2010-10-21T08:48:22Z | [
"python",
"forms",
"pdf"
] | I'm trying to use Python to processes some PDF forms that were filled out and signed using Adobe Acrobat Reader.
I've tried:
* The [pdfminer](http://www.unixuser.org/~euske/python/pdfminer/) demo: it didn't dump any of the filled out data.
* [pyPdf](http://pybrary.net/pyPdf/): it maxed a core for 2 minutes when I tri... | You should be able to do it with [pdfminer](http://www.unixuser.org/~euske/python/pdfminer/), but it will require some delving into the internals of pdfminer and some knowledge about the pdf format (wrt forms of course, but also about pdf's internal structures like "dictionaries" and "indirect objects").
This example ... |
Python: use regular expression to remove the white space from all lines | 3,984,539 | 19 | 2010-10-21T05:26:45Z | 3,984,615 | 20 | 2010-10-21T05:45:22Z | [
"python",
"regex"
] | `^(\s+)` only removes the whitespace from the first line. How do I remove the front whitespace from all the lines? | Python's regex module does not default to [multi-line `^` matching](http://docs.python.org/library/re.html#re.MULTILINE), so you need to specify that flag explicitly.
```
r = re.compile(r"^\s+", re.MULTILINE)
r.sub("", "a\n b\n c") # "a\nb\nc"
# or without compiling (only possible for Python 2.7+ because the flags op... |
How do I send single character ASCII data to a serial port with python | 3,984,602 | 3 | 2010-10-21T05:42:13Z | 3,984,706 | 8 | 2010-10-21T06:05:16Z | [
"python",
"arduino"
] | I'v looked at pyserial but I can't seem to figure out how to do it. I only need to send one at a time? Please help? | Using [pySerial](http://pyserial.sourceforge.net/pyserial_api.html#classes):
Python 2.x:
```
import serial
byte = 42
out = serial.Serial("/dev/ttyS0") # "COM1" on Windows
out.write(chr(byte))
```
Python 3.x:
```
import serial
byte = 42
out = serial.Serial("/dev/ttyS0") # "COM1" on Windows
out.write(bytes(byte))
`... |
Caching static files in Django | 3,984,984 | 4 | 2010-10-21T06:51:32Z | 3,984,992 | 7 | 2010-10-21T06:52:59Z | [
"python",
"django",
"caching"
] | I was profiling the performance of my web application using Google's Page Speed plugin for Firebug and one of the things it says is that I should 'leverage caching' â "The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources".... | Any static files you may have for your page should be served by your web server, e.g. Apache. Django should never be involved unless you have to prevent access of some files to certain people.
Here, [I found an example of how to do it](https://wiki.mozilla.org/Labs/Bespin/ProductionDeployment#Apache_with_mod_wsgi):
`... |
Python "best practice" for lists, dictionary, etc | 3,985,563 | 19 | 2010-10-21T08:27:22Z | 3,985,668 | 27 | 2010-10-21T08:44:54Z | [
"python",
"code-formatting"
] | I have been looking over the [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) documentation for code formatting best practice for large lists and dictionaries, for example,
```
something = {'foo' : 'bar', 'foo2' : 'bar2', 'foo3' : 'bar3'..... 200 chars wide, etc..}
```
or
```
something = {'fo... | My preferred way is:
```
something = {'foo': 'bar',
'foo2': 'bar2',
'foo3': 'bar3',
...
'fooN': 'barN'}
``` |
Python "best practice" for lists, dictionary, etc | 3,985,563 | 19 | 2010-10-21T08:27:22Z | 3,986,429 | 18 | 2010-10-21T10:22:17Z | [
"python",
"code-formatting"
] | I have been looking over the [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) documentation for code formatting best practice for large lists and dictionaries, for example,
```
something = {'foo' : 'bar', 'foo2' : 'bar2', 'foo3' : 'bar3'..... 200 chars wide, etc..}
```
or
```
something = {'fo... | aaronasterling's indentation style is what I prefer. This, and several other styles are explained in [another SO Question](http://stackoverflow.com/questions/1431862/python-bracket-convention). Especially Lennart Regebro's answer gave a nice overview.
But this style was the one most voted for:
```
my_dictionary = {
... |
How to calculate a logistic sigmoid function in Python? | 3,985,619 | 29 | 2010-10-21T08:36:07Z | 3,985,630 | 49 | 2010-10-21T08:37:31Z | [
"python"
] | This is a logistic sigmoid function:

I know x. How can I calculate F(x) in Python now?
Let's say x = 0.458.
F(x) = ? | This should do it:
```
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
```
And now you can test it by calling:
```
>>> sigmoid(0.458)
0.61253961344091512
```
**Update**: Note that the above was mainly intended as a straight one-to-one translation of the given expression into Python code. It is *not* te... |
How to calculate a logistic sigmoid function in Python? | 3,985,619 | 29 | 2010-10-21T08:36:07Z | 25,164,452 | 58 | 2014-08-06T15:32:05Z | [
"python"
] | This is a logistic sigmoid function:

I know x. How can I calculate F(x) in Python now?
Let's say x = 0.458.
F(x) = ? | It is also available in scipy: <http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.logistic.html>
```
In [1]: from scipy.stats import logistic
In [2]: logistic.cdf(0.458)
Out[2]: 0.61253961344091512
```
which is only a costly wrapper (because it allows you to scale and translate the logistic function) o... |
How to calculate a logistic sigmoid function in Python? | 3,985,619 | 29 | 2010-10-21T08:36:07Z | 29,863,846 | 7 | 2015-04-25T10:11:57Z | [
"python"
] | This is a logistic sigmoid function:

I know x. How can I calculate F(x) in Python now?
Let's say x = 0.458.
F(x) = ? | Here's how you would implement the logistic sigmoid in a numerically stable way (as described [here](http://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/)):
```
def sigmoid(x):
"Numerically-stable sigmoid function."
if x >= 0:
z = exp(-x)
return 1 / (1 + z)
else:
z =... |
How to implement "autoincrement" on Google AppEngine | 3,985,812 | 28 | 2010-10-21T09:02:16Z | 3,986,265 | 23 | 2010-10-21T09:59:36Z | [
"python",
"database",
"google-app-engine"
] | I have to label something in a "strong monotone increasing" fashion. Be it Invoice Numbers, shipping label numbers or the like.
1. A number MUST NOT BE used twice
2. Every number SHOULD BE used when exactly all smaller numbers have been used (no holes).
Fancy way of saying: I need to count 1,2,3,4 ...
The number Spac... | If you absolutely have to have sequentially increasing numbers with no gaps, you'll need to use a single entity, which you update in a transaction to 'consume' each new number. You'll be limited, in practice, to about 1-5 numbers generated per second - which sounds like it'll be fine for your requirements. |
How to implement "autoincrement" on Google AppEngine | 3,985,812 | 28 | 2010-10-21T09:02:16Z | 4,056,817 | 7 | 2010-10-30T01:03:55Z | [
"python",
"database",
"google-app-engine"
] | I have to label something in a "strong monotone increasing" fashion. Be it Invoice Numbers, shipping label numbers or the like.
1. A number MUST NOT BE used twice
2. Every number SHOULD BE used when exactly all smaller numbers have been used (no holes).
Fancy way of saying: I need to count 1,2,3,4 ...
The number Spac... | If you drop the requirement that IDs must be strictly sequential, you can use a hierarchical allocation scheme. The basic idea/limitation is that transactions must not affect multiple storage groups.
For example, assuming you have the notion of "users", you can allocate a storage group for each user (creating some glo... |
How to implement "autoincrement" on Google AppEngine | 3,985,812 | 28 | 2010-10-21T09:02:16Z | 4,177,134 | 7 | 2010-11-14T10:41:42Z | [
"python",
"database",
"google-app-engine"
] | I have to label something in a "strong monotone increasing" fashion. Be it Invoice Numbers, shipping label numbers or the like.
1. A number MUST NOT BE used twice
2. Every number SHOULD BE used when exactly all smaller numbers have been used (no holes).
Fancy way of saying: I need to count 1,2,3,4 ...
The number Spac... | The [gaetk - Google AppEngine Toolkit](https://github.com/mdornseif/appengine-toolkit) now comes with a simple library function to get a number in a sequence. It is based on Nick Johnson's transactional approach and can be used quite easily as a foundation for Martin von Löwis' sharding approach:
```
>>> from gaeth.s... |
How do I write text in subscript in the axis labels and the legend? | 3,985,827 | 12 | 2010-10-21T09:03:51Z | 4,044,008 | 16 | 2010-10-28T14:47:46Z | [
"python",
"matplotlib"
] | I have the following axis labels and legend.
```
plt.ylabel("ratio_2")
plt.xlabel("n_1")
plt.legend(('alpha_1','alpha_2' ), loc = 'best',shadow = True)
``` | Put dollar signs around the formula: `plt.xlabel("$n_1$")` |
Django query filter combining AND and OR with Q objects don't return the expected results | 3,986,071 | 11 | 2010-10-21T09:35:49Z | 3,989,905 | 11 | 2010-10-21T16:50:22Z | [
"python",
"django",
"django-q"
] | I try to combine AND and OR in a filter using Q objects. It looks like that the | behave like an AND. This is related to the previous annotate which is run in the same query and not as a subquery.
What is the correct way to handle this with Django?
**models.py**
```
class Type(models.Model):
name = models.CharFi... | Try adding parentheses to explicitly specify your grouping? As you already figured out, multiple params to [filter()](http://docs.djangoproject.com/en/dev/ref/models/querysets/#filter-kwargs) are just joined via AND in the underlying SQL.
Originally you had this for the filter:
```
[...].filter(
Q(hide=False) & Q... |
Accessing previous array element in django template for loop | 3,986,183 | 10 | 2010-10-21T09:49:06Z | 3,986,324 | 22 | 2010-10-21T10:08:36Z | [
"python",
"django",
"django-templates"
] | I'm new to django and can't find a way to get this to work in django templates. The idea is to check if previous items first letter is equal with current ones, like so:
```
{% for item in items %}
{% ifequal item.name[0] previous_item.name[0] %}
{{ item.name[0] }}
{% endifequal %}
{{ item.name }}<b... | Use the [`{% ifchanged %}`](https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#ifchanged) tag.
```
{% for item in items %}
{% ifchanged item.name.0 %}
{{ item.name.0 }}
{% endifchanged %}
{% endfor %}
```
Also remember you have to always use dot syntax - brackets are not valid template synt... |
Python: Comparing Lists | 3,986,222 | 6 | 2010-10-21T09:53:56Z | 3,986,239 | 8 | 2010-10-21T09:57:14Z | [
"python",
"list"
] | I have come across a small problem. Say I have two lists:
```
list_A = ['0','1','2']
list_B = ['2','0','1']
```
I then have a list of lists:
```
matrix = [
['56','23','4'],
['45','5','67'],
['1','52','22']
]
```
I then need to iterate through list\_A and list\_B and effectively use them as co-ordinates. For example... | ```
matrix = [
['56','23','4'],
['45','5','67'],
['1','52','22']
]
list_A = ['0','1','2']
list_B = ['2','0','1']
for x in zip(list_A,list_B):
a,b=map(int,x)
print(matrix[a][b])
# 4
# 45
# 52
``` |
How to find the local minima of a smooth multidimensional array in NumPy efficiently? | 3,986,345 | 6 | 2010-10-21T10:11:38Z | 3,986,876 | 11 | 2010-10-21T11:22:30Z | [
"python",
"numpy",
"discrete-mathematics",
"mathematical-optimization"
] | Say I have an array in NumPy containing evaluations of a continuous differentiable function, and I want to find the local minima. There is no noise, so every point whose value is lower than the values of all its neighbors meets my criterion for a local minimum.
I have the following list comprehension which works for a... | The location of the local minima can be found for an array of arbitrary dimension
using [Ivan](http://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710)'s [detect\_peaks function](http://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710), with minor modifica... |
Rename dictionary keys according to another dictionary | 3,986,549 | 3 | 2010-10-21T10:41:05Z | 3,986,568 | 9 | 2010-10-21T10:43:44Z | [
"python",
"dictionary",
"python-3.x"
] | (In Python 3)
I have dictionary `old`. I need to change some of its keys; the keys that need to be changed and the corresponding new keys are stored in a dictionary `change`. What's a good way to do it? Note that there may be an overlap between `old.keys()` and `change.values()`, which requires that I'm careful applyi... | ```
old = {change.get(k,k):v for k,v in old.items()}
``` |
how to round to higher 10's place in python | 3,986,996 | 7 | 2010-10-21T11:39:08Z | 3,987,014 | 12 | 2010-10-21T11:41:04Z | [
"python",
"math"
] | I have a bunch of floats and I want to round them up to the next highest multiple of 10.
For example:
```
10.2 should be 20
10.0 should be 10
16.7 should be 20
94.9 should be 100
```
I only need it to go from the range 0-100. I tried math.ceil() but that only rounds up to the nearest integer.
Thanks in advance. | ```
from math import ceil
def ceil_to_tens(x):
return int(ceil(x / 10.0)) * 10
```
**Edit**: okay, now that I have an undeserved "Nice answer" badge for this answer, I think owe the community with a proper solution using the `decimal` module that does not suffer from these problems :) Thanks to Jeff for pointing ... |
Python: Run function from the command line | 3,987,041 | 124 | 2010-10-21T11:44:25Z | 3,987,107 | 29 | 2010-10-21T11:51:45Z | [
"python",
"function",
"command-line"
] | I have below code in my file:
```
def hello():
return 'Hi :)'
```
How would I run this from the command line? | `python -c 'from myfile import hello; hello()'` where `myfile` must be replaced with the basename of your Python script. (E.g., `myfile.py` becomes `myfile`).
However, if `hello()` is your "permanent" main entry point in your Python script, then the usual way to do this is as follows:
```
def hello():
print "Hi :... |
Python: Run function from the command line | 3,987,041 | 124 | 2010-10-21T11:44:25Z | 3,987,109 | 39 | 2010-10-21T11:52:03Z | [
"python",
"function",
"command-line"
] | I have below code in my file:
```
def hello():
return 'Hi :)'
```
How would I run this from the command line? | Just put `hello()` somewhere below the function and it will execute when you do `python your_file.py`
For a neater solution you can use this:
```
if __name__ == '__main__':
hello()
```
That way the function will only be executed if you run the file, not when you import the file. |
Python: Run function from the command line | 3,987,041 | 124 | 2010-10-21T11:44:25Z | 3,987,113 | 193 | 2010-10-21T11:52:51Z | [
"python",
"function",
"command-line"
] | I have below code in my file:
```
def hello():
return 'Hi :)'
```
How would I run this from the command line? | With the `-c` *(command)* argument (assuming your file is named `foo.py`):
```
$ python -c 'import foo; print foo.hello()'
```
Alternatively, if you don't care about namespace pollution:
```
$ python -c 'from foo import *; print hello()'
```
And the middle ground:
```
$ python -c 'from foo import hello; print hell... |
Python: Run function from the command line | 3,987,041 | 124 | 2010-10-21T11:44:25Z | 29,130,994 | 11 | 2015-03-18T19:25:35Z | [
"python",
"function",
"command-line"
] | I have below code in my file:
```
def hello():
return 'Hi :)'
```
How would I run this from the command line? | I wrote a quick little Python script that is callable from a bash command line. It takes the name of the module, class and method you want to call and the parameters you want to pass. I call it PyRun and left off the .py extension and made it executable with chmod +x PyRun so that I can just call it quickly as follow:
... |
Custom field's to_python not working? - Django | 3,988,171 | 12 | 2010-10-21T13:53:39Z | 3,988,326 | 15 | 2010-10-21T14:07:13Z | [
"python",
"django",
"encryption",
"django-models"
] | I'm trying to implement an encrypted char field.
---
I'm using [pydes](http://twhiteman.netfirms.com/des.html) for encryption
This is what I have:
```
from pyDes import triple_des, PAD_PKCS5
from binascii import unhexlify as unhex
from binascii import hexlify as dohex
class BaseEncryptedField(models.CharField):
... | You've forgotten to set the metaclass:
```
class BaseEncryptedField(models.CharField):
__metaclass__ = models.SubfieldBase
... etc ...
```
As [the documentation explains](http://docs.djangoproject.com/en/1.2/howto/custom-model-fields/#the-subfieldbase-metaclass), `to_python` is only called when the Subfield... |
Problem deleting emails in gmail using imaplib | 3,988,583 | 5 | 2010-10-21T14:34:07Z | 3,989,496 | 7 | 2010-10-21T16:05:55Z | [
"python",
"gmail",
"imap",
"imaplib",
"gmail-imap"
] | I try to remove message from inbox folder and all alright, but when i switched to All Mail folder the removing does not work. `expunge()` method returns `('OK', [None])` and message was not removed:
```
>>>import imaplib
>>>server = imaplib.IMAP4_SSL('imap.gmail.com','993')
>>>server.login('likvidator89@gmail.com','Pa... | As it says on the [gmail blog site](http://gmailblog.blogspot.com/2008/10/new-in-labs-advanced-imap-controls.html), Google's implementation of IMAP is a bit different. When you follow the instructions for getting more usual semantics, does it help?
> There are also some more obscure
> options for those of you who want... |
Problem deleting emails in gmail using imaplib | 3,988,583 | 5 | 2010-10-21T14:34:07Z | 10,229,827 | 11 | 2012-04-19T14:05:47Z | [
"python",
"gmail",
"imap",
"imaplib",
"gmail-imap"
] | I try to remove message from inbox folder and all alright, but when i switched to All Mail folder the removing does not work. `expunge()` method returns `('OK', [None])` and message was not removed:
```
>>>import imaplib
>>>server = imaplib.IMAP4_SSL('imap.gmail.com','993')
>>>server.login('likvidator89@gmail.com','Pa... | it moves all the mail in a given gmail label to the gmail Trash
```
#!usr/bin/python
import email, imaplib
user = 'xxx'
pwd = 'xxx'
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("some_gmail_label")
m.store("1:*",'+X-GM-LABELS', '\\Trash')
m.expunge() # should be useless, but gmail server says ... |
How to find all positions of the maximum value in a list? | 3,989,016 | 67 | 2010-10-21T15:15:25Z | 3,989,029 | 149 | 2010-10-21T15:17:02Z | [
"python",
"list",
"max"
] | I have a list:
```
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
```
max element is 55 (two elements on position 9 and 12)
I need to find on which position(s) the maximum value is situated. Please, help. | ```
a.index(max(a))
```
will tell you the index of the first instance of the largest valued element of list `a`. |
How to find all positions of the maximum value in a list? | 3,989,016 | 67 | 2010-10-21T15:15:25Z | 3,989,032 | 98 | 2010-10-21T15:17:24Z | [
"python",
"list",
"max"
] | I have a list:
```
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
```
max element is 55 (two elements on position 9 and 12)
I need to find on which position(s) the maximum value is situated. Please, help. | ```
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
``` |
How to find all positions of the maximum value in a list? | 3,989,016 | 67 | 2010-10-21T15:15:25Z | 3,990,826 | 13 | 2010-10-21T18:46:51Z | [
"python",
"list",
"max"
] | I have a list:
```
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
```
max element is 55 (two elements on position 9 and 12)
I need to find on which position(s) the maximum value is situated. Please, help. | The chosen answer (and most others) require at least two passes through the list.
Here's a one pass solution which might be a better choice for longer lists.
**Edited:** To address the two deficiencies pointed out by @John Machin. For (2) I attempted to optimize the tests based on guesstimated probability of occurre... |
How to find all positions of the maximum value in a list? | 3,989,016 | 67 | 2010-10-21T15:15:25Z | 3,993,283 | 7 | 2010-10-22T01:29:33Z | [
"python",
"list",
"max"
] | I have a list:
```
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
```
max element is 55 (two elements on position 9 and 12)
I need to find on which position(s) the maximum value is situated. Please, help. | I can't reproduce the @SilentGhost-beating performance quoted by @martineau. Here's my effort with comparisons:
=== maxelements.py ===
```
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c
def ... |
CherryPy combine file and dictionary based configuration | 3,989,763 | 5 | 2010-10-21T16:34:15Z | 3,991,899 | 9 | 2010-10-21T21:01:40Z | [
"python",
"configuration",
"cherrypy"
] | I'm setting up a CherryPy application and would like to have the majority of my configuration settings in a .conf file like this:
```
[global]
server.socketPort = 8080
server.threadPool = 10
server.environment = "production"
```
However I would also like to setup a few with a dictionary in code like this:
```
conf =... | `quickstart` is for quick sites. If you're doing anything as complex as having multiple configs, it's time to graduate. Look at the source code for the quickstart function (it's not scary!): you're going to unpack that into your startup script. So instead of `quickstart`, write this:
```
cherrypy.config.update(conffil... |
best way to integrate erlang and python | 3,990,344 | 26 | 2010-10-21T17:44:42Z | 3,990,836 | 11 | 2010-10-21T18:47:49Z | [
"python",
"erlang"
] | What's the best way to integrate erlang and python?
We need to call python functions in erlang and call erlang functions in python. At this moment we are trying to use SOAP as a intermediate layer between these two languages, but we have a lot of "not compatible" troubles. Could you advise the best way to perform inte... | In my experience, the best is [erlport](http://erlport.org/).
It allows you to build an Erlang port in Python by satisfying the Erlang port protocol. It handles the data compatibility issue by implementing the Erlang external term format. The linked page shows a clear example of how to use it. |
best way to integrate erlang and python | 3,990,344 | 26 | 2010-10-21T17:44:42Z | 3,991,545 | 26 | 2010-10-21T20:18:02Z | [
"python",
"erlang"
] | What's the best way to integrate erlang and python?
We need to call python functions in erlang and call erlang functions in python. At this moment we are trying to use SOAP as a intermediate layer between these two languages, but we have a lot of "not compatible" troubles. Could you advise the best way to perform inte... | As already mentioned with [erlport](http://erlport.org) you can use [Erlang port protocol](http://erlang.org/doc/reference_manual/ports.html) and [term\_to\_binary](http://erlang.org/doc/man/erlang.html#term_to_binary-1)/[binary\_to\_term](http://erlang.org/doc/man/erlang.html#binary_to_term-1) functions on Erlang side... |
Longest increasing subsequence | 3,992,697 | 26 | 2010-10-21T23:04:17Z | 3,992,910 | 7 | 2010-10-21T23:53:22Z | [
"python",
"algorithm",
"language-agnostic"
] | Given an input sequence, what is the best way to find the longest (not necessarily continuous) non-decreasing subsequence.
```
0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 # sequence
1, 9, 13, 15 # non-decreasing subsequence
0, 2, 6, 9, 13, 15 # longest non-deceasing subsequence (not unique)
```
I'm looking... | Here is how to simply find longest increasing/decreasing subsequence in Mathematica:
```
LIS[list_] := LongestCommonSequence[Sort[list], list];
input={0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
LIS[input]
-1*LIS[-1*input]
```
Output:
```
{0, 2, 6, 9, 11, 15}
{12, 10, 9, 5, 3}
```
Mathematica has als... |
Longest increasing subsequence | 3,992,697 | 26 | 2010-10-21T23:04:17Z | 9,832,414 | 16 | 2012-03-23T00:11:44Z | [
"python",
"algorithm",
"language-agnostic"
] | Given an input sequence, what is the best way to find the longest (not necessarily continuous) non-decreasing subsequence.
```
0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 # sequence
1, 9, 13, 15 # non-decreasing subsequence
0, 2, 6, 9, 13, 15 # longest non-deceasing subsequence (not unique)
```
I'm looking... | I just stumbled in this problem, and came up with this Python 3 implementation:
```
def subsequence(seq):
if not seq:
return seq
M = [None] * len(seq) # offset by 1 (j -> j-1)
P = [None] * len(seq)
# Since we have at least one element in our list, we can start by
# knowing that the th... |
Print all variables in a class? - Python | 3,992,803 | 6 | 2010-10-21T23:28:13Z | 3,992,855 | 12 | 2010-10-21T23:38:50Z | [
"python",
"class",
"shelve"
] | I'm making a program that can access data stored inside a class. So for example I have this class:
```
#!/usr/bin/env python
import shelve
cur_dir = '.'
class Person:
def __init__(self, name, score, age=None, yrclass=10):
self.name = name
self.firstname = name.split()[0]
try:
... | ```
print db['han'].__dict__
``` |
ImportError: No module named ***** in python | 3,992,952 | 14 | 2010-10-22T00:02:53Z | 3,992,964 | 12 | 2010-10-22T00:05:24Z | [
"python",
"python-import"
] | I am very new to python, about one month, and am trying to figure out how the importing works in python. I was told that I can import any 'module' that has Python code in it. So I am trying to import a module just to try it out, but I keep getting an 'ImportError: No module named redue'. This is an example of the pytho... | These files are not on sys.path. It should have been though.
If you want to access them from the interpreter, you will need to add the location to sys.path
```
>>> import sys
>>> print sys.path
>>> sys.path.append('C:\\Users\\Cube\\Documents\\Python')
>>> import reduc
```
You could also include the path in environme... |
What does ... mean in numpy code? | 3,993,125 | 5 | 2010-10-22T00:50:15Z | 3,993,156 | 7 | 2010-10-22T00:59:45Z | [
"python",
"numpy"
] | And what is it called? I don't know how to search for it; I tried calling it ellipsis with the Google. I don't mean in interactive output when dots are used to indicate that the full array is not being shown, but as in the code I'm looking at,
`xTensor0[...] = xVTensor[..., 0]`
From my experimentation, it appears to ... | Yes, you're right. It fills in as many `:` as required. The only difference occurs when you use multiple ellipses. In that case, the first ellipsis acts in the same way, but each remaining one is converted to a single `:`. |
python: class override "is" behavior | 3,993,239 | 11 | 2010-10-22T01:22:35Z | 3,993,244 | 21 | 2010-10-22T01:23:56Z | [
"python"
] | I'm writing a class which encapsulates any arbitrary object, including simple types. I want the "is" keyword to operate on the encapsulated value, such as this behavior:
```
Wrapper(True) is True -> True
Wrapper(False) is True -> False
Wrapper(None) is None -> True
Wrapper(1) is 1 -> True
```
Is there any object meth... | No. `is`, `and`, and `or` cannot be overloaded. |
Django: How to override unique_together error message? | 3,993,560 | 9 | 2010-10-22T02:54:26Z | 6,682,124 | 24 | 2011-07-13T16:17:37Z | [
"python",
"django",
"validation"
] | In a model's Meta class, I define a unique\_together. I have a ModelForm based on this model. When I call is\_valid on this ModelForm, an error will automatically raised if unique\_together validation fails. That's all good.
Now my problem is that I'm not satisfied with the default unique\_together error message. I wa... | The nicest way to override these error messages might be to override the `unique_error_message` method on your model. Django calls this method to get the error message whenever it encounters a uniqueness issue during validation.
You can just handle the specific case you want and let all other cases be handled by Djang... |
Django: How to override unique_together error message? | 3,993,560 | 9 | 2010-10-22T02:54:26Z | 22,602,140 | 11 | 2014-03-24T06:05:08Z | [
"python",
"django",
"validation"
] | In a model's Meta class, I define a unique\_together. I have a ModelForm based on this model. When I call is\_valid on this ModelForm, an error will automatically raised if unique\_together validation fails. That's all good.
Now my problem is that I'm not satisfied with the default unique\_together error message. I wa... | You can do [this](https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#considerations-regarding-model-s-error-messages) in Django 1.7
```
class ArticleForm(ModelForm):
class Meta:
error_messages = {
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_label... |
How do I access netstat data in Python? | 3,993,731 | 6 | 2010-10-22T03:42:21Z | 6,244,270 | 13 | 2011-06-05T16:37:27Z | [
"python",
"netstat"
] | I'm trying to need to access/parse all outgoing connections on a particular port number on a Linux machine using a Python script. The simplest implementation seems to be to open a subprocess for netstat and parse its stdout.
I imagine someone somewhere has had this problem before, and am surprised not to find any nets... | If you want to control the connection opened **by a certain process** you can use psutil:
```
>>> p = psutil.Process(1694)
>>> p.name()
'firefox'
>>> p.connections()
[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776), remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
connection(fd=117,... |
Python: Create associative array in a loop | 3,994,345 | 8 | 2010-10-22T06:13:54Z | 3,994,397 | 11 | 2010-10-22T06:22:29Z | [
"python",
"associative-array"
] | I want to create an associative array with values read from a file. My code looks something like this, but its giving me an error saying i can't the indicies must be ints.
Thanks =]
```
for line in open(file):
x=prog.match(line)
myarray[x.group(1)]=[x.group(2)]
``` | ```
myarray = {} # Declares myarray as a dict
for line in open(file, 'r'):
x = prog.match(line)
myarray[x.group(1)] = [x.group(2)] # Adds a key-value pair to the dict
``` |
Checking whole string with a regex | 3,994,493 | 6 | 2010-10-22T06:41:16Z | 3,994,507 | 17 | 2010-10-22T06:44:35Z | [
"python",
"regex"
] | I'm trying to check if a string is a number, so the regex "\d+" seemed good. However that regex also fits "78.46.92.168:8000" for some reason, which I do not want, a little bit of code:
```
class Foo():
_rex = re.compile("\d+")
def bar(self, string):
m = _rex.match(string)
if m != None:
... | `\d+` matches any positive number of digits **within** your string, so it matches the first `78` and succeeds.
Use `^\d+$`.
Or, even better: `"78.46.92.168:8000".isdigit()` |
Does Python re module support word boundaries (\b)? | 3,995,034 | 37 | 2010-10-22T08:21:37Z | 3,995,061 | 45 | 2010-10-22T08:24:58Z | [
"python",
"regex"
] | While trying to learn a little more about regular expressions, a tutorial suggested that you can use the \b to match a word boundary. However, the following snippet in the Python interpreter does not work as expected:
```
>>> x = 'one two three'
>>> y = re.search("\btwo\b", x)
```
y should have been a match object if... | Why don't you try
```
word = 'two'
re.compile(r'\b%s\b' % word, re.I)
```
Output:
```
>>> word = 'two'
>>> k = re.compile(r'\b%s\b' % word, re.I)
>>> x = 'one two three'
>>> y = k.search( x)
>>> y
<_sre.SRE_Match object at 0x100418850>
```
Also forgot to mention, you should be using raw strings in your code
```
>>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.