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 |
|---|---|---|---|---|---|---|---|---|---|
Is it possible to have an optional with/as statement in python? | 12,168,208 | 6 | 2012-08-28T22:07:47Z | 12,168,252 | 8 | 2012-08-28T22:11:47Z | [
"python",
"file-io",
"with-statement"
] | Instead of this:
```
FILE = open(f)
do_something(FILE)
FILE.close()
```
it's better to use this:
```
with open(f) as FILE:
do_something(FILE)
```
What if I have something like this?
```
if f is not None:
FILE = open(f)
else:
FILE = None
do_something(FILE)
if FILE is not None:
FILE.close()
```
Where ... | If you were to just write it like this:
```
if f is not None:
with open(f) as FILE:
do_something(FILE)
else:
do_something(f)
```
(`file` is a builtin btw )
**Update**
Here is a funky way to do an on-the-fly context with an optional None that won't crash:
```
from contextlib import contextmanager
n... |
Python simultaneous variable incrementation | 12,168,571 | 3 | 2012-08-28T22:43:47Z | 12,168,605 | 10 | 2012-08-28T22:46:41Z | [
"python",
"variables",
"simultaneous"
] | Currently, I'm trying to simultaneously redefine two variables in python. For example, I have the base case
```
p = 3
q = 2
```
and I want to redefine p and q such that
```
p = p+2q
```
and
```
q = p+q
```
Therefore, the tuples of p and q should be (p,q) = (3,2) then (7,5) then (17,15), and so on. I'm not sur... | ```
>>> p = 2
>>> q = 3
>>> p, q = p + 2 * q, p + q
>>> print p
8
>>> print q
5
>>>
```
You can also add optional parentheses:
```
(p, q) = (p + 2 * q, p + q)
``` |
Pandas (python): How to add column to dataframe for index? | 12,168,648 | 7 | 2012-08-28T22:50:21Z | 12,170,403 | 20 | 2012-08-29T03:13:24Z | [
"python",
"indexing",
"dataframe",
"pandas"
] | The index that I have in the dataframe (with 30 rows) is of the form:
```
Int64Index([171, 174,173, 172, 199..............
....175, 200])
```
The index is not strictly increasing because the data frame is the output of a sort().
I want to have add a column which is the series:
```
[1, 2, 3, 4, 5................ | How about:
```
df['new_col'] = range(1, len(df) + 1)
```
Alternatively if you want the index to be the ranks and store the original index as a column:
```
df = df.reset_index()
``` |
How should I take the max of 2 columns in a dataframe and make it another column? | 12,169,170 | 8 | 2012-08-28T23:58:47Z | 12,169,357 | 17 | 2012-08-29T00:27:33Z | [
"python",
"dataframe",
"pandas"
] | I have a dataframe with columns `A`,`B`. I need to create a column `C` such that for every record / row:
`C = max(A, B)`.
How should I go about doing this?
Thanks. | You can get the maximum like this:
```
>>> df = DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]]
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]].max(axis=1)
0 1
1 8
2 3
```
and so:
```
>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
A B C
0 1 -2 ... |
Which is the preferred way to concatenate a string in Python? | 12,169,839 | 103 | 2012-08-29T01:46:02Z | 12,169,859 | 22 | 2012-08-29T01:48:41Z | [
"python",
"string",
"python-3.x",
"concat"
] | Since Python's `string` can't be changed, I was wondering how to concatenate a string more efficiently?
I can write like it:
```
s += stringfromelsewhere
```
or like this:
```
s = []
s.append(somestring)
later
s = ''.join(s)
```
While writing this question, I found a good article talking about the topic.
<http:... | If you are concatenating a lot of values, then neither. Appending a list is expensive. You can use StringIO for that. Especially if you are building it up over a lot of operations.
```
from cStringIO import StringIO
# python3: from io import StringIO
buf = StringIO()
buf.write('foo')
buf.write('foo')
buf.write('foo... |
Which is the preferred way to concatenate a string in Python? | 12,169,839 | 103 | 2012-08-29T01:46:02Z | 12,171,382 | 149 | 2012-08-29T05:24:50Z | [
"python",
"string",
"python-3.x",
"concat"
] | Since Python's `string` can't be changed, I was wondering how to concatenate a string more efficiently?
I can write like it:
```
s += stringfromelsewhere
```
or like this:
```
s = []
s.append(somestring)
later
s = ''.join(s)
```
While writing this question, I found a good article talking about the topic.
<http:... | The *best* way of appending a string to a string variable is to use `+` or `+=`. This is because it's readable and fast. They are also just as fast, which one you choose is a matter of taste, the latter one is the most common. Here are timings with the timeit module:
```
a = a + b:
0.11338996887207031
a += b:
0.110404... |
Django filter many to many field in admin? | 12,170,267 | 10 | 2012-08-29T02:50:37Z | 12,177,799 | 13 | 2012-08-29T12:19:28Z | [
"python",
"django",
"django-models",
"django-admin"
] | I have three objects:
```
Thing
some fields
Bucket
things = models.ManyToManyField(Thing)
User
buckets = models.ManyToManyField(Bucket)
things = models.ManyToManyField(Thing)
```
When editing my "Bucket" field in the admin, I want to be able to select Things, but only those things that are in the "Things" l... | Read [the docs](https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey):
```
class BucketAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "things":
kwargs["queryset"] = Thing... |
Flask and WTForms - how to get wtforms to refresh select data | 12,170,995 | 7 | 2012-08-29T04:39:47Z | 12,173,395 | 7 | 2012-08-29T08:07:44Z | [
"python",
"flask",
"wtforms"
] | I am using the latest version of flask, wtforms and Flask-WTForms.
I have a page that displays a form and one is a select box with option option called "A".
When the app starts all is well. In a another form I add a record called "B".
Now, the form I want should have the select box wth options A and B bot only optio... | The problem is that `getAgencyList()` is called upon definition of the class. So whatever that function returns at that time will be it's data. In order to update the list information you have to somehow run `getAgencyList` during instantiation. In order to do this you can use a not very obvious fact about wtforms that... |
Changes in import statement python3 | 12,172,791 | 58 | 2012-08-29T07:24:06Z | 12,173,406 | 89 | 2012-08-29T08:08:42Z | [
"python",
"python-3.x"
] | I don't understand the following from [pep-0404](http://www.python.org/dev/peps/pep-0404/)
> In Python 3, implicit relative imports within packages are no longer
> available - only absolute imports and explicit relative imports are
> supported. In addition, star imports (e.g. from x import \*) are only
> permitted in ... | Relative import happens whenever you are importing a package relative to the current script/package.
Consider the following tree for example:
```
mypkg
âââ base.py
âââ derived.py
```
Now, your `derived.py` requires something from `base.py`. In Python 2, you could do it like this (in `derived.py`):
```
f... |
method chaining in python | 12,172,934 | 10 | 2012-08-29T07:34:26Z | 12,173,146 | 13 | 2012-08-29T07:49:53Z | [
"python",
"method-chaining"
] | (not to be confused with itertools.chain)
I was reading the following:
<http://en.wikipedia.org/wiki/Method_chaining>
My question is: **what is the best way to implement method chaining in python?**
Here is my attempt:
```
class chain():
def __init__(self, my_object):
self.o = my_object
def __getat... | There is a very interesting [`Pipe`](https://github.com/JulienPalard/Pipe) library which may be the answer to your question. For example::
```
seq = fib() | take_while(lambda x: x < 1000000) \
| where(lambda x: x % 2) \
| select(lambda x: x * x) \
| sum()
``` |
Modify bits in an integer in Python | 12,173,774 | 6 | 2012-08-29T08:31:52Z | 12,174,051 | 11 | 2012-08-29T08:49:01Z | [
"python",
"binary",
"bit"
] | So, I have an integer with a value 7. (0b00000111) And I would like to replace it with a function to 13. (0b00001101) So what is the best algorithm to replace bytes in an integer? For example:
```
set_bits(somevalue, 3, 1) # What makes the 3rd bit to 1 in somevalue?
``` | You just need:
```
def set_bit(v, index, x):
"""Set the index:th bit of v to x, and return the new value."""
mask = 1 << index
v &= ~mask
if x:
v |= mask
return v
>>> set_bit(7, 3, 1)
15
>>> set_bit(set_bit(7, 1, 0), 3, 1)
13
```
Note that bit numbers (`index`) are from 0, with 0 being the least signif... |
Modify bits in an integer in Python | 12,173,774 | 6 | 2012-08-29T08:31:52Z | 12,174,125 | 9 | 2012-08-29T08:54:01Z | [
"python",
"binary",
"bit"
] | So, I have an integer with a value 7. (0b00000111) And I would like to replace it with a function to 13. (0b00001101) So what is the best algorithm to replace bytes in an integer? For example:
```
set_bits(somevalue, 3, 1) # What makes the 3rd bit to 1 in somevalue?
``` | These work for integers of any size, even greater than 32 bit:
```
def set_bit(value, bit):
return value | (1<<bit)
def clear_bit(value, bit):
return value & ~(1<<bit)
```
If you like things short, you can just use:
```
>>> val = 0b111
>>> val |= (1<<3)
>>> '{:b}'.format(val)
'1111'
>>> val &=~ (1<<1)
'1101... |
Implementing python slice notation | 12,173,856 | 17 | 2012-08-29T08:35:57Z | 12,216,257 | 16 | 2012-08-31T13:23:32Z | [
"php",
"python",
"arrays",
"algorithm"
] | I'm trying to reimplement python [slice notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part the... | Here's a straight port of the C code:
```
def adjust_endpoint(length, endpoint, step):
if endpoint < 0:
endpoint += length
if endpoint < 0:
endpoint = -1 if step < 0 else 0
elif endpoint >= length:
endpoint = length - 1 if step < 0 else length
return endpoint
def... |
Hello World in mod_wsgi | 12,173,971 | 14 | 2012-08-29T08:43:41Z | 12,176,268 | 11 | 2012-08-29T10:51:13Z | [
"python",
"apache",
"mod-wsgi",
"wsgi"
] | After failing repeatedly in my quest to get my flask application to run on Apache using `mod_wsgi` I decided to try running the [hello world example](http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide). Here is what I have -
Directory Structure (I changed the apache default `/var/www` to `~/public_html`)
`... | You need to use an absolute path, i.e. don't use `~`. This works fine for me...
```
[mpenning@tsunami public_html]$ sudo cat /etc/apache2/sites-available/wsgi_test
<VirtualHost *:80>
ServerName wsgihost
DocumentRoot /home/mpenning/public_html
WSGIScriptAlias / /home/mpenning/public_html/test.wsgi
</Virtual... |
Which Python testing framework to use? | 12,174,093 | 4 | 2012-08-29T08:51:48Z | 12,174,240 | 7 | 2012-08-29T09:00:02Z | [
"python",
"unit-testing",
"pyunit"
] | I have lots of directories in which there are python files. All are plain python files. I have not used any sort of framework for the same. I want to test those py files from one central location. I should just fire one command and all the \*\_test.py files from each and every directory should be invoked.
So, is there ... | [nose](http://nose.readthedocs.org/en/latest/) does all of this. Just `cd` to the root of your tree of Python files, and run
```
nosetests
```
Nose [finds test files](http://nose.readthedocs.org/en/latest/finding_tests.html) using a [regex](http://nose.readthedocs.org/en/latest/writing_tests.html) (basically the word... |
passing unicode strings from django to javascript | 12,174,494 | 6 | 2012-08-29T09:13:08Z | 12,174,682 | 10 | 2012-08-29T09:23:43Z | [
"javascript",
"python",
"django",
"unicode"
] | I have a bunch of unicode strings in my data which I need to pass from my django view to template for using in a JavaScript scriptlet that passes it to the web back and forth.
The problem is I want the strings to be represented in the JavaScript unicode form but I get strings with a **u** prefix from python.
For exam... | **Edit:** Django 1.7+ [no longer includes simplejson](https://docs.djangoproject.com/en/1.7/releases/1.7/#features-removed-in-1-7). Instead of
```
from django.utils import simplejson
```
write
```
import json
```
and then use `json` instead of `simplejson`.
---
You are probably printing the python repr of your da... |
Search document in MongoDB by _id using Flask-pymongo extension | 12,175,128 | 12 | 2012-08-29T09:48:34Z | 12,199,652 | 28 | 2012-08-30T14:50:55Z | [
"python",
"mongodb",
"flask",
"pymongo"
] | I am baffled with the following problem.
I am using Flask, flask-pymongo extension, mongodb version v2.2.0-rc0, pdfile version 4.5
This is my route:
```
@app.route("/check/<id>")
def check(id):
doc=conn.db.msg.find_one({'_id':id})
return render_template('base.html',name=doc)
```
the id is a valid \_id from a ... | You might also want to try using `ObjectId` from the `bson.objectid` module, like so:
```
from bson.objectid import ObjectId
```
In that case, you won't need to provide the `oid` kwarg. You'll just do something like this:
```
db_conn.msg.find_one({'_id': ObjectId(my_oid)})
``` |
scikit-learn GMM produce positive log probability | 12,175,404 | 5 | 2012-08-29T10:01:32Z | 12,199,026 | 9 | 2012-08-30T14:20:29Z | [
"python",
"machine-learning",
"scikit-learn",
"mixture-model"
] | I am using Gaussian Mixture Model from python scikit-learn package to train my dataset , however , I fount that when I code
-- G=mixture.GMM(...)
-- G.fit(...)
-- G.score(sum feature)
the resulting log probability is positive real number... why is that?
isn't log probability guaranteed to be negative?
I get it. wh... | Positive log probabilities are okay.
Remember that the GMM computed probability is a probability density function (PDF), so can be greater than one at any individual point.
The restriction is that the PDF must integrate to one over the data domain.
If the log probability grows very large, then the inference algorith... |
Python method for reading keypress? | 12,175,964 | 26 | 2012-08-29T10:33:09Z | 12,178,312 | 7 | 2012-08-29T12:45:42Z | [
"python",
"windows",
"key",
"keydown",
"getch"
] | I'm new to Python, and I just made a game and a menu in Python.
Question is, that using (raw\_)input() requires me to press enter after every keypress, I'd like to make it so that pressing downarrow will instantly select the next menuitem, or move down in the game. At the moment, it requires me to like type "down" and ... | See the MSDN [getch](http://msdn.microsoft.com/en-us/library/078sfkak%28v=vs.110%29.aspx) docs. Specifically:
> The \_getch and\_getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each... |
Python method for reading keypress? | 12,175,964 | 26 | 2012-08-29T10:33:09Z | 12,179,724 | 26 | 2012-08-29T14:01:26Z | [
"python",
"windows",
"key",
"keydown",
"getch"
] | I'm new to Python, and I just made a game and a menu in Python.
Question is, that using (raw\_)input() requires me to press enter after every keypress, I'd like to make it so that pressing downarrow will instantly select the next menuitem, or move down in the game. At the moment, it requires me to like type "down" and ... | Figured it out by testing all the stuff by myself.
Couldn't find any topics about it tho, so I'll just leave the solution here. This might not be the only, or even the best solution, but it works for my purposes (within getch's limits), and is better than nothing.
Note: proper `keyDown()` which would recognize all the... |
Passing an argument to a python script and opening a file | 12,178,206 | 4 | 2012-08-29T12:40:48Z | 12,178,253 | 7 | 2012-08-29T12:43:22Z | [
"python"
] | I've built a script that takes a filename as an argument and extracts all lines that match a certain pattern. Trouble is I can't open the filename - I keep getting :
```
"TypeError: coercing to unicode: need string or buffer"
```
It's complaining about the line `info = open(name, 'r')`.
Here's the code:
```
import ... | `sys.argv[1:]` is a *list*, not a *string*. When you slice a list, you get a list back -- even if you only take 1 element with the slice. You need to give `open` a string. Perhaps you wanted `sys.argv[-1]` (the last element)?
As a side note, the python standard library provides commandline parsing options -- One is th... |
Python @classmethod and @staticmethod for beginner? | 12,179,271 | 727 | 2012-08-29T13:37:33Z | 12,179,325 | 120 | 2012-08-29T13:40:24Z | [
"python",
"oop",
"static-methods",
"class-method"
] | Could someone explain to me the meaning of `@classmethod` and `@staticmethod` in python? I need to know the difference and the meaning.
As far as I understand, `@classmethod` tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that? Why not just def... | `@classmethod` means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
`@staticmethod` means: when this method is called, ... |
Python @classmethod and @staticmethod for beginner? | 12,179,271 | 727 | 2012-08-29T13:37:33Z | 12,179,752 | 1,377 | 2012-08-29T14:03:03Z | [
"python",
"oop",
"static-methods",
"class-method"
] | Could someone explain to me the meaning of `@classmethod` and `@staticmethod` in python? I need to know the difference and the meaning.
As far as I understand, `@classmethod` tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that? Why not just def... | Though `classmethod` and `staticmethod` are quite similar, there's a slight difference in usage for both entities: `classmethod` must have a reference to a class object as the first parameter, whereas `staticmethod` can have no parameters at all.
Let's look at all that was said in real examples.
**Boilerplate**
Let'... |
Python @classmethod and @staticmethod for beginner? | 12,179,271 | 727 | 2012-08-29T13:37:33Z | 14,605,349 | 492 | 2013-01-30T13:35:39Z | [
"python",
"oop",
"static-methods",
"class-method"
] | Could someone explain to me the meaning of `@classmethod` and `@staticmethod` in python? I need to know the difference and the meaning.
As far as I understand, `@classmethod` tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that? Why not just def... | Rostyslav Dzinko's answer is very appropriate. I thought I could highlight one other reason you should choose `@classmethod` over `@staticmethod`.
In the example above, Rostyslav used the `@classmethod` `from_string` as a Factory to create `Date` objects from otherwise unacceptable parameters. The same can be done wit... |
Python @classmethod and @staticmethod for beginner? | 12,179,271 | 727 | 2012-08-29T13:37:33Z | 23,054,064 | 35 | 2014-04-14T07:12:38Z | [
"python",
"oop",
"static-methods",
"class-method"
] | Could someone explain to me the meaning of `@classmethod` and `@staticmethod` in python? I need to know the difference and the meaning.
As far as I understand, `@classmethod` tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that? Why not just def... | `@staticmethod` function is nothing more than a function defined inside a class. It is callable without instantiating the class first. Itâs definition is immutable via inheritance.
* Python does not have to instantiate a **bound-method** for object.
* It eases the readability of the code: seeing **@staticmethod**, w... |
Python @classmethod and @staticmethod for beginner? | 12,179,271 | 727 | 2012-08-29T13:37:33Z | 31,503,491 | 12 | 2015-07-19T16:43:01Z | [
"python",
"oop",
"static-methods",
"class-method"
] | Could someone explain to me the meaning of `@classmethod` and `@staticmethod` in python? I need to know the difference and the meaning.
As far as I understand, `@classmethod` tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that? Why not just def... | ***A little compilation***
**@staticmethod**
A way to write a method inside a class without reference to the object it is being called on. So no need to pass implicit argument like self or cls.
It is written exactly the same how written outside the class, but it is not of no use in python because if you need to encaps... |
A starting point for learning how to implement MapReduce/Hadoop in Python? | 12,179,359 | 13 | 2012-08-29T13:42:32Z | 12,179,711 | 14 | 2012-08-29T14:00:41Z | [
"python",
"hadoop",
"mapreduce"
] | I've recently started getting into data analysis and I've learned quite a bit over the last year (at the moment, pretty much exclusively using Python). I feel the next step is to begin training myself in MapReduce/Hadoop. I have no formal computer science training however and so often don't quite understand the jargon ... | First, to use Hadoop with Python (whenever you run it on your own cluster, or Amazon EMR, or anything else) you would need an option called "Hadoop Streaming".
Read the [original chapter](http://hadoop.apache.org/common/docs/r0.15.2/streaming.html) ([updated link](http://hadoop.apache.org/docs/r0.18.0/commands_manual.... |
Flask - POST Error 405 Method Not Allowed | 12,179,593 | 23 | 2012-08-29T13:53:51Z | 12,179,649 | 23 | 2012-08-29T13:57:24Z | [
"python",
"http",
"post",
"flask"
] | I'm just starting to learn Flask, and I am trying to create a form which will allow a POST method. Here's my method:
```
@app.route('/template', methods=['GET', 'POST'])
def template():
if request.method == 'POST':
return "Hello"
return render_template('index.html')
```
And my index.html:
```
<html>
... | Your form is submitting to `/` when the method is routed for `/template` unless that is a typo, you should adjust your form's `action` attribute and point it to `'/template'`. |
Flask - POST Error 405 Method Not Allowed | 12,179,593 | 23 | 2012-08-29T13:53:51Z | 12,179,750 | 8 | 2012-08-29T14:03:01Z | [
"python",
"http",
"post",
"flask"
] | I'm just starting to learn Flask, and I am trying to create a form which will allow a POST method. Here's my method:
```
@app.route('/template', methods=['GET', 'POST'])
def template():
if request.method == 'POST':
return "Hello"
return render_template('index.html')
```
And my index.html:
```
<html>
... | Replace:
```
<form action="/" method="post">
```
with:
```
<form action="/template" method="post">
``` |
installing Mayavi with pip - no module named vtk | 12,182,052 | 17 | 2012-08-29T16:03:29Z | 12,206,868 | 9 | 2012-08-30T23:09:38Z | [
"python",
"installation",
"pip",
"vtk",
"mayavi"
] | I want to use Mayavi.
## Situation
* I use a MacBook Air, with OSX 10.7.3.
* I use Python 2.7.2
* I have `virtualenv` installed. But I have not used it for this installation.
I've manually installed all it's dependencies, including `VTK`.
For `VTK`, I followed its installation guide and installed the python wrapper... | Your `pip` is probably using a different `python`, kind of you have `vtk` installed using `/usr/local/bin/python`, while your `pip` binary uses `/usr/bin/python`.
Check it:
```
$ head -n1 $(which pip)
```
In order to get it solved, you can choose to use a `virtualenv`, or install `pip` using `/usr/local/bin/python`:... |
installing Mayavi with pip - no module named vtk | 12,182,052 | 17 | 2012-08-29T16:03:29Z | 24,497,610 | 12 | 2014-06-30T19:34:05Z | [
"python",
"installation",
"pip",
"vtk",
"mayavi"
] | I want to use Mayavi.
## Situation
* I use a MacBook Air, with OSX 10.7.3.
* I use Python 2.7.2
* I have `virtualenv` installed. But I have not used it for this installation.
I've manually installed all it's dependencies, including `VTK`.
For `VTK`, I followed its installation guide and installed the python wrapper... | I'm on Debian but this should work for you as well
I was stuck with installing vtk into a virtualenv, after hours of search with no results I did the following and it worked.
1. install python-vtk from repositories systemwide
2. copy vtk folder from /usr/lib/pymodules/python2.7 to /PATH/TO/YOUR/VIRTUALENV/lib/python2... |
How to read out the text from QLineEdit in python? | 12,182,057 | 4 | 2012-08-29T16:03:36Z | 12,182,136 | 7 | 2012-08-29T16:09:12Z | [
"python",
"qt-creator",
"qgis",
"qlineedit"
] | I have created for my plugin a start GUI with 3 buttons. This works very well and if I click on one of the buttons a specific action is started. So far this works. If I click on one of the buttons a new GUI with two buttons "ok" and "cancel" and a lineedit appears. If I push on cancel the GUI will be closed, if I push ... | As mentioned in the [documentation](http://www.pyside.org/docs/pyside-git/PySide/QtGui/QLineEdit.html#PySide.QtGui.QLineEdit.text), the text of a `QLineEdit` can be retrieved with its method `text`.
```
text = dlg.ui.lineEdit.text()
```
Note that it's a `QString`, not a regular string, but that shouldn't be a problem... |
Python closure function losing outer variable access | 12,182,068 | 7 | 2012-08-29T16:04:32Z | 12,182,176 | 9 | 2012-08-29T16:11:40Z | [
"python",
"closures",
"decorator"
] | I just learned python @ decorator, it's cool, but soon I found my modified code coming out weird problems.
```
def with_wrapper(param1):
def dummy_wrapper(fn):
print param1
param1 = 'new'
fn(param1)
return dummy_wrapper
def dummy():
@with_wrapper('param1')
def implementation(pa... | When Python parses a function, it notes whenever it finds a variable used on the left-hand side of an assignment, such as
```
param1 = 'new'
```
It assumes that all such variables are local to the function.
So when you precede this assignment with
```
print param1
```
an error occurs because Python does not have a ... |
Copy or clone an object instance in Django/Python | 12,182,657 | 2 | 2012-08-29T16:41:19Z | 12,183,010 | 14 | 2012-08-29T17:02:35Z | [
"python",
"database",
"django",
"oop",
"deep-copy"
] | I've following scenario:
```
class CourseTemplate(models.Model):
title = models.CharField(max_length=70)
teacher = models.ForeignKey(User)
description = models.TextField()
max_students = models.IntegerField()
sessions = models.ManyToManyField(CourseSession) # e.g. Session 1 Introduction, Session 2... | You can duplicate any existing django model instance by clearing its primary key, and then saving it again.
```
ct = CourseTemplate.objects.all()[0]
print ct.pk
# some original pk
ct.pk = None
ct.save()
print ct.pk
# will be a new auto-incremented
``` |
python pandas: apply a function with arguments to a series | 12,182,744 | 31 | 2012-08-29T16:46:39Z | 12,183,507 | 44 | 2012-08-29T17:36:10Z | [
"python",
"pandas",
"apply"
] | I want to apply a function with arguments to a series in python pandas:
```
x = my_series.apply(my_function, more_arguments_1)
y = my_series.apply(my_function, more_arguments_2)
...
```
The [documentation](http://pandas.sourceforge.net/generated/pandas.Series.apply.html) describes support for an apply method, but it ... | The documentation explains this clearly. The apply method accepts a python function which should have a single parameter. If you want to pass more parameters you should use `functools.partial` as suggested by Joel Cornett in his comment.
An example:
```
>>> import functools
>>> import operator
>>> add_3 = functools.p... |
python pandas: apply a function with arguments to a series | 12,182,744 | 31 | 2012-08-29T16:46:39Z | 26,918,510 | 13 | 2014-11-13T21:12:58Z | [
"python",
"pandas",
"apply"
] | I want to apply a function with arguments to a series in python pandas:
```
x = my_series.apply(my_function, more_arguments_1)
y = my_series.apply(my_function, more_arguments_2)
...
```
The [documentation](http://pandas.sourceforge.net/generated/pandas.Series.apply.html) describes support for an apply method, but it ... | Series.apply(func, convert\_dtype=True, args=(), \*\*kwds)
args : tuple
x = my\_series.apply(my\_function, args = (arg1,)) |
Is there a better way to use strip() on a list of strings? - python | 12,182,777 | 16 | 2012-08-29T16:48:49Z | 12,182,818 | 25 | 2012-08-29T16:50:57Z | [
"python",
"string",
"list",
"iterator",
"strip"
] | For now i've been trying to perform strip() on a list of strings and i did this:
```
i = 0
for j in alist:
alist[i] = j.strip()
i+=1
```
Is there a better way of doing that? | You probably shouldn't be using `list` as a variable name since it's a type. Regardless:
```
list = map(str.strip, list)
```
This will apply the function `str.strip` to every element in `list`, return a new list, and store the result back in `list`. |
Is there a better way to use strip() on a list of strings? - python | 12,182,777 | 16 | 2012-08-29T16:48:49Z | 12,182,862 | 17 | 2012-08-29T16:52:41Z | [
"python",
"string",
"list",
"iterator",
"strip"
] | For now i've been trying to perform strip() on a list of strings and i did this:
```
i = 0
for j in alist:
alist[i] = j.strip()
i+=1
```
Is there a better way of doing that? | You could use list comprehensions
```
stripped_list = [j.strip() for j in initial_list]
``` |
Is there a better way to use strip() on a list of strings? - python | 12,182,777 | 16 | 2012-08-29T16:48:49Z | 12,183,359 | 7 | 2012-08-29T17:25:25Z | [
"python",
"string",
"list",
"iterator",
"strip"
] | For now i've been trying to perform strip() on a list of strings and i did this:
```
i = 0
for j in alist:
alist[i] = j.strip()
i+=1
```
Is there a better way of doing that? | Some intriguing discussions on performance happened here, so let me provide a benchmark:
<http://ideone.com/ldId8>
```
noslice_map : 0.0814900398254
slice_map : 0.084676027298
noslice_comprehension : 0.0927240848541
slice_comprehension : 0.124806165695
iter_manual : 0.... |
Plot image color histogram using matplotlib | 12,182,891 | 8 | 2012-08-29T16:54:20Z | 12,183,468 | 11 | 2012-08-29T17:33:05Z | [
"python",
"image",
"matplotlib"
] | I am trying to generate a color histogram of an image. I am using PIL for reading image files and trying to plot the same through matplotlib.
```
im = Image.open(sys.argv[1])
w, h = im.size
colors = im.getcolors(w*h) #Returns a list [(pixel_count, (R, G, B))]
```
**Update**: After some trial and error this code ... | I tired your update code and it worked fine. Here is exactly what I am trying:
```
import PIL
from PIL import Image
from matplotlib import pyplot as plt
im = Image.open('./color_gradient.png')
w, h = im.size
colors = im.getcolors(w*h)
def hexencode(rgb):
r=rgb[0]
g=rgb[1]
b=rgb[2]
return '#%02x%0... |
open(file) from anywhere | 12,184,161 | 4 | 2012-08-29T18:21:22Z | 12,184,208 | 8 | 2012-08-29T18:24:02Z | [
"python",
"osx",
"file-io"
] | Working on OS X Lion, I'm trying to open a file in my python-program from anywhere in the terminal. I have set the following function in my .bash\_profile:
```
function testprogram() {python ~/.folder/.testprogram.py}
```
This way I can(in the terminal) run my testprogram from a different directory than my ~/.
Now, ... | Use the tilde to represent the home folder, just as you would in the `.bash_profile`, and use `os.path.expanduser`.
```
import os
infile = open(os.path.expanduser("~/folder2/test.txt"), "r+")
``` |
How to install Python25 on my mac with Homebrew | 12,184,308 | 3 | 2012-08-29T18:30:27Z | 12,274,446 | 15 | 2012-09-05T04:20:49Z | [
"python",
"osx",
"homebrew"
] | I'm new to Mac's and Python. I want to install an older version of Python (2.5) on to the Mac (OS X 10.8.1).
I'm using homebrew as it's newer than MacPorts and I don't know enough to choose between them.
Following instructions I have installed Rails, mySQL, budle, pow - all sorts of stuff, but when I use the same tech... | python25 is available in the Homebrew-versions tap:
```
$ brew tap homebrew/versions
$ brew install python25
``` |
How to install Python25 on my mac with Homebrew | 12,184,308 | 3 | 2012-08-29T18:30:27Z | 28,216,459 | 9 | 2015-01-29T13:53:57Z | [
"python",
"osx",
"homebrew"
] | I'm new to Mac's and Python. I want to install an older version of Python (2.5) on to the Mac (OS X 10.8.1).
I'm using homebrew as it's newer than MacPorts and I don't know enough to choose between them.
Following instructions I have installed Rails, mySQL, budle, pow - all sorts of stuff, but when I use the same tech... | I think the `brew tap homebrew/versions` tip is no longer valid...
I have added that to my Homebrew, however it appears to point to this repo: <https://github.com/Homebrew/homebrew-versions>
...and that does not contain any Python versions.
```
$ brew search python25
No formula found for "python25".
```
So if you w... |
Where should virtualenvs be created? | 12,184,846 | 30 | 2012-08-29T19:04:00Z | 12,184,873 | 45 | 2012-08-29T19:06:35Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] | I'm confused as to where I should put my virtualenvs.
With my first django project, I created the project with the command, "django-admin.py startproject djangoproject".
I then cd'd into the djangoproject directory and ran the command, "virtualenv env" which created the virtual environment directory at the same level... | Many people use the [virtualenvwrapper](http://www.doughellmann.com/projects/virtualenvwrapper/) tool, which keeps all virtualenvs in the same place (the `~/.virtualenvs` directory) and allows shortcuts for creating and keeping them there. For example, you might do:
```
mkvirtualenv djangoproject
```
and then later:
... |
Generate arrays that contain every combination of elements from an array | 12,185,374 | 2 | 2012-08-29T19:42:49Z | 12,185,398 | 12 | 2012-08-29T19:44:14Z | [
"python",
"list",
"combinations"
] | I have an array with approximately 1000 elements what I want to do is generate arrays of size 100 from that array that contain every combination of elements. For example let's say I have this array:
```
[A,B,C,D,E,F,G,H,I,J]
```
Splitting it into arrays with size two I want arrays that look like this:
```
[A,B]
[A,C... | You can use the [combinations](http://docs.python.org/py3k/library/itertools.html#itertools.combinations) function from the [itertools](http://docs.python.org/py3k/library/itertools.html) module:
```
>>> from itertools import combinations
>>> list(combinations('ABCD', 2))
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'... |
Get value at list/array index or "None" if out of range in Python | 12,186,388 | 12 | 2012-08-29T20:56:50Z | 12,186,422 | 13 | 2012-08-29T20:59:16Z | [
"python"
] | Is there clean way to get the value at a list index of `None` if the index is out or range in Python?
The obvious way to do it would be this:
```
if len(the_list) > i:
return the_list[i]
else:
return None
```
However, the verbosity reduces code readability. Is there a clean, simple, one-liner that can be use... | Try:
```
try:
return the_list[i]
except IndexError:
return None
```
Or, one liner:
```
l[i] if i < len(l) else None
```
Example:
```
>>> l=range(5)
>>> i=6
>>> print(l[i] if i < len(l) else None)
None
>>> i=2
>>> print(l[i] if i < len(l) else None)
2
``` |
Python Increment two strings at the same time | 12,186,624 | 5 | 2012-08-29T21:14:14Z | 12,186,636 | 13 | 2012-08-29T21:15:16Z | [
"python",
"for-loop"
] | I want to be able to interate both `list1 = list('asdf')` and `list2 = list('qwer')` at the same time. What is the best approach?
```
for i, p in list1, list2:
print(i,p)
```
Where `i` would be increment `list1` and `p` would be increment `list2`. | Use [`zip`](http://docs.python.org/library/functions.html#zip) (or [`itertools.izip`](http://docs.python.org/library/itertools.html#itertools.izip) if the two lists are large):
```
for i, p in zip(list1, list2):
print(i, p)
```
Alternately, if `list1` might not be the same length as `list2` use [`izip_longest` fr... |
How to exclude mock package from python coverage report using nosetests | 12,187,106 | 24 | 2012-08-29T21:58:53Z | 12,198,991 | 26 | 2012-08-30T14:18:37Z | [
"python",
"mocking",
"code-coverage",
"nose",
"python-mock"
] | I currently try to use the mock library to write some basic nose unittests in python.
After finishing some basic example I now tried to use `nosetests --with-coverage` and now I have the mock package and the package I tried to 'mock away' are shown in the coverage report. Is there a possibility to exclude these?
Here... | Create a .coveragerc file that excludes what you don't want in the report: <http://nedbatchelder.com/code/coverage/config.html> |
How to exclude mock package from python coverage report using nosetests | 12,187,106 | 24 | 2012-08-29T21:58:53Z | 16,426,571 | 13 | 2013-05-07T19:00:09Z | [
"python",
"mocking",
"code-coverage",
"nose",
"python-mock"
] | I currently try to use the mock library to write some basic nose unittests in python.
After finishing some basic example I now tried to use `nosetests --with-coverage` and now I have the mock package and the package I tried to 'mock away' are shown in the coverage report. Is there a possibility to exclude these?
Here... | In your .coveragerc move your `omit` entry from the `[report]` section to the `[run]` section. |
Open Source Scientific Project - Use Python 2.6 or 2.7? | 12,187,115 | 2 | 2012-08-29T21:59:17Z | 12,187,140 | 9 | 2012-08-29T22:01:30Z | [
"python",
"numpy",
"version",
"scipy",
"optparse"
] | I've seen several other topics on whether to use 2.x or 3.x. However, most of these are at least two years old and do not distinguish between 2.6 and 2.7.
I am rebooting a scientific project that I ultimately may want to release by 2013. I make use of numpy, scipy, and pylab, among standard 2.6+ modules like itertools... | If everything you need would work with 2.7 I would use it, no point staying with 2.6. Also, `.format()` works a bit nicer (no need to specify positions in the `{}` for the arguments to the formatting directives).
FWIW, I usually use 2.7 or 3.2 and every once in a while I end up porting some code to my Linux box which ... |
Assert a function/method was not called using Mock | 12,187,122 | 56 | 2012-08-29T21:59:50Z | 12,187,244 | 77 | 2012-08-29T22:12:30Z | [
"python",
"unit-testing",
"mocking",
"python-mock"
] | I'm using the Mock library to test my application, but I want to assert that some function was not called. Mock docs talk about methods like `mock.assert_called_with` and `mock.assert_called_once_with`, but I didn't find anything like `mock.assert_not_called` or something related to verify mock was **NOT called**.
I c... | This should work for your case;
```
assert not my_var.called, 'method should not have been called'
```
Sample;
```
>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have ... |
Assert a function/method was not called using Mock | 12,187,122 | 56 | 2012-08-29T21:59:50Z | 17,432,369 | 22 | 2013-07-02T17:48:24Z | [
"python",
"unit-testing",
"mocking",
"python-mock"
] | I'm using the Mock library to test my application, but I want to assert that some function was not called. Mock docs talk about methods like `mock.assert_called_with` and `mock.assert_called_once_with`, but I didn't find anything like `mock.assert_not_called` or something related to verify mock was **NOT called**.
I c... | You can check the `called` attribute, but if your assertion fails, the next thing you'll want to know is something *about* the unexpected call, so you may as well arrange for that information to be displayed from the start. Using `unittest`, you can check the contents of `call_args_list` instead:
```
self.assertItemsE... |
Assert a function/method was not called using Mock | 12,187,122 | 56 | 2012-08-29T21:59:50Z | 31,037,693 | 7 | 2015-06-24T21:48:17Z | [
"python",
"unit-testing",
"mocking",
"python-mock"
] | I'm using the Mock library to test my application, but I want to assert that some function was not called. Mock docs talk about methods like `mock.assert_called_with` and `mock.assert_called_once_with`, but I didn't find anything like `mock.assert_not_called` or something related to verify mock was **NOT called**.
I c... | When you test using class inherits **unittest.TestCase** you can simply use methods like:
* assertTrue
* assertFalse
* assertEqual
and similar (in [python documentation](https://docs.python.org/3.4/library/unittest.html#unittest.TestCase.debug) you find the rest).
In your example we can simply assert if **mock\_meth... |
Identifying the type of a file without extension from binary data | 12,190,128 | 3 | 2012-08-30T04:55:19Z | 12,190,187 | 9 | 2012-08-30T05:01:39Z | [
"python",
"file",
"binaryfiles",
"binary-data"
] | I have some files without extension. I would like associate extensions to them. For that I have written a python program to read the data in the file. My doubt is how can I identify its type without the extension without using third party tools.
I have to identify a pdf, doc and text file only. Other type of files are... | You could read the first few bytes of the file and look for a "magic number". The [Wikipedia page](http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_numbers_in_files) on magic numbers suggests that PDF files begin with ASCII `%PDF` and doc files begin with hex D0 CF 11 E0.
Identifying text files is goi... |
How to do a 'groupby' by multilevel index in Pandas | 12,190,716 | 7 | 2012-08-30T06:00:25Z | 12,192,290 | 8 | 2012-08-30T07:51:48Z | [
"python",
"pandas"
] | I have a dataframe 'RPT' indexed by (STK\_ID,RPT\_Date), contains the accumulated sales of stocks for each qurter:
```
sales
STK_ID RPT_Date
000876 20060331 798627000
20060630 1656110000
20060930 2719700000
20061231 3573660000
20070331 8784... | Assuming here that RPT\_Data is a string, any reason why not to use Datetime?
It is possible to groupby using functions, but only on a non MultiIndex-index. Working around this by resetting the index, and set 'RPT\_Date' as index to extract the year (note: pandas toggles between object and int as dtype for 'RPT\_Date'... |
Pandas: Sampling a DataFrame | 12,190,874 | 50 | 2012-08-30T06:12:46Z | 12,192,021 | 69 | 2012-08-30T07:36:18Z | [
"python",
"partitioning",
"pandas"
] | I'm trying to read a fairly large CSV file with Pandas and split it up into two random chunks, one of which being 10% of the data and the other being 90%.
Here's my current attempt:
```
rows = data.index
row_count = len(rows)
random.shuffle(list(rows))
data.reindex(rows)
training_data = data[row_count // 10:]
testi... | What version of pandas are you using? For me your code works fine (i`m on git master).
Another approach could be:
```
In [117]: import pandas
In [118]: import random
In [119]: df = pandas.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
In [120]: rows = random.sample(df.index, 10)
In [121]: df_10 = df.ix[... |
Pandas: Sampling a DataFrame | 12,190,874 | 50 | 2012-08-30T06:12:46Z | 17,171,819 | 70 | 2013-06-18T14:41:39Z | [
"python",
"partitioning",
"pandas"
] | I'm trying to read a fairly large CSV file with Pandas and split it up into two random chunks, one of which being 10% of the data and the other being 90%.
Here's my current attempt:
```
rows = data.index
row_count = len(rows)
random.shuffle(list(rows))
data.reindex(rows)
training_data = data[row_count // 10:]
testi... | I have found that `np.random.choice()` new in NumPy 1.7.0 works quite well for this.
For example you can pass the index values from a DataFrame and and the integer 10 to select 10 random uniformly sampled rows.
```
rows = np.random.choice(df.index.values, 10)
sampled_df = df.ix[rows]
``` |
Pandas: Sampling a DataFrame | 12,190,874 | 50 | 2012-08-30T06:12:46Z | 30,971,633 | 10 | 2015-06-22T03:13:46Z | [
"python",
"partitioning",
"pandas"
] | I'm trying to read a fairly large CSV file with Pandas and split it up into two random chunks, one of which being 10% of the data and the other being 90%.
Here's my current attempt:
```
rows = data.index
row_count = len(rows)
random.shuffle(list(rows))
data.reindex(rows)
training_data = data[row_count // 10:]
testi... | Pandas 0.16.1 have a [sample](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html) method for that. |
Pandas: Sampling a DataFrame | 12,190,874 | 50 | 2012-08-30T06:12:46Z | 33,768,634 | 9 | 2015-11-17T22:53:28Z | [
"python",
"partitioning",
"pandas"
] | I'm trying to read a fairly large CSV file with Pandas and split it up into two random chunks, one of which being 10% of the data and the other being 90%.
Here's my current attempt:
```
rows = data.index
row_count = len(rows)
random.shuffle(list(rows))
data.reindex(rows)
training_data = data[row_count // 10:]
testi... | New in version 0.16.1:
```
sample_dataframe = your_dataframe.sample(n=how_many_rows_you_want)
```
doc here: <http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sample.html> |
Is there a shortcut for `self.somevariable = somevariable` in a Python class constructor? | 12,191,075 | 3 | 2012-08-30T06:29:54Z | 12,191,118 | 7 | 2012-08-30T06:33:33Z | [
"python",
"class",
"constructor"
] | Constructors in Python often look like this:
```
class SomeClass:
def __init__(self, a, b = None, c = defC):
self.a = a
self.b = b or []
self.c = c
```
Is there a shortcut for this, e.g. to simply define `__init__(self,**kwargs)` and use the keys as properties of `self`? | One idiom I've seen is `self.__dict__.update(locals())`. If you run it right at the beginning of the method, this will update the object's dictionary with the arguments (since those are the only locals at the beginning of the method). If you pass in `**kwargs` you can do `self.__dict__.update(**kwargs)`.
Of course, th... |
Set command alias for print in python? | 12,191,318 | 4 | 2012-08-30T06:47:53Z | 12,191,418 | 7 | 2012-08-30T06:54:37Z | [
"python",
"aliases"
] | In bash you can give a command an alias like so:
```
alias e=echoset
alias e="echo blah"
```
I want to know how to do the same thing in Python. I know you can give classes aliases, but when I try to give a command (the print statement for example) an alias, I get an error:
```
>>> p = print
File "<stdin>", line 1... | Is your question specific to `print`?
In Python prior to 3.0, `print` is a keyword in the language grammar. Since it's not a first-class language object, you cannot assign it to a variable.
In Python 3.0, there is no keyword `print`; there's a `print` function instead ([documentation](http://docs.python.org/library/f... |
What is the underscore prefix for python file name? | 12,192,207 | 9 | 2012-08-30T07:46:51Z | 12,192,283 | 14 | 2012-08-30T07:51:35Z | [
"python",
"naming-conventions",
"prefix"
] | In `cherryPy` for example, there are files like:
* `__init__.py`
* `_cptools.py`
How are they different? What does this mean? | `__...__` means reserved Python *name* (both in filenames and in other names). You shouldn't *invent* your own names using the double-underscore notation; and if you use existing, they have special functionality.
In this particular example, `__init__.py` defines the 'main' unit for a package; it also causes Python to ... |
What is the underscore prefix for python file name? | 12,192,207 | 9 | 2012-08-30T07:46:51Z | 12,192,307 | 7 | 2012-08-30T07:53:29Z | [
"python",
"naming-conventions",
"prefix"
] | In `cherryPy` for example, there are files like:
* `__init__.py`
* `_cptools.py`
How are they different? What does this mean? | `__init__.py` is a special file that, when existing in a folder turns that folder into module. Upon importing the module, `__init__.py` gets executed. The other one is just a naming convention but I would guess this would say that you shouldn't import that file directly.
Take a look here: [6.4. Packages](http://docs.p... |
What is the underscore prefix for python file name? | 12,192,207 | 9 | 2012-08-30T07:46:51Z | 12,192,313 | 9 | 2012-08-30T07:54:01Z | [
"python",
"naming-conventions",
"prefix"
] | In `cherryPy` for example, there are files like:
* `__init__.py`
* `_cptools.py`
How are they different? What does this mean? | These, and other, naming conventions are described in detail in [Style Guide for Python Code - Descriptive: Naming Styles](http://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles)
Briefly:
* `__double_leading_and_trailing_underscore__`: "magic" objects or attributes that live in user-controlled namespaces.... |
matplotlib - increase resolution to see details | 12,192,661 | 14 | 2012-08-30T08:18:02Z | 12,200,590 | 17 | 2012-08-30T15:40:09Z | [
"python",
"matplotlib"
] | I have a big process that is composed of tasks (about 600), and I created a figure to watch the order they are launched with and the time they take. To do this, I used matplotlib and a barh.
The figure is ok (my 1st matplotlib success !), but:
* I would like to see the details and zoom on the picture when exported (a... | I managed to do so, on [Evert](http://stackoverflow.com/users/707650/evert)'s advice, by using a very big resolution with a very small font. Here are the most important steps:
```
import pylab as pl
pl.figure(figsize=(70, 70)) # This increases resolution
pl.savefig('test.eps', format='eps', dpi=900) # This does, too
p... |
matplotlib - increase resolution to see details | 12,192,661 | 14 | 2012-08-30T08:18:02Z | 12,212,939 | 9 | 2012-08-31T09:51:54Z | [
"python",
"matplotlib"
] | I have a big process that is composed of tasks (about 600), and I created a figure to watch the order they are launched with and the time they take. To do this, I used matplotlib and a barh.
The figure is ok (my 1st matplotlib success !), but:
* I would like to see the details and zoom on the picture when exported (a... | Just for the record, I will put the suggestion done in my second comment here as a possible answer as well. This may not always work, but a test shows good results:
```
import pylab as pl
pl.figure(figsize=(7, 7)) # Don't create a humongous figure
pl.annotate(..., fontsize=1, ...) # probably need the annotate line ... |
Flask Python, trying to return list or dict to Ajax call | 12,193,013 | 8 | 2012-08-30T08:40:37Z | 12,193,228 | 16 | 2012-08-30T08:53:09Z | [
"python",
"ajax",
"flask"
] | Within a Flask app, I have the following ajax call:
```
$.ajax({
url: "{{ url_for( 'bookings.get_customer' ) }}",
type: "POST",
data: nameArray,
success: function( resp ){
console.log( resp )
}
})
```
As you can see, I am passing ... | Flask doesn't expect that you will return `list` object from your view function. Try `jsonify` it before:
```
from flask import jsonify
@bookings.route( '/get_customer', methods=[ 'POST' ] )
def get_customer():
name = {}
for key, value in request.form.items():
name[ key ] = value
customer_obj = c... |
Is there something like a depth buffer in matplotlib? | 12,193,709 | 6 | 2012-08-30T09:22:48Z | 12,242,296 | 13 | 2012-09-03T05:11:47Z | [
"python",
"numpy",
"plot",
"matplotlib"
] | I'm trying to plot some curves with matplotlib.
But, since these curve overlap with each other from viewport.
So only z-order can not help here.
I wonder if there is a function works like a depth buffer in matplotlib.
I'm plotting something like this.
And the red line should not always on top in 3D space.
![]... | I think it's difficult to do such things in matplotlib, since it's a 2D plot library with some 3D plot ability. I recommend some real 3D plot library, such as visvis, mayavi, vpython. For example, in visvis, you can create a 3D curve like:

```
import... |
Invoke Python SimpleHTTPServer from command line with no cache option | 12,193,803 | 14 | 2012-08-30T09:28:39Z | 25,708,957 | 17 | 2014-09-07T09:46:44Z | [
"python"
] | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to sp... | Perhaps this may work. Save the following to a file:
**serveit.py**
```
#!/usr/bin/env python
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
... |
Shouldn't else be indented in the below code | 12,194,947 | 2 | 2012-08-30T10:35:55Z | 12,195,025 | 7 | 2012-08-30T10:40:09Z | [
"python"
] | In the [python tutorial](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) is an example (copied below), shouldn't `else` be indented? I ran the code and it didn't work but I indented it (`else`) and it worked. Is, what I am saying right? If the documentation is w... | See docs you linked:
```
Loop statements may have an else clause; it is executed when the loop
terminates through exhaustion of the list (with for) or when the condition
becomes false (with while), but not when the loop is terminated by a break
statement. This is exemplified by the following loop, which searches fo... |
Shouldn't else be indented in the below code | 12,194,947 | 2 | 2012-08-30T10:35:55Z | 12,195,043 | 7 | 2012-08-30T10:41:07Z | [
"python"
] | In the [python tutorial](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) is an example (copied below), shouldn't `else` be indented? I ran the code and it didn't work but I indented it (`else`) and it worked. Is, what I am saying right? If the documentation is w... | Tha example is working and the indented is fine, have a look here:
```
# Ident level:
>>> for n in range(2, 10): # 0
... for x in range(2, n): # 1
... if n % x == 0: ... |
Face recognition in OpenCV Python FAR/FRR | 12,197,383 | 3 | 2012-08-30T12:57:11Z | 12,324,991 | 22 | 2012-09-07T20:32:53Z | [
"python",
"opencv",
"computer-vision",
"face-recognition"
] | How can i conduct performance tests in OpenCV Python to check;
1. the time it takes to obtain a recognition result
2. the false accept/false reject rate on the database test cases.
I am using the example eigenface method in OpenCV (from Phillip - <https://github.com/bytefish/facerecognition_guide>) and am just intere... | # Validating OpenCV algorithms
## introduction
First of all sorry that it took so long to reply, but there was simply no spare time left. Actually validating algorithms is a very interesting topic and it's really not that hard. In this post I'll show how to validate your algorithms (I'll take the FaceRecognizer, beca... |
How to set style display of an html element in a selenium test? | 12,197,828 | 15 | 2012-08-30T13:20:00Z | 12,197,876 | 43 | 2012-08-30T13:22:45Z | [
"jquery",
"python",
"selenium",
"styles"
] | I get an element like
```
cv_upload = driver.find_element_by_id('id_cv_upload')
```
So I want to set its display as inline in python itself.**is it possible with python to set the display.**
I tried
```
cv_upload.style.display = "inline"
```
which is showing me error.
**One way** which is getting into my mind is ... | since you marked jQuery - You can use the [css()](http://api.jquery.com/css/) function to set/get css attributes
```
$('#id_cv_upload').css('display','inline');
``` |
Python : How to remove duplicate lists in a list of list? | 12,198,468 | 15 | 2012-08-30T13:51:28Z | 12,198,497 | 31 | 2012-08-30T13:52:52Z | [
"python"
] | I want to remove all duplicates list from a list of list.
So I have a list of lists like this.
```
a = [[1,2],[1,2],[3,4,5],[3,4,5],[3,4,5]]
```
I want to have:
```
b = [[1,2],[3,4,5]]
```
I don't know how to do.
Thank you | You could use a set:
```
b_set = set(map(tuple,a)) #need to convert the inner lists to tuples so they are hashable
b = map(list,b_set) #Now convert tuples back into lists (maybe unnecessary?)
```
Or, if you prefer list comprehensions/generators:
```
b_set = set(tuple(x) for x in a)
b = [ list(x) for x in b_set ]
``... |
Python: List all the file names in a directory and its subdirectories and then print the results in a txt file | 12,199,120 | 3 | 2012-08-30T14:24:23Z | 12,199,154 | 14 | 2012-08-30T14:25:41Z | [
"python",
"python-2.7"
] | My problem is as follows. I want to list all the file names in my directory and its subdirectories and have that output printed in a txt file. Now this is the code I have so far:
```
import os
for path, subdirs, files in os.walk('\Users\user\Desktop\Test_Py'):
for filename in files:
f = os.path.join(path, fil... | don't open a file in your `for` loop. open it before your `for` loop
like this
```
import os
a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
for filename in files:
f = os.path.join(path, filename)
a.write(str(f) + os.linesep)
```
Or using a context man... |
Python Ternary Operator Without else | 12,199,757 | 25 | 2012-08-30T14:56:43Z | 12,199,784 | 7 | 2012-08-30T14:57:47Z | [
"python",
"ternary"
] | Is it possible to do this on 1 line in Python?
```
if <condition>:
myList.append('myString')
```
I tried the ternary operator
```
myList.append('myString' if <condition>)
```
but my IDE (MyEclipse) didn't like it without an else. | ```
if <condition>: myList.append('myString')
```
Otherwise, no. Why the need to put it on one line?
Note that the "ternary operator" is an *operator*. Like any operator, it *must return something*, so how can you have a ternary operator without the `else` clause? What is it supposed to return if the condition isn't ... |
Python Ternary Operator Without else | 12,199,757 | 25 | 2012-08-30T14:56:43Z | 12,199,811 | 16 | 2012-08-30T14:59:11Z | [
"python",
"ternary"
] | Is it possible to do this on 1 line in Python?
```
if <condition>:
myList.append('myString')
```
I tried the ternary operator
```
myList.append('myString' if <condition>)
```
but my IDE (MyEclipse) didn't like it without an else. | The reason the language doesn't allow you to use the syntax
```
variable = "something" if a_condition
```
without else is that, in the case where `a_condition == False`, `variable` is suddenly unknown. Maybe it could default to `None`, but Python requires that all variable assignments actually result in explicit assi... |
Python Ternary Operator Without else | 12,199,757 | 25 | 2012-08-30T14:56:43Z | 12,199,948 | 32 | 2012-08-30T15:05:19Z | [
"python",
"ternary"
] | Is it possible to do this on 1 line in Python?
```
if <condition>:
myList.append('myString')
```
I tried the ternary operator
```
myList.append('myString' if <condition>)
```
but my IDE (MyEclipse) didn't like it without an else. | Yes, you can do this:
```
<condition> and myList.append('myString')
```
If `<condition>` is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If `<condition>` is true, then the right-hand side will be evaluated and the element will be appended.
I'll just point out that doing the a... |
Python dict incomprehension | 12,199,930 | 5 | 2012-08-30T15:04:28Z | 12,199,953 | 8 | 2012-08-30T15:05:31Z | [
"python",
"dictionary"
] | (Sorry, couldn't resist the pun!)
I wonder why it doesn't seem possible to translate:
```
dict([(str(x),x) if x % 2 else (str(x),x*10) for x in range(10)])
```
into this more readable expression, using dict comprehension:
```
{str(x):x if x % 2 else str(x):x*10 for x in range(10)}
``` | ```
{ str(x):(x if x % 2 else x*10) for x in range(10) }
```
seems to work well |
numpy: function for simultaneous max() and min() | 12,200,580 | 43 | 2012-08-30T15:39:23Z | 12,200,671 | 20 | 2012-08-30T15:44:12Z | [
"python",
"numpy"
] | [numpy.amax()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html#numpy.amax) will find the max value in an array, and [numpy.amin()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html) does the same for the min value. If I want to find both max and min, I have to call both functions, ... | I don't think that passing over the array twice is a problem. Consider the following pseudo-code:
```
minval = array[0]
maxval = array[0]
for i in array:
if i < minval:
minval = i
if i > maxval:
maxval = i
```
While there is only 1 loop here, there are still 2 checks. (Instead of having 2 loops ... |
numpy: function for simultaneous max() and min() | 12,200,580 | 43 | 2012-08-30T15:39:23Z | 12,200,694 | 14 | 2012-08-30T15:45:27Z | [
"python",
"numpy"
] | [numpy.amax()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html#numpy.amax) will find the max value in an array, and [numpy.amin()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html) does the same for the min value. If I want to find both max and min, I have to call both functions, ... | There is a function for finding (max-min) called [numpy.ptp](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ptp.html) if that's useful for you:
```
>>> import numpy
>>> x = numpy.array([1,2,3,4,5,6])
>>> x.ptp()
5
```
but I don't think there's a way to find both min and max with one traversal.
**EDIT:** [... |
numpy: function for simultaneous max() and min() | 12,200,580 | 43 | 2012-08-30T15:39:23Z | 29,436,730 | 9 | 2015-04-03T17:15:03Z | [
"python",
"numpy"
] | [numpy.amax()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html#numpy.amax) will find the max value in an array, and [numpy.amin()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html) does the same for the min value. If I want to find both max and min, I have to call both functions, ... | > Is there a function in the numpy API that finds both max and min with only a single pass through the data?
No. At the time of this writing, there is no such function. (And yes, if there *were* such a function, its performance would be *significantly* better than calling `numpy.amin()` and `numpy.amax()` successively... |
Checking for lists of empty values | 12,200,652 | 5 | 2012-08-30T15:43:32Z | 12,200,700 | 16 | 2012-08-30T15:45:42Z | [
"python",
"empty-list"
] | What is the most effective way to check if a list contains only empty values (not if a list is empty, but a list of empty elements)? I am using the famously pythonic implicit booleaness method in a for loop:
```
def checkEmpty(lst):
for element in lst:
if element:
return False
break... | ```
if not any(lst):
# ...
```
Should work. `any()` returns `True` if any element of the iterable it is passed evaluates `True`. Equivalent to:
```
def my_any(iterable):
for i in iterable:
if i:
return True
return False
``` |
Python Pandas How to assign groupby operation results back to columns in parent dataframe? | 12,200,693 | 22 | 2012-08-30T15:45:26Z | 12,201,723 | 23 | 2012-08-30T16:47:17Z | [
"python",
"group-by",
"dataframe",
"pandas"
] | I have the following data frame in IPython, where each row is a single stock:
```
In [261]: bdata
Out[261]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 21210 entries, 0 to 21209
Data columns:
BloombergTicker 21206 non-null values
Company 21210 non-null values
Country 21210 non-n... | ```
In [97]: df = pandas.DataFrame({'month': np.random.randint(0,11, 100), 'A': np.random.randn(100), 'B': np.random.randn(100)})
In [98]: df.join(df.groupby('month')['A'].sum(), on='month', rsuffix='_r')
Out[98]:
A B month A_r
0 -0.040710 0.182269 0 -0.331816
1 -0.004867 0.642243 ... |
Python Pandas How to assign groupby operation results back to columns in parent dataframe? | 12,200,693 | 22 | 2012-08-30T15:45:26Z | 12,332,974 | 15 | 2012-09-08T17:33:00Z | [
"python",
"group-by",
"dataframe",
"pandas"
] | I have the following data frame in IPython, where each row is a single stock:
```
In [261]: bdata
Out[261]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 21210 entries, 0 to 21209
Data columns:
BloombergTicker 21206 non-null values
Company 21210 non-null values
Country 21210 non-n... | While I'm still exploring all of the incredibly smart ways that `apply` concatenates the pieces it's given, here's another way to add a new column in the parent after a groupby operation.
```
In [236]: df
Out[236]:
yearmonth return
0 201202 0.922132
1 201202 0.220270
2 201202 0.228856
3 201203 0.... |
How can I convert an RGB image into grayscale in Python? | 12,201,577 | 48 | 2012-08-30T16:37:37Z | 12,201,744 | 77 | 2012-08-30T16:48:29Z | [
"python",
"matplotlib"
] | I'm trying to use `matplotlib` to read in an RGB image and convert it to grayscale.
In matlab I use this:
```
img = rgb2gray(imread('image.png'));
```
In the [matplotlib tutorial](http://matplotlib.sourceforge.net/users/image_tutorial.html) they don't cover it. They just read in the image
```
import matplotlib.imag... | How about doing it with [PIL](http://www.pythonware.com/products/pil/):
```
from PIL import Image
img = Image.open('image.png').convert('LA')
img.save('greyscale.png')
```
---
Using matplotlib and [the formula](http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale)
```
Y' = 0.299 R + 0.587 G + 0.114 ... |
How can I convert an RGB image into grayscale in Python? | 12,201,577 | 48 | 2012-08-30T16:37:37Z | 12,202,063 | 7 | 2012-08-30T17:11:52Z | [
"python",
"matplotlib"
] | I'm trying to use `matplotlib` to read in an RGB image and convert it to grayscale.
In matlab I use this:
```
img = rgb2gray(imread('image.png'));
```
In the [matplotlib tutorial](http://matplotlib.sourceforge.net/users/image_tutorial.html) they don't cover it. They just read in the image
```
import matplotlib.imag... | The tutorial is cheating because it is starting with a greyscale image encoded in RGB, so they are just slicing a single color channel and treating it as greyscale. The basic steps you need to do are to transform from the RGB colorspace to a colorspace that encodes with something approximating the luma/chroma model, su... |
How can I convert an RGB image into grayscale in Python? | 12,201,577 | 48 | 2012-08-30T16:37:37Z | 27,982,429 | 9 | 2015-01-16T10:56:03Z | [
"python",
"matplotlib"
] | I'm trying to use `matplotlib` to read in an RGB image and convert it to grayscale.
In matlab I use this:
```
img = rgb2gray(imread('image.png'));
```
In the [matplotlib tutorial](http://matplotlib.sourceforge.net/users/image_tutorial.html) they don't cover it. They just read in the image
```
import matplotlib.imag... | You can always read the image file as grayscale right from the beggining using opencv.
[Load an color image in grayscale:](http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_image_display/py_image_display.html)
```
img = cv2.imread('messi5.jpg',0)
``` |
How can I convert an RGB image into grayscale in Python? | 12,201,577 | 48 | 2012-08-30T16:37:37Z | 31,136,023 | 16 | 2015-06-30T10:39:19Z | [
"python",
"matplotlib"
] | I'm trying to use `matplotlib` to read in an RGB image and convert it to grayscale.
In matlab I use this:
```
img = rgb2gray(imread('image.png'));
```
In the [matplotlib tutorial](http://matplotlib.sourceforge.net/users/image_tutorial.html) they don't cover it. They just read in the image
```
import matplotlib.imag... | You can also use [scikit-image](http://scikit-image.org/docs/stable/api/skimage.color.html#rgb2gray), which provides some functions to convert an image in `ndarray`, like `rgb2gray`.
```
from skimage import color
from skimage import io
img = color.rgb2gray(io.imread('image.png'));
```
**Notes**: The weights used in ... |
python open() method IOError: [Errno 2] No such file or directory: | 12,201,928 | 15 | 2012-08-30T17:01:39Z | 12,201,952 | 14 | 2012-08-30T17:03:23Z | [
"python",
"file",
"yaml"
] | For some reason, my code, that used to working, is now having trouble opening a simple .yaml file. I have tried moving around the file, giving open() the full path to the file and none of it seems to work. I saw that this question has been asked a couple times before but didnt see any answeres that solved the problem.
... | Make sure the file exists.
You can then either:
* Call `os.chdir(dir)`, `dir` being the folder where the file is
located, then open the file with just its name like you were doing.
* Specify an absolute path to the file in your `open` call.
Remember to use a raw string if your path uses backslashes, like
so: `dir =... |
How to set up a resource shared by several unit tests? | 12,202,085 | 5 | 2012-08-30T17:13:42Z | 12,202,239 | 9 | 2012-08-30T17:23:25Z | [
"python",
"unit-testing",
"python-2.6"
] | In Python, how can I have one setup (which may contain expensive function calls) for a whole set of unit tests?
Example:
```
import unittest
class Test1(unittest.TestCase):
def setUp(self):
print "expensive call"
def test1(self):
self.assertEqual(1, 1)
def test2(self):
self.assert... | You can use setUpClass
```
import unittest
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
print 'setUpClass'
cls.data = 123
def test_one(self):
print 'test_one'
print self.data
def test_two(self):
print 'test_two'
if __name__ == "__main__":... |
python sum function - `start` parameter explanation required | 12,202,311 | 4 | 2012-08-30T17:28:03Z | 12,202,434 | 11 | 2012-08-30T17:36:22Z | [
"python",
"sum"
] | I am trying to understand the working of the built-in `sum()` function, but, the `start` parameter has evaporated my mind:
1. ```
a=[[1, 20], [2, 3]]
b=[[[[[[1], 2], 3], 4], 5], 6]
>>> sum(b,a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate li... | Sum does something like this
```
def sum(values, start = 0):
total = start
for value in values:
total = total + value
return total
```
`sum([1,2],[3,4])` expands something like `[3,4] + 1 + 2`, which you can see tries to add numbers and lists together.
In order to use `sum` to produce lists, the ... |
Remember form data for pagination | 12,202,852 | 6 | 2012-08-30T18:03:15Z | 12,226,262 | 7 | 2012-09-01T08:38:38Z | [
"python",
"pagination",
"flask",
"template-engine",
"flask-sqlalchemy"
] | In my Flask application, I have a view which renders a table of items by using the Flask-SQLAlchemy pagination method. Great stuff so far. But I want to add sorting and filtering, so I created a form with selectboxes where the user can choose the sort and filter options.
When submitting the sort/filter on the page, th... | You can use url parameters to pass the info about sorting. Say user selects sorting by name. Then add this at the end of url
```
your_url?sort=name
```
Then you can access it as
```
value = request.args.get('name','')
```
Simply pass sorting variable value to the template where you append sort value to the ... |
Working with Mountain Lion's Notification Center using PyObjC | 12,202,983 | 8 | 2012-08-30T18:12:31Z | 12,211,966 | 8 | 2012-08-31T08:53:36Z | [
"python",
"osx-mountain-lion",
"pyobjc",
"nsusernotification"
] | I'm trying to send notifications to Mountain Lion from my python script and react to clicks on the notifications. Sending the notifications works perfectly find by now. But yet I was not able to get Lion to call back my script upon a click.
Here is what I do. I implemented a Notification class. The only purpose of an ... | Ok, found it. Didn't run `AppHelper.runEventLoop()`. Obviously a facepalm mistake. The following code works:
```
class MountainLionNotification(Foundation.NSObject, Notification):
def notify(self, title, subtitle, text, url):
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotifi... |
pandas crashes on repeated DataFrame.reset_index() | 12,203,901 | 7 | 2012-08-30T19:15:56Z | 12,204,428 | 10 | 2012-08-30T19:52:44Z | [
"python",
"pandas"
] | Very weird bug here: I'm using pandas to merge several dataframes. As part of the merge, I have to call reset\_index several times. But when I do, it crashes unexpectedly on the second or third use of reset\_index.
Here's minimal code to reproduce the error:
```
import pandas
A = pandas.DataFrame({
'val' : ['aaa... | Inspecting frame.py, it looks like pandas tries to insert a column 'index' or 'level\_0'. If either/both(??) of them are already taken, then it throws the error.
Fortunately, there's a "drop" option. AFAICT, this drops an existing index with the same name and replaces it with the new, reset index. This might get you i... |
Passing C++ pointer as argument into Cython function | 12,204,441 | 16 | 2012-08-30T19:53:17Z | 23,416,111 | 8 | 2014-05-01T20:33:15Z | [
"python",
"cython"
] | ```
cdef extern from "Foo.h":
cdef cppclass Bar:
pass
cdef class PyClass:
cdef Bar *bar
def __cinit__(self, Bar *b)
bar = b
```
This will always give me something like:
`Cannot convert Python object argument to type 'Bar *'`
Is there a way to accomplish this, or do I need to extract ev... | I came across this problem trying to wrap C code with structs as python classes. The issue seems to be that "special" function including `__init__` and `__cinit__` must be declared as `def` rather than `cdef`. This means that they can be called from normal python, so the type parameters are effectively ignored and ever... |
Python Mechanize - how to add a header on a single .open() call? | 12,205,221 | 3 | 2012-08-30T20:46:45Z | 12,765,642 | 7 | 2012-10-07T02:36:42Z | [
"python",
"mechanize"
] | I'm trying to get around a certain service not having an API and decided to try Mechanize (I normally use urllib).
How do I add a specific header for one `open` call?
Or is there a way to construct a Request instance with its own headers, then have my `mechanize.Browser` instance handle it?
```
browser = mechanize.B... | Do it like this:
```
import mechanize
import urllib2
browser = mechanize.Browser()
# setup your header, add anything you want
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1', 'Referer': 'http://whateveritis.com'}
url = "http://google.com"
# wrap the request. You can rep... |
Adding parentheses around a string matched by a regex in Python | 12,205,808 | 3 | 2012-08-30T21:29:00Z | 12,205,838 | 8 | 2012-08-30T21:31:13Z | [
"python",
"regex"
] | Given a regex and a string s, I would like to generate a new string in which any substring of s matched by the regex is surrounded by parentheses.
For example: My original string s is "Alan Turing 1912-1954" and my regex happens to match "1912-1954". The newly generated string should be "Alan Turing (1912-1954)". | **Solution 1:**
```
>>> re.sub(r"\d{4}-\d{4}", r"(\g<0>)", "Alan Turing 1912-1954")
'Alan Turing (1912-1954)'
```
`\g<0>` is a backreference to the entire match (`\0` doesn't work; it would be interpreted as `\x00`).
**Solution 2:**
```
>>> regex = re.compile(r"\d{4}-\d{4}")
>>> regex.sub(lambda m: '({0})'.format(m... |
How to check if given word is in plural or singular form? | 12,206,276 | 7 | 2012-08-30T22:09:17Z | 12,206,471 | 8 | 2012-08-30T22:27:26Z | [
"python",
"nlp"
] | Question like in topic - I'm trying to do that in python for app in Google App Engine. I know PyEnchant library is used for natural language recognition but I don't see if I can use it for my problem and how. | Checkout the [inflect 0.2.4](https://pypi.python.org/pypi/inflect/0.2.4) library.
> **inflect 0.2.4**
>
> Correctly generate plurals, singular nouns, ordinals, indefinite
> articles; convert numbers to words |
Sphinx autosummary "toctree contains reference to nonexisting document" warnings | 12,206,334 | 24 | 2012-08-30T22:15:00Z | 15,210,813 | 29 | 2013-03-04T20:46:22Z | [
"python",
"python-2.7",
"python-sphinx"
] | I am trying to automatically create api docs for a large python codebase using Sphinx.
I have tried using build\_modules.py and sphinx-apidoc. With either one, I can get rst docs successfully created in my output directory for the packages and top-level modules.
However, when I build using
```
make html
```
it give... | Sorry for such a late answer (if it can be considered that) but I found this link that discusses what may be happening to you:
<https://github.com/phn/pytpm/issues/3#issuecomment-12133978>
The idea that if you have some special Doc scraper in your documentation code that is building autosummary documentation after au... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.