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 |
|---|---|---|---|---|---|---|---|---|---|
Bug or meant to be: numpy raises "ValueError: too many boolean indices" for repeated boolean indices | 16,071,310 | 7 | 2013-04-17T22:25:39Z | 16,071,470 | 7 | 2013-04-17T22:38:54Z | [
"python",
"numpy",
"multidimensional-array"
] | I am doing some simulations in experimental cosmology, and encountered this problem while working with numpy arrays. I'm new to numpy, so I am not sure if I'm doing this wrong or if it's a bug. I run:
```
Enthought Python Distribution -- www.enthought.com
Version: 7.3-1 (32-bit)
Python 2.7.3 |EPD 7.3-1 (32-bit)| (def... | `t[ t < 8 ]` does indeed give you an array, however, it doesn't give you an array of the same size that you started with. `t < 8` will give a boolean array with the same shape as `t`. When you use that to index `t`, you pull out only the elements where the boolean array is `True` leaving you with a shorter array. When ... |
Non blocking subprocess.call | 16,071,866 | 13 | 2013-04-17T23:15:41Z | 16,071,877 | 15 | 2013-04-17T23:17:03Z | [
"python",
"subprocess"
] | I'm trying to make a non blocking subprocess call to run a slave.py script from my main.py program. I need to pass args from main.py to slave.py once when it(slave.py) is first started via subprocess.call after this slave.py runs for a period of time then exits.
```
main.py
for insert, (list) in enumerate(list, start ... | you should use `subprocess.Popen` instead of `subprocess.call`
Something like:
```
subprocess.Popen(["python", "slave.py"] + sys.argv[1:])
```
From the [docs on `subprocess.call`](http://docs.python.org/2/library/subprocess.html#subprocess.call):
> Run the command described by args. **Wait for command to complete**... |
Non blocking subprocess.call | 16,071,866 | 13 | 2013-04-17T23:15:41Z | 16,071,922 | 10 | 2013-04-17T23:21:29Z | [
"python",
"subprocess"
] | I'm trying to make a non blocking subprocess call to run a slave.py script from my main.py program. I need to pass args from main.py to slave.py once when it(slave.py) is first started via subprocess.call after this slave.py runs for a period of time then exits.
```
main.py
for insert, (list) in enumerate(list, start ... | There's three levels of thoroughness here.
As mgilson says, if you just swap out `subprocess.call` for `subprocess.Popen`, keeping everything else the same, then main.py will not wait for slave.py to finish before it continues. That may be enough by itself. If you care about [zombie processes](http://en.wikipedia.org/... |
search by ObjectId in mongodb with pymongo | 16,073,865 | 22 | 2013-04-18T03:14:19Z | 16,074,920 | 41 | 2013-04-18T05:09:13Z | [
"python",
"mongodb",
"pymongo"
] | I need to search an ObjectId with python using pymongo but I always get this error. Any ideas how to search?
```
import pymongo
from pymongo import MongoClient
from pymongo import ObjectId
gate = collection.find({'_id': ObjectId(modem["dis_imei"])})
print gate
Traceback (most recent call last):
File "C:\Users\... | I use pymongo 2.4.1.
```
from bson.objectid import ObjectId
[i for i in dbm.neo_nodes.find({"_id": ObjectId(obj_id_to_find)})]
``` |
SqlAlchemy: Convert inherited type from one to another | 16,074,042 | 6 | 2013-04-18T03:36:18Z | 21,792,969 | 7 | 2014-02-15T03:21:44Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | Let's say I have two different types both on the same database table (single table inheritance):
```
class Employee(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String, nullable = False)
discriminator = db.Column('type', String)
__mapper_args__ = {'polymorphic_on': disc... | It's kludgy, and it causes a warning, but you can brute-force modify the discriminator column by setting the property:
```
john_smith = session.query(Employee).filter_by(name='john smith').one()
john_smith.discriminator = 'manager'
session.commit()
```
This will cause a warning like,
```
SAWarning: Flushing object <... |
Getting vertical gridlines to appear in line plot in matplotlib | 16,074,392 | 26 | 2013-04-18T04:17:10Z | 16,074,407 | 34 | 2013-04-18T04:19:16Z | [
"python",
"matplotlib",
"pandas"
] | I want to get both horizontal and vertical grid lines on my plot but only the horizontal grid lines are appearing by default. I am using a `pandas.DataFrame` from an sql query in python to generate a line plot with dates on the x-axis. I'm not sure why they do not appear on the dates and I have tried to search for an a... | You may need to give boolean arg in your calls, e.g. use `ax.yaxis.grid(True)` instead of `ax.yaxis.grid()`. Additionally, since you are using both of them you can combine into `ax.grid`, which works on both, rather than doing it once for each dimension.
```
ax = plt.gca()
ax.grid(True)
```
That should sort you out. |
Getting vertical gridlines to appear in line plot in matplotlib | 16,074,392 | 26 | 2013-04-18T04:17:10Z | 25,799,781 | 13 | 2014-09-12T02:23:47Z | [
"python",
"matplotlib",
"pandas"
] | I want to get both horizontal and vertical grid lines on my plot but only the horizontal grid lines are appearing by default. I am using a `pandas.DataFrame` from an sql query in python to generate a line plot with dates on the x-axis. I'm not sure why they do not appear on the dates and I have tried to search for an a... | `plt.gca().xaxis.grid(True)` proved to be the solution for me |
Global variables across multiple files in python | 16,075,512 | 3 | 2013-04-18T05:58:26Z | 16,076,029 | 8 | 2013-04-18T06:32:23Z | [
"python",
"scope",
"python-module"
] | I have a modules.py file :
```
global dns_server_ip
def SetVnetGlobalParameters():
dns_server_ip = '192.168.3.120'
```
And Iâm importing this file in say abc.py file
```
from modules import *
SetVnetGlobalParameters()
print(dns_server_ip)
```
But âdns\_server\_ipâ is still not accessible.
I want to set g... | As per your question I understand you are the beginner to the python.
While importing the modules you have use just module name and don't need to include the extension or suffix(py) and in your code you miss the starting single quote .
Here is your modified code:
it is modules.py
```
dns_server_ip = ''
def SetVnetGl... |
How to remove delete icon in one2many tree view | 16,075,761 | 4 | 2013-04-18T06:14:44Z | 16,075,884 | 8 | 2013-04-18T06:23:36Z | [
"python",
"xml",
"openerp"
] | Please advice me on this.need to remove delete icon.but need to create and edit records.
if i set it as readonly then unable to edit also.so what is the better way to implement this
 | Add `delete="false"` in `tree` tag.
```
<tree string="My Tree" delete="false">
```
This will remove delete option from `one2many` tree view. |
Implementing Google's DiffMatchPatch API for Python 2/3 | 16,075,864 | 5 | 2013-04-18T06:22:19Z | 16,086,633 | 10 | 2013-04-18T15:09:12Z | [
"python",
"diff"
] | I want to write a simple diff application in Python using [Google's Diff Match Patch APIs](http://code.google.com/p/google-diff-match-patch/).
I'm quite new to Python, so I want an example of how to use the Diff Match Patch API for semantically comparing two paragraphs of text. I'm not too sure of how to go about using... | Google's [**diff-match-patch API**](https://code.google.com/p/google-diff-match-patch/wiki/API) is the same for all languages that it is implemented in (Java, JavaScript, Dart, C++, C#, Objective C, Lua and Python 2.x or python 3.x). Therefore one can typically use sample snippets in languages other than one's target l... |
Python escape sequence \N{name} not working as per definition | 16,076,775 | 4 | 2013-04-18T07:18:23Z | 16,076,802 | 13 | 2013-04-18T07:19:47Z | [
"python",
"unicode",
"python-2.7",
"unicode-string",
"python-unicode"
] | I am trying to print unicode characters given their name as follows:
```
# -*- coding: utf-8 -*-
print "\N{SOLIDUS}"
print "\N{BLACK SPADE SUIT}"
```
However the output I get is not very encouraging.
The escape sequence is printed as is.
```
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (de... | [Those sequences only work in unicode strings](http://docs.python.org/2/reference/lexical_analysis.html#string-literals), which is the only kind of string Python 3 has. So in Python 2 you need to prefix the string literal with a `u`.
```
>>> print "\N{SOLIDUS} \N{BLACK SPADE SUIT}"
\N{SOLIDUS} \N{BLACK SPADE SUIT}
>>>... |
what does this operator means in django `reduce(operator.and_, query_list)` | 16,076,894 | 9 | 2013-04-18T07:24:40Z | 16,077,068 | 8 | 2013-04-18T07:34:50Z | [
"python",
"django",
"django-queryset"
] | I am reading this questions
[Constructing Django filter queries dynamically with args and kwargs](http://stackoverflow.com/questions/8510057/constructing-django-filter-queries-dynamically-with-args-and-kwargs?rq=1)
I am not able to get what does this operator do
`filter(reduce(operator.or_, argument_list))`
or this... | `filter` is a regular method of Django Model Manager, so there is nothing to explain.
`reduce` is a built-in function similar to the code below:
```
def reduce(func, items):
result = items.pop()
for item in items:
result = func(result, item)
return result
```
Where `func` is a user defined funct... |
Python Serial: How to use the read or readline function to read more than 1 character at a time | 16,077,912 | 7 | 2013-04-18T08:22:19Z | 16,090,601 | 13 | 2013-04-18T18:34:53Z | [
"python",
"serial-port",
"readline",
"pyserial"
] | I'm having trouble to read more than one character using my program, i cant seem to figure out what went wrong with my program, as i'm very new to python.
```
import serial
ser = serial.Serial(
port='COM5',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial... | I see a couple of issues.
First:
ser.read() is only going to return 1 byte at a time.
If you specify a count
```
ser.read(5)
```
it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)
If you know that your input is always properly terminated with EOL characters,
better way is to use
```
ser.readli... |
List the words in a vocabulary according to occurrence in a text corpus , Scikit-Learn | 16,078,015 | 5 | 2013-04-18T08:27:06Z | 16,078,639 | 12 | 2013-04-18T09:01:36Z | [
"python",
"machine-learning",
"scikit-learn",
"text-extraction"
] | I have fitted a `CountVectorizer` to some documents in `scikit-learn`. I would like to see all the terms and their corresponding frequency in the text corpus, in order to select stop-words. For example
```
'and' 123 times, 'to' 100 times, 'for' 90 times, ... and so on
```
Is there any built-in function for this? | If `cv` is your `CountVectorizer` and `X` is the vectorized corpus, then
```
zip(cv.get_feature_names(),
np.asarray(X.sum(axis=0)).ravel())
```
returns a list of `(term, frequency)` pairs for each distinct term in the corpus that the `CountVectorizer` extracted.
(The little `asarray` + `ravel` dance is needed to... |
Reuse OAuth1 authorization tokens with rauth | 16,078,366 | 6 | 2013-04-18T08:46:19Z | 16,082,674 | 13 | 2013-04-18T12:13:35Z | [
"python",
"oauth",
"rauth"
] | I have the following implementation of a `twitter` client using `rauth` (`OAuth1`), based on the `twitter-timeline-cli.py` script in the [rauth](https://github.com/litl/rauth) examples:
```
from rauth.service import OAuth1Service
class TwitterClient:
KNOWN_USERS = {
'user1' : ("xxx", "yyy", "2342354"), #... | I was misunderstanding the whole process. We do not need to save the `request_token`, `request_token_secret` and `pin`, but the `access_token` and the `access_token_secret`.
The process is actually:
1. Use `request_token`, `request_token_secret` and `pin` to get `access_token` and `access_token_secret`
2. Save `acces... |
Calculating gradient with NumPy | 16,078,818 | 12 | 2013-04-18T09:10:16Z | 16,080,427 | 8 | 2013-04-18T10:25:38Z | [
"python",
"numpy",
"scipy",
"gradient"
] | I really can not understand what numpy.gradient function does and how to use it for computation of multivariable function gradient.
For example, I have such a function:
```
def func(q, chi, delta):
return q * chi * delta
```
I need to compute it's 3-dim gradient (in other words, I want to compute partial derivat... | Numpy and Scipy are for numerical calculations. Since you want to calculate the gradient of an analytical function, you have to use the [Sympy](http://sympy.org/en/index.html) package which supports symbolic mathematics. Differentiation is explained [here](http://docs.sympy.org/dev/modules/mpmath/calculus/differentiati... |
Calculating gradient with NumPy | 16,078,818 | 12 | 2013-04-18T09:10:16Z | 16,082,040 | 11 | 2013-04-18T11:44:48Z | [
"python",
"numpy",
"scipy",
"gradient"
] | I really can not understand what numpy.gradient function does and how to use it for computation of multivariable function gradient.
For example, I have such a function:
```
def func(q, chi, delta):
return q * chi * delta
```
I need to compute it's 3-dim gradient (in other words, I want to compute partial derivat... | The problem is, that numpy can't give you the derivatives directly and you have two options:
**With NUMPY**
What you essentially have to do, is to define a grid in three dimension and to evaluate the function on this grid. Afterwards you feed this table of function values to `numpy.gradient` to get an array with the ... |
How to break a long with statement in python | 16,080,049 | 9 | 2013-04-18T10:06:51Z | 16,080,088 | 9 | 2013-04-18T10:08:42Z | [
"python"
] | I have a line of code in python like this:
```
with long_name_function(p) as a, other_long_name_function():
```
and I want to break it in multiple lines, because is too long, I could use backslashes, but they are considered a bad practice. I also could use contextlib.nested, but is deprecated, is there any other alte... | If you want to avoid backslashes, you can alias the long names:
```
lnf = long_name_function
olnf = other_long_name_function
with lnf(p) as a, olnf():
# ...
```
or you could nest the statements:
```
with long_name_function(p) as a:
with other_long_name_function():
pass
```
You do *not* want to use `... |
How to break a long with statement in python | 16,080,049 | 9 | 2013-04-18T10:06:51Z | 16,080,256 | 12 | 2013-04-18T10:17:32Z | [
"python"
] | I have a line of code in python like this:
```
with long_name_function(p) as a, other_long_name_function():
```
and I want to break it in multiple lines, because is too long, I could use backslashes, but they are considered a bad practice. I also could use contextlib.nested, but is deprecated, is there any other alte... | This disregards the premise of the question but I would actually recommend using backslashes in this case:
```
with really_really_long_name_function(p) as f1, \
other_really_really_long_name_function() as f2:
pass
```
As @JonClements said, you can't use brackets or commas in this case, there's no alternat... |
JSON schema validation with arbitrary keys | 16,081,118 | 14 | 2013-04-18T11:00:50Z | 16,081,750 | 20 | 2013-04-18T11:30:34Z | [
"python",
"validation",
"jsonschema"
] | I am using validictory for validating the attached JSON data and schema.
Working so far.
However the data dictionary can have arbitrary string keys (others than 'bp' but). The key 'bp' in the schema here is hard-coded...it can be a string from a given list (enum of string). How do I add the enum definition here for th... | It depends on exactly what you're trying to do.
If you want the same specification, but for a range of properties, you can abstract out the definition:
```
{
"type": "object",
"properties": {
"bp": {"$ref": "#/definitions/categoryList"},
"foo": {"$ref": "#/definitions/categoryList"},
"... |
Setting Application icon in my python Tk base application (On Ubuntu) | 16,081,201 | 2 | 2013-04-18T11:05:06Z | 16,081,908 | 8 | 2013-04-18T11:37:58Z | [
"python",
"ubuntu",
"tkinter"
] | I want to set an image in my GUI application built on Python Tk package.
I tried this code:
```
root.iconbitmap('window.xbm')
```
but it gives me this:
```
root.iconbitmap('window.xbm')
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1567, in wm_iconbitmap
return self.tk.call('wm', 'iconbitmap', self._w, bi... | You want to use `wm iconphoto`. Being more used to Tcl/Tk than Python Tkinter I don't know how that is exposed to you (maybe `root.iconphoto`) but it takes a `tkimage`. In Tcl/Tk:
```
image create photo applicationIcon -file application_icon.png
wm iconphoto . -default applicationIcon
```
In Tk 8.6 you can provide PN... |
Redirect to a URL which contains a 'variable part' in Flask (Python) | 16,081,754 | 6 | 2013-04-18T11:30:44Z | 16,081,950 | 11 | 2013-04-18T11:39:57Z | [
"python",
"redirect",
"python-2.7",
"flask",
"url-routing"
] | I'm trying to redirect to a URL in Flask. The target URL that I'm trying to redirect to has a variable like this `/dashboard/<username>` which has a view as follows,
```
@app.route('/dashboard/<username>')
def dashboard(username):
return render_template('dashboard.html', username=username)
```
How do I redirect t... | You will want to create your URL with `url_for` by giving it the name of your URL, the keyword `arg`, and value for your URL parameter in the following manner:
```
return redirect(url_for('dashboard', username='foo'))
``` |
How to bind Ctrl+/ in python tkinter? | 16,082,243 | 8 | 2013-04-18T11:54:46Z | 16,082,411 | 13 | 2013-04-18T12:02:14Z | [
"python",
"python-2.7",
"key-bindings"
] | ```
<Control-Shift-Key-0>
<Control-Key-plus>
```
works but
```
<Control-Key-/>
```
doesn't.
I am unable to bind ctrl+/ in python. Please help. If there is any documentation of all the possible keys that would be very helpful i couldn't find any. Thanks. | Use `<Control-slash>`:
```
def quit(event):
print "you pressed control-forwardslash"
root.quit()
root = tk.Tk()
root.bind('<Control-slash>', quit) # forward-slash
# root.bind('<Control-backslash>', quit) # backslash
root.mainloop()
```
---
I don't have a link to a complete list of these event names. H... |
Python: How to sort a list of dictionaries by several values? | 16,082,954 | 52 | 2013-04-18T12:27:04Z | 16,082,979 | 68 | 2013-04-18T12:28:26Z | [
"python",
"list",
"sorting"
] | I want to sort a list at first by a value and then by a second value. Is there an easy way to do this? Here is a small example:
```
A = [{'name':'john','age':45},
{'name':'andi','age':23},
{'name':'john','age':22},
{'name':'paul','age':35},
{'name':'john','age':21}]
```
This command is for sorting... | ```
>>> A = [{'name':'john','age':45},
{'name':'andi','age':23},
{'name':'john','age':22},
{'name':'paul','age':35},
{'name':'john','age':21}]
>>> sorted(A, key = lambda user: (user['name'], user['age']))
[{'age': 23, 'name': 'andi'}, {'age': 21, 'name': 'john'}, {'age': 22, 'name': 'john'}, {'age':... |
Python: How to sort a list of dictionaries by several values? | 16,082,954 | 52 | 2013-04-18T12:27:04Z | 16,082,981 | 52 | 2013-04-18T12:28:35Z | [
"python",
"list",
"sorting"
] | I want to sort a list at first by a value and then by a second value. Is there an easy way to do this? Here is a small example:
```
A = [{'name':'john','age':45},
{'name':'andi','age':23},
{'name':'john','age':22},
{'name':'paul','age':35},
{'name':'john','age':21}]
```
This command is for sorting... | ```
from operator import itemgetter
sorted(your_list, key=itemgetter('name', 'age'))
``` |
Alternative to contextlib.nested with variable number of context managers | 16,083,791 | 17 | 2013-04-18T13:05:02Z | 16,084,101 | 19 | 2013-04-18T13:18:10Z | [
"python",
"deprecated",
"with-statement",
"contextmanager"
] | We have code that invokes a variable number of context managers depending on runtime parameters:
```
from contextlib import nested, contextmanager
@contextmanager
def my_context(arg):
print("entering", arg)
try:
yield arg
finally:
print("exiting", arg)
def my_fn(items):
with nested(*... | The new [Python 3 `contextlib.ExitStack` class](http://docs.python.org/3/library/contextlib.html#contextlib.ExitStack) was added as a replacement for `contextlib.nested()` (see [issue 13585](http://bugs.python.org/issue13585)).
It is coded in such a way you can use it in Python 2 directly:
```
import sys
from collect... |
Encoding of headers in MIMEText | 16,084,605 | 5 | 2013-04-18T13:40:51Z | 16,086,792 | 8 | 2013-04-18T15:16:43Z | [
"python",
"email",
"python-3.x",
"mime-message"
] | I'm using MIMEText to create an email from scratch in Python 3.2, and I have trouble creating messages with non-ascii characters in the subject.
For example
```
from email.mime.text import MIMEText
body = "Some text"
subject = "» My Subject" # first char is non-ascii
msg = MIMEText(body,'plain','ut... | I found the solution.
Email headers containing non ascii characters need to be encoded as per [RFC 2047](http://tools.ietf.org/html/rfc2047).
In Python this means using email.header.Header instead of a regular string for header content
(see <http://docs.python.org/2/library/email.header.html>).
The right way to write t... |
Python - Is it okay to pass self to an external function | 16,084,623 | 9 | 2013-04-18T13:41:23Z | 16,084,773 | 14 | 2013-04-18T13:48:02Z | [
"python"
] | I have a class, A, which is inherited by a bunch of other classes. Some of these have a few functions which are similar and it would be nice to have those functions defined somewhere else and called by the classes that need them. But those functions call functions defined in the super class.
```
class A():
def imp... | There is no problem with that whatsoever. Instances of `self` get passed to functions (and methods of other classes) all the time. |
subclassing file objects (to extend open and close operations) in python 3 | 16,085,292 | 16 | 2013-04-18T14:08:57Z | 16,085,543 | 11 | 2013-04-18T14:19:26Z | [
"python",
"python-3.x"
] | Suppose I want to extend the built-in file abstraction with extra operations at `open` and `close` time. In Python 2.7 this works:
```
class ExtFile(file):
def __init__(self, *args):
file.__init__(self, *args)
# extra stuff here
def close(self):
file.close(self)
# extra stuff h... | You could just use a context manager instead. For example this one:
```
class SpecialFileOpener:
def __init__ (self, fileName, someOtherParameter):
self.f = open(fileName)
# do more stuff
print(someOtherParameter)
def __enter__ (self):
return self.f
def __exit__ (self, exc_t... |
subclassing file objects (to extend open and close operations) in python 3 | 16,085,292 | 16 | 2013-04-18T14:08:57Z | 23,796,737 | 7 | 2014-05-22T02:09:50Z | [
"python",
"python-3.x"
] | Suppose I want to extend the built-in file abstraction with extra operations at `open` and `close` time. In Python 2.7 this works:
```
class ExtFile(file):
def __init__(self, *args):
file.__init__(self, *args)
# extra stuff here
def close(self):
file.close(self)
# extra stuff h... | **tl;dr** *Use a context manager. See the bottom of this answer for important cautions about them.*
---
Files got more complicated in Python 3. While there are some methods that can be used on normal user classes, those methods don't work with built-in classes. One way is to mix-in a desired class before instanciatin... |
Python 3.2 vs Python 2.7 code problems | 16,085,679 | 4 | 2013-04-18T14:27:04Z | 16,085,698 | 10 | 2013-04-18T14:27:52Z | [
"python",
"python-2.7",
"python-3.x",
"pygame"
] | I have a code to graph the mandlebrot set using pygame. Here is the code.
```
import pygame, sys, math
from decimal import *
window=pygame.display.set_mode((1000, 1000))
window.fill((255, 255, 255))
pygame.display.update()
winrect=window.get_rect()
hq=3
getcontext().prec=20
colors=((255, 0, 0), (255, 128, 0), (255, 25... | Yes, add this at the top of your file:
```
from __future__ import division
```
Python 2 uses *integer division* (floor division) when using integer inputs by default; Python 3 switched to floating point division even when using integer inputs.
See the [PEP 238](http://www.python.org/dev/peps/pep-0238/), which docume... |
Using supercollider with python | 16,086,667 | 8 | 2013-04-18T15:10:37Z | 16,179,039 | 10 | 2013-04-23T20:57:34Z | [
"python",
"audio",
"mp3",
"sound-synthesis",
"supercollider"
] | I want to do some real time sound processing and i heard about [supercollider](http://supercollider.sourceforge.net/)
and it looks great, but i want to stick to python as far as 'normal' programming is the issue.
Is there any way to load a python script as a module to supercollider or the oposite?
meaning importing ... | I am not aware of a python implementation of SuperCollider, however it is very easy to communicate between SC and Python with [OpenSoundControl](http://opensoundcontrol.org/). Here is some sample code, from a [tutorial](https://github.com/caseyanderson/workshops/blob/master/supercollider/python_SC/python_to_sc.md) alon... |
Python split string by pattern | 16,086,847 | 6 | 2013-04-18T15:19:00Z | 16,087,009 | 11 | 2013-04-18T15:25:37Z | [
"python",
"regex",
"string",
"split"
] | I have strings like `"aaaaabbbbbbbbbbbbbbccccccccccc"`.
The number of the chars can differ and sometimes there can be dash inside the string, like `"aaaaa-bbbbbbbbbbbbbbccccccccccc"`.
Is there any smart way to either split it `"aaaaa"`,`"bbbbbbbbbbbbbb"`,`"ccccccccccc"` and get the indices of were it is split or just ... | Regular expression `MatchObject` results include indices of the match. What remains is to match repeating characters:
```
import re
repeat = re.compile(r'(?P<start>[a-z])(?P=start)+-?')
```
would match only if a given letter character (`a`-`z`) is repeated at least once:
```
>>> for match in repeat.finditer("aaaaab... |
pprint(): how to use double quotes to display strings? | 16,087,662 | 6 | 2013-04-18T15:54:48Z | 16,087,800 | 9 | 2013-04-18T16:01:59Z | [
"python",
"pretty-print",
"pprint"
] | If I print a dictionary using [`pprint`](http://docs.python.org/2/library/pprint.html), it always wraps strings around single quotes (`'`):
```
>>> from pprint import pprint
>>> pprint({'AAA': 1, 'BBB': 2, 'CCC': 3})
{'AAA': 1, 'BBB': 2, 'CCC': 3}
```
Is there any way to tell `pprint` to use double quotes (`"`) inste... | It looks like you are trying to produce JSON; if so, use the [`json` module](http://docs.python.org/2/library/json.html):
```
>>> import json
>>> print json.dumps({'AAA': 1, 'BBB': 2, 'CCC': 3})
{"AAA": 1, "BBB": 2, "CCC": 3}
``` |
Python Concatenate String and Function | 16,088,101 | 3 | 2013-04-18T16:16:11Z | 16,088,214 | 14 | 2013-04-18T16:21:07Z | [
"python",
"string",
"function"
] | Is there a way in Python to cat a string and a function?
For example
```
def myFunction():
a=(str(local_time[0]))
return a
b="MyFunction"+myFunction
```
I get an error that I cannot concatenate a 'str' and 'function' object. | There are two possibilities:
If you are looking for the return value of `myfunction`, then:
```
print 'function: ' + myfunction()
```
If you are looking for the name of `myfunction` then:
```
print 'function: ' + myfunction.__name__
``` |
Logging to specific error log file in scrapy | 16,088,279 | 6 | 2013-04-18T16:24:07Z | 16,092,502 | 9 | 2013-04-18T20:31:40Z | [
"python",
"logging",
"web-scraping",
"scrapy",
"scrapy-spider"
] | I am running a log of scrapy by doing this:
```
from scrapy import log
class MySpider(BaseSpider):
name = "myspider"
def __init__(self, name=None, **kwargs):
LOG_FILE = "logs/spider.log"
log.log.defaultObserver = log.log.DefaultObserver()
log.log.defaultObserver.start()
log.start... | Just let [logging](http://docs.python.org/2/library/logging.html) do the job. Try to use `PythonLoggingObserver` instead of `DefaultObserver`:
* configure two loggers (one for `INFO` and one for `ERROR` messages) directly in python, or via fileconfig, or via dictconfig (see [docs](http://docs.python.org/2/library/logg... |
Beautifulsoup find element by text using `find_all` no matter if there are elements in it | 16,090,324 | 4 | 2013-04-18T18:16:11Z | 16,090,520 | 13 | 2013-04-18T18:29:47Z | [
"python",
"beautifulsoup"
] | For example
```
bs = BeautifulSoup("<html><a>sometext</a></html>")
print bs.find_all("a",text=re.compile(r"some"))
```
returns `[<a>sometext</a>]` but when element searched for has a child, i.e. `img`
```
bs = BeautifulSoup("<html><a>sometext<img /></a></html>")
print bs.find_all("a",text=re.compile(r"some"))
```
i... | You will need to use a hybrid approach since `text=` will fail when an element has child elements as well as text.
```
bs = BeautifulSoup("<html><a>sometext</a></html>")
reg = re.compile(r'some')
elements = [e for e in bs.find_all('a') if reg.match(e.text)]
```
### Background
When BeautifulSoup is searching for ... |
how can I get filenames without directory name | 16,090,670 | 2 | 2013-04-18T18:38:57Z | 16,090,738 | 8 | 2013-04-18T18:43:09Z | [
"python"
] | how can I list only file names in a directory without directory info in the result? I tried
```
for file in glob.glob(dir+filetype):
print file
```
give me result
`/path_name/1.log,/path_name/2.log,....`
but what I do need is file name only: `1.log`, `2.log`, etc. I do not need the directory info in the result. i... | [`os.path.basename`](http://docs.python.org/3/library/os.path.html#os.path.basename):
> Return the base name of pathname `path`. This is the second element of the pair returned by passing `path` to the function `split()`. Note that the result of this function is different from the Unix `basename` program; where `basen... |
python/zip: How to eliminate absolute path in zip archive if absolute paths for files are provided? | 16,091,904 | 14 | 2013-04-18T19:54:28Z | 16,104,667 | 36 | 2013-04-19T12:31:53Z | [
"python",
"zip",
"absolute-path",
"zipfile"
] | I have two files in two different directories, one is `'/home/test/first/first.pdf'`, the other is `'/home/text/second/second.pdf'`. I use following code to compress them:
```
import zipfile, StringIO
buffer = StringIO.StringIO()
first_path = '/home/test/first/first.pdf'
second_path = '/home/text/second/second.pdf'
zi... | The zipfile write() method supports an extra argument (arcname) which is the archive name to be stored in the zip file, so you would only need to change your code with:
```
from os.path import basename
...
zip.write(first_path, basename(first_path))
zip.write(second_path, basename(second_path))
zip.close()
```
When y... |
How To Create a Unique Key For A Dictionary In Python | 16,092,594 | 6 | 2013-04-18T20:37:01Z | 16,092,992 | 7 | 2013-04-18T21:01:28Z | [
"python",
"hash",
"dictionary"
] | What is the best way to generate a unique key for the contents of a dictionary. My intention is to store each dictionary in a document store along with a unique id or hash so that I don't have to load the whole dictionary from the store to check if it exists already or not. *Dictionaries with the same keys and values s... | No - [you can't rely on particular order of elements when converting dictionary to a string](http://stackoverflow.com/questions/8289418/is-the-python-dict-str-function-reliably-sorting-keys).
You can, however, convert it to sorted list of (key,value) tuples, convert it to a string and compute a hash like this:
```
a_... |
How To Create a Unique Key For A Dictionary In Python | 16,092,594 | 6 | 2013-04-18T20:37:01Z | 19,844,637 | 9 | 2013-11-07T19:13:50Z | [
"python",
"hash",
"dictionary"
] | What is the best way to generate a unique key for the contents of a dictionary. My intention is to store each dictionary in a document store along with a unique id or hash so that I don't have to load the whole dictionary from the store to check if it exists already or not. *Dictionaries with the same keys and values s... | I prefer serializing the dict as JSON and hashing that:
```
import hashlib
import json
a={'name':'Danish', 'age':107}
b={'age':107, 'name':'Danish'}
print hashlib.sha1(json.dumps(a, sort_keys=True)).hexdigest()
print hashlib.sha1(json.dumps(b, sort_keys=True)).hexdigest()
```
Returns:
```
71083588011445f0e65e11c80... |
Is there a simple Python map-reduce framework that uses the regular filesystem? | 16,093,044 | 8 | 2013-04-18T21:04:42Z | 16,187,105 | 10 | 2013-04-24T08:29:49Z | [
"python",
"mapreduce"
] | I have a few problems which may apply well to the Map-Reduce model. I'd like to experiment with implementing them, but at this stage I don't want to go to the trouble of installing a heavyweight system like Hadoop or Disco.
Is there a lightweight Python framework for map-reduce which uses the regular filesystem for in... | A Coursera course dedicated to big data suggests using these lightweight python Map-Reduce frameworks:
* <http://code.google.com/p/octopy/>
* <https://github.com/michaelfairley/mincemeatpy>
To get you started very quickly, try this example:
<https://github.com/michaelfairley/mincemeatpy/zipball/v0.1.2>
(hint: for [... |
matplotlib linewidth when saving a PDF | 16,093,408 | 6 | 2013-04-18T21:28:23Z | 16,132,492 | 7 | 2013-04-21T14:58:43Z | [
"python",
"pdf",
"matplotlib",
"dpi"
] | I have a figure with some fairly delicate features that are sensitive to linewidth. I want to save this figure as a PDF that can be easily printed (i.e. no scaling on the receiver's side, just Command+P and go). Unfortunately, when I set figsize=(8.5,11) in order to correctly size the PDF for printing, matplotlib picks... | Thanks Marius, I'll upvote as soon as I get 15 reputation required to do so. While your rcParams didn't quite match what I wanted to do, rcParams itself was the correct place to look so I listed rcParams containing 'linewidth' via rcParams.keys():
```
>>> [s for s in mp.rcParams.keys() if 'linewidth' in s]
['axes.line... |
flask sqlalchemy querying a column with not equals | 16,093,475 | 19 | 2013-04-18T21:33:04Z | 16,093,713 | 30 | 2013-04-18T21:49:51Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I can query my seats table for all seats where there is no invite assigned:
```
seats = Seat.query.filter_by(invite=None).all()
```
However, when querying for all seats that have an invite assigned, I get an err:
```
seats = Seat.query.filter_by(invite!=None).all()
NameError: name 'invite' is not defined
```
Here ... | The [filter\_by()](http://docs.sqlalchemy.org/en/rel_0_8/orm/query.html#sqlalchemy.orm.query.Query.filter_by) method takes a sequence of keyword arguments, so you always have to use '=' with it. You want to use the [filter()](http://docs.sqlalchemy.org/en/rel_0_8/orm/query.html#sqlalchemy.orm.query.Query.filter) method... |
flask sqlalchemy querying a column with not equals | 16,093,475 | 19 | 2013-04-18T21:33:04Z | 28,814,750 | 21 | 2015-03-02T16:29:54Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I can query my seats table for all seats where there is no invite assigned:
```
seats = Seat.query.filter_by(invite=None).all()
```
However, when querying for all seats that have an invite assigned, I get an err:
```
seats = Seat.query.filter_by(invite!=None).all()
NameError: name 'invite' is not defined
```
Here ... | I think this can help
<http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.isnot>
# Is None
```
query.filter(User.name == None)
```
or alternatively, if pep8/linters are a concern
`query.filter(User.name.is_(None))`
# Is not None
```
query.filter(User.name != No... |
single quotes and double quotes in python strings | 16,094,809 | 2 | 2013-04-18T23:30:46Z | 16,094,836 | 7 | 2013-04-18T23:33:30Z | [
"python",
"linux"
] | I want to call a python function `pexpect.spawn(cmd)`, where cmd is a string as below:
```
ssh -t [email protected] 'sudo nohup bash -c "./tcp_sender > /dev/null 2>&1 &"'
```
the ip addresses are always changing, so it is something like:
```
ssh -t kity@%s 'sudo nohup bash -c "./tcp_sender > /dev/null 2>&1 &"' %ho... | you could use triple quotes:
```
"""ssh -t kity@{0} 'sudo nohup bash -c "./tcp_sender > /dev/null 2>&1 &"'""".format(ip_address)
``` |
Using a data structure to pass multiple arguments | 16,095,117 | 2 | 2013-04-19T00:08:12Z | 16,095,128 | 16 | 2013-04-19T00:09:42Z | [
"python"
] | Is it possible to use a single data structure to pass into a function with multiple arguments? I'd like to do something like the following but it doesn't appear to work.
```
foo_bar = (123, 546)
def a(foo, bar):
print(foo)
print(bar)
```
Is it possible to do something like the following:
```
a(foo_bar)
```
... | What you want is:
```
a(*foo_bar)
```
See [Unpacking Argument Lists](http://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists) in the tutorial for details⦠but there really isn't much more to it than this.
For completeness, the reference documentation is in [Calls](http://docs.python.org/3/refer... |
What's the most pythonic way to iterate over all the lines of multiple files? | 16,095,855 | 10 | 2013-04-19T01:36:55Z | 16,095,960 | 15 | 2013-04-19T01:49:37Z | [
"python",
"file",
"parsing",
"logging"
] | I want to treat many files as if they were all one file. What's the proper pythonic way to take [filenames] => [file objects] => [lines] with generators/not reading an entire file into memory?
We all know the proper way to open a file:
```
with open("auth.log", "rb") as f:
print sum(f.readlines())
```
And we kno... | There's always [`fileinput`](http://docs.python.org/2/library/fileinput.html#fileinput.input).
```
for line in fileinput.input(filenames):
...
```
Reading the [source](http://hg.python.org/cpython/file/2.7/Lib/fileinput.py#l184) however, it appears that `fileinput.FileInput` can't be used as a context manager1. T... |
Custom decorator in flask not working? | 16,096,211 | 3 | 2013-04-19T02:24:22Z | 16,096,357 | 8 | 2013-04-19T02:42:00Z | [
"python",
"flask",
"decorator"
] | I have the following code:
```
import datetime
from flask.app import Flask
app = Flask(__name__)
app.config.from_object(__name__)
app.debug = True
def track_time_spent(name):
def decorator(f):
def wrapped(*args, **kwargs):
start = datetime.datetime.now()
ret = f(*args, **kwargs)
delta = datet... | The other answers seem to be missing that you're getting "bar" as a response from "/foo" when you switch the order of the decorators. You must use `@wraps` here unless you update the `__name__`, `__module__`, and such manually. Flask uses your methods kinda like singletons, and sees your decorator just as the `wrapped(... |
remove None value from a list without removing the 0 value | 16,096,754 | 81 | 2013-04-19T03:31:27Z | 16,096,769 | 120 | 2013-04-19T03:33:06Z | [
"python",
"list",
"filter",
"nonetype"
] | [This was my source I started with.](http://docs.python.org/2/library/functions.html#filter)
My List
```
L= [0, 23, 234, 89, None, 0, 35, 9]
```
When I run this :
```
L = filter(None, L)
```
I get this results
```
[23, 234, 89, 35, 9]
```
But this is not what I need, what I really need is :
```
[0, 23, 234, 89,... | ```
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]
```
Just for fun, here's how you can adapt `filter` to do this without using a `lambda`, (I wouldn't recommend this code - it's just for scientific purposes)
```
>>> from operator import is_not
>>> from functoo... |
remove None value from a list without removing the 0 value | 16,096,754 | 81 | 2013-04-19T03:31:27Z | 16,096,783 | 7 | 2013-04-19T03:34:38Z | [
"python",
"list",
"filter",
"nonetype"
] | [This was my source I started with.](http://docs.python.org/2/library/functions.html#filter)
My List
```
L= [0, 23, 234, 89, None, 0, 35, 9]
```
When I run this :
```
L = filter(None, L)
```
I get this results
```
[23, 234, 89, 35, 9]
```
But this is not what I need, what I really need is :
```
[0, 23, 234, 89,... | Using list comprehension this can be done as follows:
```
l = [i for i in list if i is not None]
```
The value of l is:
```
[0, 23, 234, 89, 0, 35, 9]
``` |
remove None value from a list without removing the 0 value | 16,096,754 | 81 | 2013-04-19T03:31:27Z | 16,097,112 | 31 | 2013-04-19T04:16:12Z | [
"python",
"list",
"filter",
"nonetype"
] | [This was my source I started with.](http://docs.python.org/2/library/functions.html#filter)
My List
```
L= [0, 23, 234, 89, None, 0, 35, 9]
```
When I run this :
```
L = filter(None, L)
```
I get this results
```
[23, 234, 89, 35, 9]
```
But this is not what I need, what I really need is :
```
[0, 23, 234, 89,... | FWIW, Python 3 makes this problem easy:
```
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(None.__ne__, L))
[0, 23, 234, 89, 0, 35, 9]
```
In Python 2, you would use a list comprehension instead:
```
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]
``` |
remove None value from a list without removing the 0 value | 16,096,754 | 81 | 2013-04-19T03:31:27Z | 20,558,516 | 13 | 2013-12-13T03:22:11Z | [
"python",
"list",
"filter",
"nonetype"
] | [This was my source I started with.](http://docs.python.org/2/library/functions.html#filter)
My List
```
L= [0, 23, 234, 89, None, 0, 35, 9]
```
When I run this :
```
L = filter(None, L)
```
I get this results
```
[23, 234, 89, 35, 9]
```
But this is not what I need, what I really need is :
```
[0, 23, 234, 89,... | For Python 2.7 (See Raymond's answer, for Python 3 equivalent):
Wanting to know whether something "is not None" is so common in python (and other OO languages), that in my Common.py (which I import to each module with "from Common import \*"), I include these lines:
```
def exists(it):
return (it is not None)
```... |
Python: When I have a if statement and a print assigned to 3 integers, and I type one higher, it gives both that, and the correct print | 16,096,924 | 3 | 2013-04-19T03:52:27Z | 16,096,942 | 12 | 2013-04-19T03:55:20Z | [
"python",
"python-3.x"
] | Sorry if i'm just being dumb, but I am new to python. When I execute this, and type a number higher than 7, it gives me 5, 6, and 7's answer, and the > 7 print. It tells me, "I hope it crosses the border into awesome", and then "That's awesome".
P.S I am using Python 3
```
print ('What is your name?')
LeName = input (... | This statement:
```
if mood == '5' '6' or '7':
```
is being parsed as:
```
if (mood == '56') or '7':
```
which is really just `if '7'` or `if True` since the *type* of `mood` is `int` while the type of `'56'` is `str`.
What's happening is that python is applying automatic string concatenation to `'5' '6'` to turn ... |
How to return smallest value in dictionary? | 16,099,112 | 4 | 2013-04-19T07:09:13Z | 16,099,259 | 8 | 2013-04-19T07:17:06Z | [
"python",
"dictionary"
] | Let say I have a dictionary of total of fruits:
```
Fruits = {"apple":8, "banana":3, "lemon":5, "pineapple":2,}
```
And I want the output to be
```
["pineapple"]
```
because pineapple has the least value. Or if i have this:
```
Colour = {"blue":5, "green":2, "purple":6, "red":2}
```
The output will be:
```
["gre... | Can do it as a two-pass:
```
>>> colour
{'blue': 5, 'purple': 6, 'green': 2, 'red': 2}
>>> min_val = min(colour.itervalues())
>>> [k for k, v in colour.iteritems() if v == min_val]
['green', 'red']
```
1. Find the min value of the dict's values
2. Then go back over and extract the key where it's that value...
An alt... |
Elementwise multiplication of several arrays in Python Numpy | 16,099,488 | 5 | 2013-04-19T07:28:27Z | 16,099,533 | 12 | 2013-04-19T07:30:56Z | [
"python",
"numpy",
"multiplication"
] | Coding some Quantum Mechanics routines, I have discovered a curious behavior of Python's NumPy. When I use NumPy's multiply with more than two arrays, I get faulty results. In the code below, i have to write:
```
f = np.multiply(rowH,colH)
A[row][col]=np.sum(np.multiply(f,w))
```
which produces the correct result. Ho... | Your fault is in not reading [the documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html):
> `numpy.multiply(x1, x2[, out])`
`multiply` takes exactly two input arrays. The optional third argument is an output array which can be used to store the result. (If it isn't provided, a new arr... |
How to remove empty string in a list? | 16,099,694 | 9 | 2013-04-19T07:41:13Z | 16,099,706 | 9 | 2013-04-19T07:41:51Z | [
"python",
"list"
] | For example I have a sentence
```
"He is so .... cool!"
```
Then I remove all the punctuation and make it in a list.
```
["He", "is", "so", "", "cool"]
```
How do I remove or ignore the empty string? | You can filter it like this
```
orig = ["He", "is", "so", "", "cool"]
result = [x for x in orig if x]
```
Or you can use `filter`. In python 3 `filter` returns a generator, thus `list()` turns it into a list. This works also in python 2.7
```
result = list(filter(None, orig))
``` |
How to remove empty string in a list? | 16,099,694 | 9 | 2013-04-19T07:41:13Z | 16,099,718 | 21 | 2013-04-19T07:42:30Z | [
"python",
"list"
] | For example I have a sentence
```
"He is so .... cool!"
```
Then I remove all the punctuation and make it in a list.
```
["He", "is", "so", "", "cool"]
```
How do I remove or ignore the empty string? | You can use [`filter`](http://docs.python.org/2/library/functions.html#filter), with `None` as the key function, which filters out all elements which are `False`ish (including empty strings)
```
>>> lst = ["He", "is", "so", "", "cool"]
>>> filter(None, lst)
['He', 'is', 'so', 'cool']
```
Note however, that `filter` r... |
Some strange behavior Python list and dict | 16,102,777 | 4 | 2013-04-19T10:41:40Z | 16,102,814 | 10 | 2013-04-19T10:44:15Z | [
"python",
"list",
"dictionary"
] | Can anyone explain why this happened with list and how to clean list after appending to another list?
```
>>> t = {}
>>> t["m"] = []
>>> t
{'m': []}
>>> t["m"].append('qweasdasd aweter')
>>> t["m"].append('asdasdaf ghghdhj')
>>> t
{'m': ['qweasdasd aweter', 'asdasdaf ghghdhj']}
>>> r = []
>>> r.append(t)
>>> r
[{'m': ... | That's a normal behaviour. Python uses references to store elements.
When you do `r.append(t)` python will store `t` in `r`. If you modify `t` later, `t` in `r` will be also modified because it's the same object.
If you want to make `t`Â independant from the value stored in `r` you have to copy it. Look at the [`copy`... |
Function doesn't return all results from 'for' loop | 16,103,187 | 3 | 2013-04-19T11:06:43Z | 16,103,221 | 9 | 2013-04-19T11:08:35Z | [
"python",
"for-loop"
] | I've made a simple function to print out a times table chart depending on the number you decide to run with. The problem I'm having due to my basic understanding of the language is why it only returns the first loop and nothing else.
```
def timestables(number):
for a in range(1, number+1):
b = a*a
c = a
... | You're `return`ing inside the `for` loop - and functions stop execution immediately once they hit a `return` statement.
To work around this, you can use a list to store those values, and then return that list.
```
def timestables(number):
lst = []
for a in range(1, number+1):
b = a*a
c = a
... |
Function doesn't return all results from 'for' loop | 16,103,187 | 3 | 2013-04-19T11:06:43Z | 16,103,270 | 15 | 2013-04-19T11:11:44Z | [
"python",
"for-loop"
] | I've made a simple function to print out a times table chart depending on the number you decide to run with. The problem I'm having due to my basic understanding of the language is why it only returns the first loop and nothing else.
```
def timestables(number):
for a in range(1, number+1):
b = a*a
c = a
... | [`yield`](http://wiki.python.org/moin/Generators) them.
```
def timestables(number):
for a in range(1, number+1):
yield '%s + %s = %s' % (a, a, a*a )
for x in timestables(5):
print x
```
This turns your function into a generator function, and you need to iterate over the results, i.e. the result is not a lis... |
Pandas Timedelta in Days | 16,103,238 | 8 | 2013-04-19T11:09:34Z | 28,900,208 | 12 | 2015-03-06T13:50:33Z | [
"python",
"numpy",
"timestamp",
"pandas"
] | I have a dataframe in pandas called 'munged\_data' with two columns 'entry\_date' and 'dob' which i have converted to Timestamps using pd.to\_timestamp.I am trying to figure out how to calculate ages of people based on the time difference between 'entry\_date' and 'dob' and to do this i need to get the difference in da... | Using the Pandas type [`Timedelta`](http://pandas.pydata.org/pandas-docs/dev/timedeltas.html) available since v0.15.0 you also can do:
```
In[1]: import pandas as pd
In[2]: df = pd.DataFrame([ pd.Timestamp('20150111'),
pd.Timestamp('20150301') ], columns=['date'])
In[3]: df['today'] = pd.Ti... |
mapping values are not allowed here ... in foo.py | 16,103,447 | 8 | 2013-04-19T11:22:09Z | 17,445,384 | 11 | 2013-07-03T10:18:11Z | [
"python",
"google-app-engine"
] | I have this GAE python code
In file foo.py
```
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Hello Foo')
app = webapp2.WSGIApplication([('/', MainPage)], debug = True)
```
---... | This kind of error occurs if you start the application the wrong way: `dev_appserver.py foo.py`. You need a directory, e.g., `foo` with `foo/foo.py` and `foo/app.yaml` and then start the program from the parent directory with `dev_appserver.py foo/` or in the directory itself with `dev_appserver.py .` |
unsupported operand type(s) for *: 'float' and 'Decimal' | 16,105,485 | 11 | 2013-04-19T13:13:25Z | 16,105,582 | 12 | 2013-04-19T13:18:10Z | [
"python",
"django"
] | I'm just playing around learning classes functions etc, So I decided to create a simple function what should give me tax amount.
this is my code so far...
```
class VAT_calculator:
"""
A set of methods for VAT calculations.
"""
def __init__(self, amount=None):
self.amount = amount
s... | It seems like `self.VAT` is of `decimal.Decimal` type and `self.amount` is a `float`, thing that you can't do.
Try `decimal.Decimal(self.amount) * self.VAT` instead. |
Boost.Python custom converter | 16,105,539 | 3 | 2013-04-19T13:16:11Z | 16,109,416 | 10 | 2013-04-19T16:35:44Z | [
"c++",
"python",
"boost",
"binding",
"boost-python"
] | I have a class taking a vector as parameter (a binary file content).
I would like to convert python 'str' type into vector of unsigned char but only for one of my class method.
```
BOOST_PYTHON_MODULE(hello) { class_<Hello>("Hello").
// This method takes a string as parameter and print it
.def("printChar",... | There are two approaches to this problem:
* Export a helper function as `Hello.storeFile` that accepts `boost::python::str`, constructs `std::vector<unsigned char>` from the string, and delegates to the C++ `Hello::storeFile` member function.
* Write a custom converter. While converters cannot be registered on a per-f... |
Count how many lines are in a CSV Python? | 16,108,526 | 23 | 2013-04-19T15:48:01Z | 16,108,605 | 53 | 2013-04-19T15:51:48Z | [
"python",
"django"
] | I'm using python (Django Framework) to read a CSV file. I pull just 2 lines out of this CSV as you can see. What I have been trying to do is store in a variable the total number of rows the CSV also.
**How can I get the total number of rows?**
```
file = object.myfilePath
fileObject = csv.reader(file)
for i in range(... | You need to count the number of rows:
```
row_count = sum(1 for row in fileObject) # fileObject is your csv.reader
```
Using `sum()` with a generator expression makes for an efficient counter, avoiding storing the whole file in memory.
If you already read 2 rows to start with, then you need to add those 2 rows to y... |
AttributeError: 'module' object has no attribute | 16,109,039 | 6 | 2013-04-19T16:14:18Z | 16,109,368 | 8 | 2013-04-19T16:32:32Z | [
"python",
"python-2.7"
] | I have looked at other posts here on this topic and not found a clear answer, though I'm sure its something simple.
My code has the following structure...
```
import matplotlib
...
...
class xyz:
def function_A(self,...)
...
...
fig1 = matplotlib.figure()
...
...
```
I am... | I think you're right and it's an import issue. The `matplotlib` module doesn't *have* a `figure` function:
```
>>> import matplotlib
>>> matplotlib.figure
Traceback (most recent call last):
File "<ipython-input-130-82eb15b3daba>", line 1, in <module>
matplotlib.figure
AttributeError: 'module' object has no attri... |
how to render only part of html with data using django | 16,110,099 | 5 | 2013-04-19T17:15:28Z | 16,110,356 | 11 | 2013-04-19T17:32:08Z | [
"python",
"django",
"django-templates",
"rendering"
] | I am using ajax to sort the data which came from search results.
Now I am wondering whether it is possible to render just some part of html so that i can load this way:
`$('#result').html(' ').load('/sort/?sortid=' + sortid);`
I am doing this but I am getting the whole html page as response and it is appending ... | From what I understand you want to treat the same view in a different way if you receive an ajax request.
I would suggest splitting your `result-page.html` into two templates, one that contains only the div that you want, and one that contains everything else and includes the other template (see [django's include tag](... |
Need to compare very large files around 1.5GB in python | 16,110,252 | 3 | 2013-04-19T17:24:20Z | 16,110,376 | 7 | 2013-04-19T17:33:31Z | [
"python",
"csv",
"numpy",
"pandas",
"large-data-volumes"
] | ```
"DF","[email protected]","FLTINT1000130394756","26JUL2010","B2C","6799.2"
"Rail","[email protected]","NR251764697478","24JUN2011","B2C","2025"
"DF","[email protected]","NF2513521438550","01JAN2013","B2C","6792"
"Bus","[email protected]","NU27012932319739","26JAN2013","B2C","800"
"Rail","[email protected]... | Use the built-in [sqlite3](http://docs.python.org/2/library/sqlite3.html) database: you can insert the data, sort and group as necessary, and there's no problem using a file which is larger than available RAM. |
Need to compare very large files around 1.5GB in python | 16,110,252 | 3 | 2013-04-19T17:24:20Z | 16,110,391 | 7 | 2013-04-19T17:34:29Z | [
"python",
"csv",
"numpy",
"pandas",
"large-data-volumes"
] | ```
"DF","[email protected]","FLTINT1000130394756","26JUL2010","B2C","6799.2"
"Rail","[email protected]","NR251764697478","24JUN2011","B2C","2025"
"DF","[email protected]","NF2513521438550","01JAN2013","B2C","6792"
"Bus","[email protected]","NU27012932319739","26JAN2013","B2C","800"
"Rail","[email protected]... | make sure you have 0.11, read these docs: <http://pandas.pydata.org/pandas-docs/dev/io.html#hdf5-pytables>, and these recipes: <http://pandas.pydata.org/pandas-docs/dev/cookbook.html#hdfstore> (esp the 'merging on millions of rows'
Here is a solution that seems to work. Here is the workflow:
1) read data from your cs... |
Splitting a list of lists and strings by a string | 16,110,307 | 2 | 2013-04-19T17:28:22Z | 16,110,349 | 7 | 2013-04-19T17:31:28Z | [
"python",
"list",
"split"
] | Is there a convenient pythonic way to split a list by a search string (even if the list contains non-strings and have nested lists). For example, say I would like to split the following by ',':
```
[[ 'something', ',', 'eh' ], ',', ['more'], ',', 'yet more', '|', 'even more' ]
```
This would become:
```
[[[ 'somethi... | Take a look at [`itertools.groupby`](http://docs.python.org/2/library/itertools.html#itertools.groupby):
```
In [1]: from itertools import groupby
In [2]: lst = [[ 'something', ',', 'eh' ], ',', ['more'], ',', 'yet more', '|', 'even more' ]
In [3]: [list(group) for key, group in groupby(lst, lambda x: x!=',') if key... |
Remove dot at the end of number | 16,110,777 | 2 | 2013-04-19T17:58:04Z | 16,110,801 | 8 | 2013-04-19T17:59:41Z | [
"python"
] | I have a txt file that looks like this:
```
1, 0., 0., 0.
2, 0., 0., 600.
3, 0., 0., 2600.
4, 0., 0., 50.
```
I'd like to read it and create the following list:
```
['1', '0', '0', '0']
['2', '0'... | Pass `"." + string.whitespace` to `strip` so that it strips both the spaces and the periods:
```
from string import whitespace
for line in inputFile:
fileData.append([int(x.strip("." + whitespace)) for x in line.split(',')])
``` |
scipy.sparse __add__ method being called when adding to a regular numpy ndarray? | 16,111,309 | 2 | 2013-04-19T18:31:40Z | 16,112,400 | 7 | 2013-04-19T19:43:57Z | [
"python",
"numpy",
"scipy",
"ipython",
"sparse-matrix"
] | I'm calculating the dot product between a scipy.sparse matrix (CSC) and a numpy ndarray vector:
```
>>> print type(np_vector), np_vector.shape
<type 'numpy.ndarray'> (200,)
>>> print type(sp_matrix), sparse.isspmatrix(sp_matrix), sp_matrix.shape
<class 'scipy.sparse.csc.csc_matrix'> True (200, 200)
>>> dot_vector = do... | What your call to `np.dot` is doing is not very different from what you get if you do the following:
```
>>> np.dot([1, 2, 3], 4)
array([ 4, 8, 12])
```
Because `np.dot` doesn't know about sparse matrices, the return in your case is again the product of each element of the vector with your original sparse matrix. Th... |
How to monkeypatch builtin function datetime.datetime.now? | 16,112,273 | 6 | 2013-04-19T19:36:03Z | 16,112,320 | 8 | 2013-04-19T19:39:22Z | [
"python",
"unit-testing",
"datetime",
"monkeypatching",
"py.test"
] | I'd like to make sure that `datetime.datetime.now()` returns a specific datetime for testing purposes, How do I do this? I've tried with pytest's monkeypatch
```
monkeypatch.setattr(datetime.datetime,"now", nowfunc)
```
But this gives me the error `TypeError: can't set attributes of built-in/extension type 'datetime.... | As the error tells you, you can't monkeypatch the attributes of many extension types implemented in C. (Other Python implementations may have different rules than CPython, but they often have similar restrictions.)
The way around this is to create a subclass, and monkeypatch the *class*.
For example (untested, becaus... |
Computation time insanely long in python | 16,113,234 | 4 | 2013-04-19T20:47:04Z | 16,113,603 | 9 | 2013-04-19T21:14:52Z | [
"python",
"optimization"
] | I'm running my code, that consist in find average values. In a ~6 million lines CSV (ssm\_resnik.txt), the first row is one reference, the second row is another and the third value is the 'distance' between the 2 references. Such distances are arbitrarly defined by biological criteria not important for this issue. Most... | 6 million rows can either be held in memory or in a SQLite database. Put it there and make use of the lookup optimizations that offers:
```
with open('ssm_resnik.txt', 'rbU') as uniprot_vs_uniprot:
reader = csv.reader(uniprot_vs_uniprot, delimiter='\t')
allVSall = { tuple(r[:2]): float(r[2]) for r in reader }
... |
Python Comparing Lists | 16,113,680 | 6 | 2013-04-19T21:21:58Z | 16,114,737 | 10 | 2013-04-19T23:06:56Z | [
"python",
"list",
"compare"
] | I want to compare two lists and want to know if a element corresponds to another element.
example:
'a' should correspond to 'b'
here, it will return True.
```
list1 = [a,b,c,d]
list2 = [b,a,d,c]
```
'a' and 'b' correspond to each-other (they share the same spot on lists). how do I make a function to return True if t... | I would do it like this:
```
>>> from operator import eq
>>> list1 = ['a','b','c','d']
>>> list2 = ['c','d','a','b']
>>> any(map(eq, list1, list2))
False
```
Of course, if you want the full boolean 'correspondence' list you can simply omit the `any` function:
```
>>> map(eq, list1, list2)
[False, False, False, False... |
error when trying to use pass keyword in one line if statement | 16,114,003 | 2 | 2013-04-19T21:48:36Z | 16,114,028 | 8 | 2013-04-19T21:51:17Z | [
"python"
] | stumped that this works:
```
if 5 % 2 == 0:
print "no remainder"
else:
pass
```
but not this:
```
print "no remainder" if 5% 2 == 0 else pass
SyntaxError: invalid syntax
``` | The latter is not an `if` statement, rather an expression (I mean, `print` is a statement, but the rest is being interpreted as an expression, which fails). Expressions have values. `pass` doesn't, because it's a statement.
You may be seeing it as two statements (`print or pass`), but the interpreter sees it different... |
calling dot products and linear algebra operations in Cython? | 16,114,100 | 22 | 2013-04-19T21:56:50Z | 16,153,914 | 22 | 2013-04-22T18:16:24Z | [
"python",
"numpy",
"scipy",
"cython",
"blas"
] | I'm trying to use dot products, matrix inversion and other basic linear algebra operations that are available in numpy from Cython. Functions like `numpy.linalg.inv` (inversion), `numpy.dot` (dot product), `X.t` (transpose of matrix/array). There's a large overhead to calling `numpy.*` from Cython functions and the res... | Calling BLAS bundled with Scipy is "fairly" straightforward, here's one example for calling DGEMM to compute matrix multiplication: <https://gist.github.com/pv/5437087> Note that BLAS and LAPACK expect all arrays to be Fortran-contiguous (modulo the lda/b/c parameters), hence `order="F"` and `double[::1,:]` which are r... |
getting the opposite diagonal of a numpy array | 16,114,333 | 13 | 2013-04-19T22:21:36Z | 16,114,400 | 16 | 2013-04-19T22:28:46Z | [
"python",
"arrays",
"numpy"
] | So in numpy arrays there is the built in function for getting the diagonal indices, but I can't seem to figure out how to get the diagonal starting from the top right rather than top left.
This is the normal code to get starting from the top left:
```
>>> import numpy as np
>>> array = np.arange(25).reshape(5,5)
>>> ... | There is
```
In [47]: np.diag(np.fliplr(array))
Out[47]: array([ 4, 8, 12, 16, 20])
```
or
```
In [48]: np.diag(np.rot90(array))
Out[48]: array([ 4, 8, 12, 16, 20])
```
Of the two, `np.diag(np.fliplr(array))` is faster:
```
In [50]: %timeit np.diag(np.fliplr(array))
100000 loops, best of 3: 4.29 us per loop
In ... |
adding directory to sys.path /PYTHONPATH | 16,114,391 | 43 | 2013-04-19T22:27:28Z | 16,114,586 | 54 | 2013-04-19T22:49:25Z | [
"python",
"mechanize",
"pythonpath"
] | I am trying to import a module from a particular directory.
The problem is that if I use `sys.path.append(mod_directory)` to append the path and then open the python interpreter, the directory `mod_directory` gets added to the end of the list sys.path. If I export the `PYTHONPATH` variable before opening the python in... | This is working as documented. Any paths specified in `PYTHONPATH` are documented as normally coming after the working directory but before the standard interpreter-supplied paths. `sys.path.append()` appends to the existing path. See [here](http://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH) and [here](http... |
Big-O notation for two simple recursive functions | 16,115,129 | 7 | 2013-04-20T00:06:02Z | 16,115,221 | 13 | 2013-04-20T00:20:26Z | [
"python",
"algorithm",
"math",
"recursion",
"big-o"
] | I have two recursive functions in Python and simply just want to know the Big O Notation for them. What is the Big O for each these?
```
def cost(n):
if n == 0:
return 1
else:
return cost(n-1) + cost(n-1)
def cost(n):
if n == 0:
return 1
else:
return 2*cost(n-1)
``` | Let's use recurrence relations to solve this! The first function's runtime can be described recursively as
> T(0) = 1
>
> T(n + 1) = 2T(n) + 1
That is, the base case takes one time unit to complete, and otherwise we make two recursive calls to smaller instances of the problem and do some amount of setup and cleanup w... |
Tkinter example code for multiple windows, why won't buttons load correctly? | 16,115,378 | 16 | 2013-04-20T00:46:32Z | 16,115,592 | 7 | 2013-04-20T01:28:02Z | [
"python",
"class",
"tkinter",
"destroy"
] | There must be something very obvious about why this code is wrong. I'm hoping somebody will be able to point it out.
I am new at Python and even newer at Tkinter. Can you tell? ; )
The reason I am using classes is that this is just sample code for me to get the jist of things, then this will be inserted into a larger... | You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for `Button`, but also for other widgets and non-gui objects such as `StringVar`.
**Quick fix:** add the frame `new` as the first argument to your `Button` in `Demo2`.
**Possibly better:**... |
Tkinter example code for multiple windows, why won't buttons load correctly? | 16,115,378 | 16 | 2013-04-20T00:46:32Z | 16,115,616 | 19 | 2013-04-20T01:33:35Z | [
"python",
"class",
"tkinter",
"destroy"
] | There must be something very obvious about why this code is wrong. I'm hoping somebody will be able to point it out.
I am new at Python and even newer at Tkinter. Can you tell? ; )
The reason I am using classes is that this is just sample code for me to get the jist of things, then this will be inserted into a larger... | I rewrote your code in a more organized, better-practiced way:
```
import tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
... |
Python: C for loop with two variables | 16,115,710 | 3 | 2013-04-20T01:52:54Z | 16,115,738 | 7 | 2013-04-20T01:58:12Z | [
"python",
"c"
] | I'm new to python. Is there a similar way to write this C for loop with 2 variables in python?
```
for (i = 0, j = 20; i != j; i++, j--) { ... }
``` | Python 2.x
```
from itertools import izip, count
for i, j in izip(count(0, 1), count(20, -1)):
if i == j: break
# do stuff
```
Python 3.x:
```
from itertools import count
for i, j in zip(count(0, 1), count(20, -1)):
if i == j: break
# do stuff
```
This uses `itertools.count()`, an iterator that iter... |
How Pony (ORM) does its tricks? | 16,115,713 | 78 | 2013-04-20T01:53:15Z | 16,118,756 | 151 | 2013-04-20T09:32:10Z | [
"python",
"orm",
"metaprogramming",
"dsl",
"ponyorm"
] | [Pony ORM](http://doc.ponyorm.com/) does the nice trick of converting a generator expression into SQL. Example:
```
>>> select(p for p in Person if p.name.startswith('Paul'))
.order_by(Person.name)[:2]
SELECT "p"."id", "p"."name", "p"."age"
FROM "Person" "p"
WHERE "p"."name" LIKE "Paul%"
ORDER BY "p"."name"
L... | Pony ORM author is here.
Pony translates Python generator into SQL query in three steps:
1. Decompiling of generator bytecode and rebuilding generator AST
(abstract syntax tree)
2. Translation of Python AST into "abstract SQL" -- universal
list-based representation of a SQL query
3. Converting abstract SQL repr... |
How to allow __init__ to allow 1 or no parameters in python | 16,116,161 | 3 | 2013-04-20T03:15:29Z | 16,116,166 | 10 | 2013-04-20T03:17:08Z | [
"python",
"class"
] | Right now I have this class:
```
class foo():
def __init__(self):
self.l = []
```
Right now, I can set a variable to foo without an argument in the parameter because it doesn't take one, but how can I allow this continue to take no required parameters, but also put in a list if I wanted into foo()? Example:
... | ```
def __init__(self, items=None):
if items is None: items = []
self.l = items
```
In response to @Eastsun's edit, I propose a different structure to `__init__`
```
def __init__(self, items=()):
''' Accepts any iterable
The appropriate TypeError will be raised if items is not iterable '''
self.l... |
Python Ordered Dictionary to regular Dictionary | 16,117,982 | 3 | 2013-04-20T07:42:47Z | 16,117,987 | 9 | 2013-04-20T07:43:25Z | [
"python"
] | I have something like
```
[('first', 1), ('second', 2), ('third', 3)]
```
and i want a built in function to make something like
```
{'first': 1, 'second': 2, 'third': 3}
```
Is anyone aware of a built-in python function that provides that instead of having a loop to handle it?
Needs to work with python >= 2.6 | [`dict`](http://docs.python.org/2/library/stdtypes.html#mapping-types-dict) can take a list of tuples and convert them to key-value pairs.
```
>>> lst = [('first', 1), ('second', 2), ('third', 3)]
>>> dict(lst)
{'second': 2, 'third': 3, 'first': 1}
``` |
How to write inline latex code in IPython notebook | 16,118,112 | 8 | 2013-04-20T08:01:49Z | 16,119,952 | 9 | 2013-04-20T11:44:14Z | [
"python",
"latex",
"ipython"
] | This might be painfully obvious but how do I write Latex script inline in IPython notebook file so when it is parsed it does not start a new line? | The answer can be found in this helpful [cookbook](http://www.personal.ceu.hu/tex/cookbook.html)
Inline uses `$...$`
Displayed used `$$...$$` |
First common element from two lists | 16,118,621 | 6 | 2013-04-20T09:13:31Z | 16,118,633 | 9 | 2013-04-20T09:16:27Z | [
"python"
] | ```
x = [8,2,3,4,5]
y = [6,3,7,2,1]
```
How to find out the first common element in two lists (in this case, "2") in a concise and elegant way? Any list can be empty or there can be no common elements - in this case None is fine.
I need this to show python to someone who is new to it, so the simpler the better.
UPD:... | This should be straight forward ~~and almost as effective as it gets~~ (for more effective solution check [Ashwini Chaudharys answer](http://stackoverflow.com/a/16118787/1149736) and for the most effective check [jamylaks answer](http://stackoverflow.com/a/16118989/1149736) and comments):
```
result = None
# Go trough... |
How to speed up python's 'turtle' function and stop it freezing at the end | 16,119,991 | 6 | 2013-04-20T11:48:52Z | 16,120,087 | 16 | 2013-04-20T11:59:33Z | [
"python",
"graphics",
"draw",
"turtle-graphics"
] | I have written a turtle program in python, but there are two problems.
1. It goes way too slow for larger numbers, I was wonder how I can speed up turtle.
2. It freezes after it finishes and when clicked on, says 'not responding'
This is my code so far:
```
import turtle
#Takes user input to decide how many squares... | 1. Set [turtle.speed](http://docs.python.org/2/library/turtle.html#turtle.speed) to fastest.
2. Use the `turtle.mainloop()` functionality to do work without screen refreshes.
3. Disable screen refreshing with `turtle.tracer(0, 0)` then at the end do `turtle.update()` |
Matplotlib grayscale heatmap with visually distinct "NA" squares fields | 16,120,481 | 4 | 2013-04-20T12:39:58Z | 16,125,413 | 8 | 2013-04-20T21:34:38Z | [
"python",
"matplotlib",
"heatmap"
] | I am creating a heatmap to be used in a publication. The publication is restricted to black and white printing, so I'm creating the heatmap in grayscale. The problem I have is that there are some squares in the heatmap which are "Not Applicable" which I want to visually differentiate from the other cells. My understand... | A simple solution is to just hatch the background axes patch. E.g.:
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
np.random.seed(1977)
data = np.random.random((10,25))
data = np.ma.masked_greater(data, 0.8)
fig, ax = plt.subplots()
im = ax.pcolormesh(data, cmap=cm.gray, edgecolors... |
Suggestions on get_text() in BeautifulSoup | 16,121,001 | 6 | 2013-04-20T13:41:03Z | 16,121,049 | 9 | 2013-04-20T13:47:27Z | [
"python",
"beautifulsoup"
] | I am using BeautifulSoup to parse some content from a html page.
I can extract from the html the content I want (i.e. the text contained in a `span` defined by the `class` myclass).
```
result = mycontent.find(attrs={'class':'myclass'})
```
I obtain this result:
```
<span class="myclass">Lorem ipsum<br/>dolor sit a... | Use 'contents' , then replace `<br>`?
Here is a full (working, tested) example:
```
from bs4 import BeautifulSoup
import urllib2
url="http://www.floris.us/SO/bstest.html"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
result = soup.find(attrs={'class':'myclass'})
print "The result of soup.find:"
print ... |
Suggestions on get_text() in BeautifulSoup | 16,121,001 | 6 | 2013-04-20T13:41:03Z | 16,121,098 | 13 | 2013-04-20T13:53:11Z | [
"python",
"beautifulsoup"
] | I am using BeautifulSoup to parse some content from a html page.
I can extract from the html the content I want (i.e. the text contained in a `span` defined by the `class` myclass).
```
result = mycontent.find(attrs={'class':'myclass'})
```
I obtain this result:
```
<span class="myclass">Lorem ipsum<br/>dolor sit a... | If you are using bs4 you can use [`strings`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#strings-and-stripped-strings):
```
" ".join(result.strings)
``` |
2D Convolution in Python similar to Matlab's conv2 | 16,121,269 | 13 | 2013-04-20T14:12:17Z | 16,121,975 | 23 | 2013-04-20T15:22:30Z | [
"python",
"image",
"matlab",
"signal-processing",
"convolution"
] | I have been trying to do Convolution of a 2D Matrix using SciPy, and Numpy but have failed. For SciPy I tried, sepfir2d and scipy.signal.convolve and Convolve2D for Numpy. Is there a simple function like conv2 in Matlab for Python?
Here is an example:
```
A= [ 5 4 5 4;
3 2 3 2;
5 ... | There are a number of different ways to do it with `scipy`, but 2D convolution isn't directly included in `numpy`. (It's also easy to implement with an fft using only numpy, if you need to avoid a scipy dependency.)
`scipy.signal.convolve2d`, `scipy.signal.convolve`, `scipy.signal.fftconvolve`, and `scipy.ndimage.conv... |
Python/Matplotlib - How to put text in the corner of equal aspect figure | 16,122,362 | 9 | 2013-04-20T16:04:11Z | 16,122,683 | 31 | 2013-04-20T16:37:14Z | [
"python",
"matplotlib"
] | I would like to put text in the right bottom corner of equal aspect figure.
I set the position relative to the figure by ax.transAxes,
but I have to define the relative coordinate value manually depending on height scales of each figures.
What would be a good way to know axes height scale and the correct text position... | Use `annotate`.
In fact, I hardly ever use `text`. Even when I want to place things in data coordinates, I usually want to offset it by some fixed distance in points, which is much easier with `annotate`.
As a quick example:
```
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspec... |
Handling all but one exception | 16,123,529 | 10 | 2013-04-20T18:03:46Z | 16,123,643 | 14 | 2013-04-20T18:17:49Z | [
"python",
"exception",
"exception-handling",
"error-handling"
] | How to handle all but one exception ?
```
try:
something
except NoChildException:
raise NoChildException
except:
pass
``` | The answer is to simply do `raise`:
```
try:
...
except SomeException:
raise
except:
...
```
`raise` without any expression after it will simple raise the last thrown exception (even if it's been handled!). It's roughly equivalent to:
```
except SomeException as e:
raise e
```
If you think another e... |
Last Key in Python Dictionary | 16,125,229 | 16 | 2013-04-20T21:10:36Z | 16,125,237 | 9 | 2013-04-20T21:11:14Z | [
"python",
"python-2.7"
] | I am having difficulty figuring out what the syntax would be for the last key in a Python dictionary. I know that for a Python list, one may say this to denote the last:
```
list[-1]
```
I also know that one can get a list of the keys of a dictionary as follows:
```
dict.keys()
```
However, when I attempt to use th... | It seems like you want to do that:
```
dict.keys()[-1]
```
`dict.keys()` returns a list of your dictionary's keys. Once you got the list, the -1 index allows you getting the last element of a list.
Since a dictionary is unordered, it's doesn't make sense to get the last key of your dictionary.
Perhaps you want to s... |
Last Key in Python Dictionary | 16,125,229 | 16 | 2013-04-20T21:10:36Z | 16,125,297 | 16 | 2013-04-20T21:16:34Z | [
"python",
"python-2.7"
] | I am having difficulty figuring out what the syntax would be for the last key in a Python dictionary. I know that for a Python list, one may say this to denote the last:
```
list[-1]
```
I also know that one can get a list of the keys of a dictionary as follows:
```
dict.keys()
```
However, when I attempt to use th... | It doesn't make sense to ask for the "last" key in a dictionary, because dictionary keys are *unordered*. You can get the list of keys and get the last one if you like, but that's not in any sense the "last key in a dictionary". |
Last Key in Python Dictionary | 16,125,229 | 16 | 2013-04-20T21:10:36Z | 16,125,343 | 18 | 2013-04-20T21:23:27Z | [
"python",
"python-2.7"
] | I am having difficulty figuring out what the syntax would be for the last key in a Python dictionary. I know that for a Python list, one may say this to denote the last:
```
list[-1]
```
I also know that one can get a list of the keys of a dictionary as follows:
```
dict.keys()
```
However, when I attempt to use th... | If insertion order matters, take a look at [`collections.OrderedDict`](http://docs.python.org/2/library/collections.html#collections.OrderedDict):
> An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unch... |
Search Python dictionary where value is list | 16,125,950 | 3 | 2013-04-20T22:43:15Z | 16,125,981 | 9 | 2013-04-20T22:45:25Z | [
"python",
"dictionary",
"python-2.7"
] | If I had a dictionary where the value was set to a list by default, how could I go about searching all of these lists in the dictionary for a certain term?
For Example:
```
textbooks = {"math":("red", "large"), "history":("brown", "old", "small")}
```
With more terms and cases where the same thing might occur again,... | ```
[k for k, v in textbooks.iteritems() if 'red' in v]
```
It is Pythonic shorthand for
```
res = []
for key, val in textbooks.iteritems():
if 'red' in val:
res.append(key)
```
See list [comprehension in Python documentation](http://docs.python.org/2.7/tutorial/datastructures.html#list-comprehensions) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.