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 |
|---|---|---|---|---|---|---|---|---|---|
Finding the outlier points from matplotlib : boxplot | 10,238,357 | 6 | 2012-04-19T23:36:45Z | 10,242,354 | 12 | 2012-04-20T07:57:27Z | [
"python",
"matplotlib",
"outliers"
] | I am plotting a non-normal distribution using boxplot and interested in finding out about outliers using boxplot function of matplotlib.
Besides the plot I am interested in finding out the value of points in my code which are shown as outliers in the boxplot. Is there any way I can extract these values for use in my d... | Do you means those points above and below the two black lines?
```
from pylab import *
spread= rand(50) * 100
center = ones(25) * 50
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
data =concatenate((spread, center, flier_high, flier_low), 0)
r = boxplot(data)
```
)*2"
```
I want to be able to handle multiple parentheses within parentheses for a math reader I'm writing. Perhaps I'm going about this the wrong way, but my goal was to recursively go deeper into the parentheses until there were none, and then I would perform the math operations.... | I love regular expressions. I use them all the time.
Don't use regular expressions for this.
You want an actual parser that will actually parse your math expressions. You might want to read this:
<http://effbot.org/zone/simple-top-down-parsing.htm>
Once you have actually parsed the expression, it's trivial to walk ... |
Can't install Orange: "error: command 'clang' failed with exit status 1" | 10,238,458 | 9 | 2012-04-19T23:50:59Z | 10,265,017 | 14 | 2012-04-22T03:38:37Z | [
"python",
"osx",
"gcc",
"orange"
] | I am trying to install [Orange](http://orange.biolab.si/) on my Mac OS X 10.7.3 (Lion) and I keep getting an error when using either pip or building from source. First, I was getting an error that read:
```
error: command 'gcc-4.0' failed with exit status 1
```
I have Xcode 4, which comes bundled with gcc 4.2.1. So I... | Problem solved: Xcode 4 doesn't actually come with gcc-4.2; it comes with the new LLVM compilers.
It was just a matter of doing:
```
export CC=llvm-gcc-4.2
export CXX=llvm-g++-4.2
```
then building Orange. |
Pylint disable all warnings for a file | 10,238,473 | 26 | 2012-04-19T23:53:41Z | 10,238,540 | 33 | 2012-04-20T00:02:39Z | [
"python",
"pylint"
] | We are using pylint within our build system. We have a python package within our code base that has throwaway code, and I'd like to disable all warnings for a module temporarily so I can stop bugging the other devs with these superfluous messages. Is there an easy way to `pylint: disable` all warnings for a module? | From the [PyLint FAQ](https://pylint.readthedocs.io/en/latest/faq.html#how-can-i-tell-pylint-to-never-check-a-given-module)
With Pylint < 0.25, add
```
#pylint: disable-all
```
at the beginning of the module.
Pylint 0.26.1 and up have renamed that directive to
```
#pylint: skip-file
```
(but the first version wil... |
IndentationError expected an indented block | 10,238,770 | 5 | 2012-04-20T00:37:38Z | 10,238,788 | 20 | 2012-04-20T00:40:22Z | [
"python",
"indentation"
] | Here is the code.:
```
def myfirst_yoursecond(p,q):
a = p.find(" ")
b = q.find(" ")
str_p = p[0:a]
str_q = p[b+1:]
if str_p == str_q:
result = True
else:
result = False
return result
```
Here is the error:
```
Traceback (most recent call last):
File "vm_main.py", line 26, in <module>
import main
File "/tmp... | You've mixed tabs and spaces. This can lead to some confusing errors.
I'd suggest using *only* tabs or *only* spaces for indentation.
Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.
---
As an aside... |
IndentationError: unexpected unindent WHY? | 10,239,668 | 10 | 2012-04-20T03:00:45Z | 10,239,677 | 27 | 2012-04-20T03:01:57Z | [
"python",
"indentation"
] | IndentationError: unexpected unindent WHY???
```
#!/usr/bin/python
import sys
class Seq:
def __init__(self, id, adnseq, colen):
self.id = id
self.dna = adnseq
self.cdnlen = colen
self.prot = ""
def __str__(self):
return ">%s\n%s\n" % (self.id, self.prot)
def... | It's because you have:
```
def readTTable(fname):
try:
```
without a matching `except` block after the `try:` block. Every `try` must have at least one matching `except`.
See the [Errors and Exceptions](http://docs.python.org/tutorial/errors.html) section of the Python tutorial. |
Why does this output occur? | 10,239,716 | 2 | 2012-04-20T03:08:10Z | 10,239,729 | 9 | 2012-04-20T03:10:59Z | [
"python"
] | ```
def function(s):
if len(s) == 1:
print s[0],
else:
function(s[1:])
print s[0],
```
`function("1234")` ends up printing `4 3 2 1`
Why does this happen? In the function, obviously the first condition is not met. In the else condition, `s[1:]` is put in for s, yet its length is not 1. I just don't see ... | ```
>>> def function(s):
... print 's is currently %r' % s
... if len(s) == 1:
... print s[0],
... else:
... function(s[1:])
... print s[0],
...
>>> function("1234")
s is currently '1234'
s is currently '234'
s is currently '34'
s is currently '4'
4 3 2 1
```
It's a recursive funct... |
HOW TO use Pycharm to debug python script? | 10,240,018 | 8 | 2012-04-20T03:54:57Z | 22,495,241 | 8 | 2014-03-19T02:49:34Z | [
"python",
"debugging",
"pycharm"
] | I'm trying to use [pycharm](http://www.jetbrains.com/pycharm/). I can write code and run it. However, I do not know how to to debug the code. When I click the debug button, I get something similar to the below image:

Is there any special configuratio... | I'd like to illustrate how to set parameters, as it took me a while to do this right:
**Find the drop-down menu next to the "Run" button:**

**Choose the file you want to configure, then click "Edit Configurations":**
![enter image description her... |
Python - Getting Started | 10,240,241 | 2 | 2012-04-20T04:20:44Z | 10,240,249 | 9 | 2012-04-20T04:22:45Z | [
"python",
"syntax",
"syntax-error"
] | I am just getting started with Python and wrote a simple perimeter program. However whenever I type python perimeter.py in my terminal I get the following error I don't know how to solve it.
```
>>> python perimeter.py
File "<stdin>", line 1
python perimeter.py
^
```
SyntaxError: invalid syntax
What i... | You type `python perimeter.py` in your command shell to start the Python interpreter. You don't type it *in* the Python interpreter.
If you really need to run the script from within the Python interpreter, do `execfile('perimeter.py')`. |
How do I run a python interpreter in Emacs? | 10,241,279 | 16 | 2012-04-20T06:27:08Z | 10,241,346 | 7 | 2012-04-20T06:32:36Z | [
"python",
"emacs",
"interpreter"
] | I just downloaded GNU emacs23.4, and I already have python3.2 installed in Windows7.
I have been using Python IDLE to edit python files.
The problem is that I can edit python files with Emacs but I do not know how to run python interpreter in Emacs. When i click on "switch to interpreter", then it says "Searching for... | IF you have python installed, try M-x-python-shell
(as in press and hold ALT while pressing x, then type in 'python-shell' without the quotes)
There are different language implementations if that is what you are asking (see a list of them [here](http://en.wikipedia.org/wiki/Category%3aPython_implementations)). |
How do I run a python interpreter in Emacs? | 10,241,279 | 16 | 2012-04-20T06:27:08Z | 10,241,634 | 9 | 2012-04-20T06:57:25Z | [
"python",
"emacs",
"interpreter"
] | I just downloaded GNU emacs23.4, and I already have python3.2 installed in Windows7.
I have been using Python IDLE to edit python files.
The problem is that I can edit python files with Emacs but I do not know how to run python interpreter in Emacs. When i click on "switch to interpreter", then it says "Searching for... | Place this in your `.emacs` to let emacs know where is your python interpretor
```
(setq python-shell-interpreter "path\to\your\python3.2")
```
To learn about`.emacs` you can read about it in Emacs itself.(Emacs comes with good info manuals and info mode to help to read that manual).
press the following in emacs
`... |
How do I run a python interpreter in Emacs? | 10,241,279 | 16 | 2012-04-20T06:27:08Z | 20,375,113 | 8 | 2013-12-04T12:14:51Z | [
"python",
"emacs",
"interpreter"
] | I just downloaded GNU emacs23.4, and I already have python3.2 installed in Windows7.
I have been using Python IDLE to edit python files.
The problem is that I can edit python files with Emacs but I do not know how to run python interpreter in Emacs. When i click on "switch to interpreter", then it says "Searching for... | `C-c C-z` can do this. It is the key-binding for the command `python-switch-to-python` |
Using .sort with PyMongo | 10,242,149 | 47 | 2012-04-20T07:39:59Z | 10,242,305 | 91 | 2012-04-20T07:54:13Z | [
"python",
"mongodb"
] | With PyMongo, when I try to retrieve objects sorted by their 'number' and 'date' fields like this:
```
db.test.find({"number": {"$gt": 1}}).sort({"number": 1, "date": -1})
```
I get this error:
```
TypeError: if no direction is specified, key_or_list must be an instance of list
```
What's wrong with my sort query? | `sort` should be a list of key-direction pairs, that is
```
db.test.find({"number": {"$gt": 1}}).sort([("number", 1), ("date", -1)])
```
The reason why this has to be a list is that the ordering of the arguments matters and `dict`s are not ordered in Python. |
lxml etree.iterparse error "TypeError: reading file objects must return plain strings" | 10,242,237 | 8 | 2012-04-20T07:48:01Z | 10,242,432 | 15 | 2012-04-20T08:03:01Z | [
"python",
"lxml",
"elementtree",
"iterparse"
] | I would like to parse an HTML document using lxml. I am using python 3.2.3 and lxml 2.3.4 ( <http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml> )
I am using the `etree.iterparse` to parse the document, but it returns the following run-time error:
```
Traceback (most recent call last):
File "D:\Eclipse Projects\Python... | Your StringIO buffer has unicode string. `iterparse` works with file like objects that return bytes. The following buffer should work with iterparse:
```
from io import BytesIO
some_file_like = BytesIO("<root><a>data</a></root>".encode('utf-8'))
``` |
Python None and if conditions | 10,243,137 | 2 | 2012-04-20T08:58:19Z | 10,243,151 | 10 | 2012-04-20T08:59:35Z | [
"python"
] | I have some code here:
```
m = None
n = None
if not m:
print "Something happens"
>>> Something happens
```
if I do:
```
if not m and n:
print "Something happens"
```
Nothing happens.
But I can do:
```
m, n = 1,2
if m and n:
print "Something happens"
>>> Something happens
```
Why are if and if not ha... | You have an [operator precedence](http://docs.python.org/reference/expressions.html#summary) problem.
`if not m and n` is equivalent to `if (not m) and n`. What you want is `if not m and not n` or `if not (m or n)`.
*See also: [De Morgan's Laws](http://en.wikipedia.org/wiki/De_Morgan%27s_laws)* |
python: Generating integer partitions | 10,244,180 | 7 | 2012-04-20T10:08:58Z | 10,399,049 | 7 | 2012-05-01T14:21:09Z | [
"python",
"combinatorics",
"performance",
"data-partitioning"
] | I need to generate all the [partition](https://en.wikipedia.org/wiki/Partition_%28number_theory%29) of a given integer.
I found this algorithm by Jerome Kelleher that states to be the most efficient one:
```
def accelAsc(n):
a = [0 for i in range(n + 1)]
k = 1
a[0] = 0
y = n - 1
while k != 0:
... | To generate compositions directly you can use the following algorithm:
```
def ruleGen(n, m, sigma):
"""
Generates all interpart restricted compositions of n with first part
>= m using restriction function sigma. See Kelleher 2006, 'Encoding
partitions as ascending compositions' chapters 3 and 4 for de... |
PASSWORD_HASHERS setting in Django | 10,246,463 | 11 | 2012-04-20T12:42:25Z | 10,246,947 | 24 | 2012-04-20T13:11:57Z | [
"python",
"django"
] | i have an error when ever i try to login by any User
error
> Unknown password hashing algorithm 'sahar'. Did you specify it in the
> PASSWORD\_HASHERS setting?
Views.Py
```
def Login(request):
state = "Please log in below..."
username = password = ''
if request.method == 'POST':
username = reques... | It means there is a plain text `'sahar'` stored as the password of the account of a user who tries to log in.
Update the password of the user in Admin or in `manage.py shell`
```
user = User.objects.get(username=username)
# use set_password method
user.set_password('sahar')
user.save()
# INSTEAD OF
user.password ... |
HTTP POST and GET with cookies for authentication in python | 10,247,054 | 5 | 2012-04-20T13:18:37Z | 10,248,314 | 12 | 2012-04-20T14:37:54Z | [
"python",
"http",
"authentication",
"post",
"cookies"
] | I'm trying to create a python program that logs in to my university's site using my id and password. This is the formal page for logging in: <https://webapp.pucrs.br/consulta/>
As you may notice, the two fields are named pr1 and pr2. The page uses POST to send the data. ALSO, there's a cookie that is downloaded when t... | I would try using the `requests` library. The [documentation](http://docs.python-requests.org/en/latest/user/quickstart/) is excellent, and the code ends up being much cleaner than with `urllib*`
```
$ pip install requests
```
Using a [session](http://docs.python-requests.org/en/latest/user/advanced/#session-objects)... |
What does 'site' in 'site-packages' actually mean? | 10,247,264 | 7 | 2012-04-20T13:31:14Z | 10,247,378 | 8 | 2012-04-20T13:37:20Z | [
"python",
"naming",
"nomenclature"
] | I've always been a bit curious about the rationale of the naming of `site-packages`. What does `site` mean in this context? I doubt it means 'website', and I've never heard 'site' used in relation to the installation location, or the context of the machine.
Any ideas? | I think `site` is used to mean the same thing as `local`, as in `/usr/local/*` - it's those elements that are installed locally/for this site, as opposed to those that are provided by the system. |
Python C-API functions that borrow and steal references | 10,247,779 | 9 | 2012-04-20T14:01:12Z | 10,250,720 | 7 | 2012-04-20T17:23:18Z | [
"python",
"python-c-api",
"reference-counting"
] | The standard convention in the Python C-API is that
* functions do not steal references from input arguments (that are objects)
* return values and output arguments (that are objects) own a reference
Most functions in the Python C-API follow this convention. However, there are some exceptions. I have come across the ... | A text search in the Python 2.7.2 C-API docs for the words "steal" and "borrow" gave the following lists:
**Functions that steal a reference from an input argument**
```
PyCell_SET (but not PyCell_Set)
PyList_SetItem, PyList_SET_ITEM
PyModule_AddObject
PyTuple_SetItem, PyTuple_SET_ITEM
```
**Functions with return va... |
What is a good pythonic way of finding duplicate objects? | 10,247,815 | 6 | 2012-04-20T14:03:20Z | 10,247,854 | 10 | 2012-04-20T14:06:18Z | [
"python",
"sorting",
"python-2.x"
] | I frequently use `sorted` and `groupby` to find duplicates items in an iterable. Now I see it is unreliable:
```
from itertools import groupby
data = 3 * ('x ', (1,), u'x')
duplicates = [k for k, g in groupby(sorted(data)) if len(list(g)) > 1]
print duplicates
# [] printed - no duplicates found - like 9 unique values... | **Note:** Assumes entries are hashable
```
>>> from collections import Counter
>>> data = 3 * ('x ', (1,), u'x')
>>> [k for k, c in Counter(data).iteritems() if c > 1]
[u'x', 'x ', (1,)]
``` |
python: recover exception from try block if finally block raises exception | 10,248,410 | 12 | 2012-04-20T14:43:41Z | 10,248,543 | 12 | 2012-04-20T14:52:13Z | [
"python",
"exception",
"exception-handling",
"try-catch",
"try-catch-finally"
] | Say I have some code like this:
```
try:
try:
raise Exception("in the try")
finally:
raise Exception("in the finally")
except Exception, e:
print "try block failed: %s" % (e,)
```
The output is:
```
try block failed: in the finally
```
From the point of that print statement, is there any... | I can't find any information about whether this has been backported and don't have a Py2 installation handy, but in Python 3, `e` has an attribute called `e.__context__`, so that:
```
try:
try:
raise Exception("in the try")
finally:
raise Exception("in the finally")
except Exception as e:
p... |
Determine which version of OpenCV | 10,248,880 | 17 | 2012-04-20T15:13:42Z | 10,249,392 | 21 | 2012-04-20T15:48:38Z | [
"python",
"opencv"
] | I want to write to short code snippet in python, to determine which version of OpenCV has been installed in my System. How do i do it ?
Thank you. | ```
>>> from cv2 import __version__
>>> __version__
'$Rev: 4557 $'
```
If that doesn't work then, use `cv` instead of `cv2`. |
Play video file with VLC, then quit VLC | 10,249,261 | 12 | 2012-04-20T15:40:03Z | 10,249,354 | 26 | 2012-04-20T15:46:28Z | [
"python",
"windows",
"vlc",
"subprocess"
] | I am working on a simple Python script that is supposed to do something, then play a video file, and then do some more stuff.
I am forced to do this on a **Windows XP** machine with **Python 3.2.3** and **VLC** to play my video file.
I am currently using this code...
```
vlc_path = '\\path\\to\\vlc.exe'
video_path =... | Funnily enough, vlc has a command line option for this:
```
--play-and-exit, --no-play-and-exit
Play and exit (default disabled)
```
So, just pass this option to vlc. |
Passing additional arguments using scipy.optimize.curve_fit? | 10,250,461 | 9 | 2012-04-20T17:02:42Z | 10,250,623 | 13 | 2012-04-20T17:14:18Z | [
"python",
"scipy"
] | I am writing a program in Python that will fit Gaussian and Lorentzian shapes to some given resonance data. I originally began using `scipy.optimize.leastsq` but changed to using `optimize.curve_fit` after having difficulties in retrieving the errors in the optimized parameters from the covariance matrix.
I have defin... | The great thing about python is that you can define functions that return other functions,
try currying:
```
def make_mix(numg):
def mix(x, *p):
ng = numg
p1 = p[:3*ng]
p2 = p[3*ng:]
a = sumarray(gaussian(x,p1),lorentzian(x,p2))
return a
return mix
```
and then
```
l... |
Suppressing output in python subprocess call | 10,251,391 | 20 | 2012-04-20T18:17:20Z | 10,251,529 | 26 | 2012-04-20T18:26:47Z | [
"python",
"subprocess",
"stdout"
] | For the following command:
```
subprocess.call(shlex.split(
"""/usr/local/itms/bin/iTMSTransporter -m lookupMetadata
-apple_id %s -destination %s"""%(self.apple_id, self.destination))
```
It prints the entire output into the Terminal window. How would I suppress ALL output here? I tried doi... | You can use the `stdout=` and `stderr=` parameters to `subprocess.call()` to direct `stdout` or `stderr` to a file descriptor of your choice. So maybe something like this:
```
import os
devnull = open(os.devnull, 'w')
subprocess.call(shlex.split(
'/usr/local/itms/bin/iTMSTransporter -m lookupMetadata '
'-appl... |
How can I get the current contents of an element in webdriver | 10,251,525 | 26 | 2012-04-20T18:26:35Z | 10,259,649 | 31 | 2012-04-21T14:12:33Z | [
"python",
"selenium",
"webdriver"
] | I must be thinking about this wrong.
I want to get the contents of an element, in this case a formfield, on a page that I am accessing with Webdriver/Selenium 2
Here is my broken code:
```
Element=driver.find_element_by_id(ElementID)
print Element
print Element.text
```
here is the result:
```
<selenium.webdriv... | I believe prestomanifesto was on the right track. It depends on what kind of element it is. You would need to use `element.get_attribute('value')` for input elements and 'element.text' to return the text node of an element.
You could check the WebElement object with `element.tag_name` to find out what kind of element ... |
Serializing python object instance to JSON | 10,252,010 | 27 | 2012-04-20T19:00:21Z | 10,252,138 | 43 | 2012-04-20T19:09:39Z | [
"python",
"json",
"serialization",
"pickle"
] | I am trying to create a JSON string representation of a class instance and having difficulty. Let's say the class is built like this:
```
class testclass:
value1 = "a"
value2 = "b"
```
A call to the json.dumps is made like this:
```
t = testclass()
json.dumps(t)
```
It is failing and telling me that the tes... | The basic problem is that the JSON encoder `json.dumps()` only knows how to serialize a limited set of object types by default, all built-in types. List here: <https://docs.python.org/3.3/library/json.html#encoders-and-decoders>
One good solution would be to make your class inherit from `JSONEncoder` and then implemen... |
Serializing python object instance to JSON | 10,252,010 | 27 | 2012-04-20T19:00:21Z | 17,573,507 | 9 | 2013-07-10T14:36:02Z | [
"python",
"json",
"serialization",
"pickle"
] | I am trying to create a JSON string representation of a class instance and having difficulty. Let's say the class is built like this:
```
class testclass:
value1 = "a"
value2 = "b"
```
A call to the json.dumps is made like this:
```
t = testclass()
json.dumps(t)
```
It is failing and telling me that the tes... | I just do:
```
data=json.dumps(myobject.__dict__)
```
This is not the full answer, and if you have some sort of complicated object class you certainly will not get everything. However I use this for some of my simple objects.
One that it works really well on is the "options" class that you get from the OptionParser ... |
@csrf_exempt stopped working in Django 1.4 | 10,252,238 | 13 | 2012-04-20T19:18:24Z | 10,252,521 | 18 | 2012-04-20T19:39:29Z | [
"python",
"django",
"csrf",
"django-csrf"
] | I have the following code, that was working fine in Django 1.2.5:
```
from django.views.decorators.csrf import csrf_exempt
class ApiView(object):
def __call__(self, request, *args, **kwargs):
method = request.method.upper()
return getattr(self, method)(request, *args, **kwargs)
@csrf_exempt
class... | According to the [django docs](https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-the-class):
> To decorate every instance of a class-based view, you need to decorate
> the class definition itself. To do this you apply the decorator to the
> dispatch() method of the class.
So you'd need to do ... |
@csrf_exempt stopped working in Django 1.4 | 10,252,238 | 13 | 2012-04-20T19:18:24Z | 23,046,702 | 8 | 2014-04-13T18:33:12Z | [
"python",
"django",
"csrf",
"django-csrf"
] | I have the following code, that was working fine in Django 1.2.5:
```
from django.views.decorators.csrf import csrf_exempt
class ApiView(object):
def __call__(self, request, *args, **kwargs):
method = request.method.upper()
return getattr(self, method)(request, *args, **kwargs)
@csrf_exempt
class... | Just use `csrf_exempt` in the `urls.py`. ie::
## urls.py
```
..other imports...
from django.views.decorators.csrf import csrf_exempt
from myapp.views import MyView
urlpatterns = patterns('',
url(r'^myview/(?P<parameter_name>[A-Za-z0-9-_]+)/$',
csrf_exempt(MyView.as_view()), # use csrf_exempt here
... |
How do I get a list of column names from a psycopg2 cursor? | 10,252,247 | 39 | 2012-04-20T19:18:43Z | 10,252,273 | 64 | 2012-04-20T19:20:10Z | [
"python",
"psycopg2"
] | I would like a general way to generate column labels directly from the selected column names, and recall seeing that python's psycopg2 module supports this feature. | From "Programming Python" by Mark Lutz:
```
curs.execute("Select * FROM people")
colnames = [desc[0] for desc in curs.description]
``` |
How do I get a list of column names from a psycopg2 cursor? | 10,252,247 | 39 | 2012-04-20T19:18:43Z | 22,172,390 | 11 | 2014-03-04T12:48:29Z | [
"python",
"psycopg2"
] | I would like a general way to generate column labels directly from the selected column names, and recall seeing that python's psycopg2 module supports this feature. | To **get the column names in a separate query**, you can query the information\_schema.columns table.
```
#!/usr/bin/env python3
import psycopg2
if __name__ == '__main__':
DSN = 'host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER'
column_names = []
with psycopg2... |
how to add Permissions in Django to Models and Test it using the shell | 10,252,332 | 8 | 2012-04-20T19:24:27Z | 10,252,613 | 16 | 2012-04-20T19:47:31Z | [
"python",
"django",
"django-models",
"django-forms",
"django-admin"
] | I added the Meta class in my model and synchronized the DB then created an object in the shell
it returns false so i really cant understand where is the error or what is missing is there some sort of configuration maybe in some other files ..
```
class Employer(User):#Employer inherits from User
employer_verified ... | In the example you gave, I would expect `emp.has_perm('myappname.is_member')` to indeed be `False`. Unless you explicitly give the new `Employer` object the `is_member` permission, it won't have it.
To programmatically give it the permission you need to get the actual permission object and add it to the `Employer`'s `... |
How to check whether a sentence is correct (simple grammar check in Python)? | 10,252,448 | 16 | 2012-04-20T19:33:13Z | 10,252,472 | 15 | 2012-04-20T19:34:56Z | [
"python",
"nlp",
"grammar"
] | How to check whether a sentence is valid in Python?
Examples:
```
I love Stackoverflow - Correct
I Stackoverflow love - Incorrect
``` | Check out [NLTK](http://www.nltk.org). They have support for grammars that you can use to parse your sentence. You can define a grammar, or use one that is provided, along with a context-free parser. If the sentence parses, then it has valid grammar; if not, then it doesn't. These grammars may not have the widest cover... |
How to check whether a sentence is correct (simple grammar check in Python)? | 10,252,448 | 16 | 2012-04-20T19:33:13Z | 25,142,528 | 16 | 2014-08-05T15:22:37Z | [
"python",
"nlp",
"grammar"
] | How to check whether a sentence is valid in Python?
Examples:
```
I love Stackoverflow - Correct
I Stackoverflow love - Incorrect
``` | There are various Web Services providing automated proofreading and grammar checking. Some have a Python library to simplify querying.
As far as I can tell, most of those tools (certainly After the Deadline and LanguageTool) are rule based. The checked text is compared with a large set of rules describing common error... |
Python: why print statements and subprocess.call() output are out of sync? | 10,253,698 | 3 | 2012-04-20T21:20:08Z | 10,253,723 | 8 | 2012-04-20T21:21:50Z | [
"python",
"linux",
"subprocess"
] | I am running the following piece of code (call it batch.py)
```
for config in keystoneConfig:
cmdlist = generate_cmd_list(config)
print ' '.join(cmdlist)
subprocess.call(cmdlist)
```
And redirecting the output of batch.py to another file. i.e.
> ./batch.py > output.txt
But I realize that all the output... | Python is block buffering its own output and not flushing it before `subprocess.call()`, because you redirected its output to a file instead of the console; you would need to force line buffering or disable buffering, or manually flush before the subprocess call. |
PATH issue with pytest 'ImportError: No module named YadaYadaYada' | 10,253,826 | 39 | 2012-04-20T21:32:03Z | 10,253,916 | 26 | 2012-04-20T21:39:12Z | [
"python",
"unit-testing",
"py.test"
] | I used easy\_install to install pytest on a mac and started writing tests for a project with a file structure likes so:
```
repo/
repo/app.py
repo/settings.py
repo/models.py
repo/tests/
repo/tests/test_app.py
```
run `py.test` while in the repo directory, everything behaves as you would expect
but when I try that sa... | yes, the source folder is not in python's path if you `cd` to the tests directory. you have 2 choices:
a. Add the path manually to the test files, something like:
```
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')
```
b. run the tests with the env var `PYTHONPA... |
PATH issue with pytest 'ImportError: No module named YadaYadaYada' | 10,253,826 | 39 | 2012-04-20T21:32:03Z | 18,971,504 | 38 | 2013-09-24T01:20:44Z | [
"python",
"unit-testing",
"py.test"
] | I used easy\_install to install pytest on a mac and started writing tests for a project with a file structure likes so:
```
repo/
repo/app.py
repo/settings.py
repo/models.py
repo/tests/
repo/tests/test_app.py
```
run `py.test` while in the repo directory, everything behaves as you would expect
but when I try that sa... | I had the same problem. I fixed it by adding an empty `__init__.py` file to my `tests` directory. |
PATH issue with pytest 'ImportError: No module named YadaYadaYada' | 10,253,826 | 39 | 2012-04-20T21:32:03Z | 26,544,761 | 13 | 2014-10-24T09:03:03Z | [
"python",
"unit-testing",
"py.test"
] | I used easy\_install to install pytest on a mac and started writing tests for a project with a file structure likes so:
```
repo/
repo/app.py
repo/settings.py
repo/models.py
repo/tests/
repo/tests/test_app.py
```
run `py.test` while in the repo directory, everything behaves as you would expect
but when I try that sa... | You can run with PYTHONPATH in project root
```
PYTHONPATH=. py.test
```
Or use pip install as editable import
```
pip install -e . # install package using setup.py in editable mode
``` |
PATH issue with pytest 'ImportError: No module named YadaYadaYada' | 10,253,826 | 39 | 2012-04-20T21:32:03Z | 34,140,498 | 28 | 2015-12-07T18:21:06Z | [
"python",
"unit-testing",
"py.test"
] | I used easy\_install to install pytest on a mac and started writing tests for a project with a file structure likes so:
```
repo/
repo/app.py
repo/settings.py
repo/models.py
repo/tests/
repo/tests/test_app.py
```
run `py.test` while in the repo directory, everything behaves as you would expect
but when I try that sa... | I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):
```
python -m pytest tests/
```
It works because Python adds the current directory in the PYTHONPATH for you. |
Color and Line writing using MatPlotLib | 10,254,207 | 3 | 2012-04-20T22:07:03Z | 10,256,940 | 13 | 2012-04-21T06:53:49Z | [
"python",
"matplotlib",
"graphing"
] | I am trying to graph families of curves using Matplotlib. I am graphing the data directly using scatter() and then plotting a fit line (least squares from scipy) using plot(). I do not know how many sets of data there will be beforehand, or the limits, etc.
I need to be able to cycle the colors of these lines and poin... | This tries to answer all your questions.
The code below cycles a maximum of 7 colors. If you need more you should create a more sofisticated generator, as that shown in another answer.
```
import numpy as np
from matplotlib import pyplot as plt
def get_color():
for item in ['r', 'g', 'b', 'c', 'm', 'y', 'k']:
... |
What makes a user-defined class unhashable? | 10,254,594 | 15 | 2012-04-20T22:58:40Z | 10,254,636 | 11 | 2012-04-20T23:04:37Z | [
"python",
"class",
"python-3.x",
"user-defined-types",
"hashable"
] | The [docs](http://docs.python.org/py3k/glossary.html#term-hashable) say that a class is hashable as long as it defines `__hash__` method and `__eq__` method. However:
```
class X(list):
# read-only interface of `tuple` and `list` should be the same, so reuse tuple.__hash__
__hash__ = tuple.__hash__
x1 = X()
s = {... | Simply setting the `__hash__` method to that of the `tuple` class is not enough. You haven't actually told it how to hash any differently. tuples are hashable because they are immutable. If you really wanted to make you specific example work, it might be like this:
```
class X2(list):
def __hash__(self):
r... |
Iterating on a file using Python | 10,255,273 | 27 | 2012-04-21T01:00:16Z | 10,255,293 | 46 | 2012-04-21T01:02:59Z | [
"python",
"iteration",
"file-type"
] | I have a problem to understand iterating on a file, Here I go on what i type on the interpreter and the result:
```
>>> f = open('baby1990.html', 'rU')
>>> for line in f.readlines():
>>> print(line)
>>> ...
>>> ... all the lines from the file appear here
>>> ...
```
When I try to iterate on the same open file again... | Yes, that is normal behavior. You basically read to the end of the file the first time (you can sort of picture it as reading a tape), so you can't read any more from it unless you reset it, by either using `f.seek(0)` to reposition to the start of the file, or to close it and then open it again which will start from t... |
Iterating on a file using Python | 10,255,273 | 27 | 2012-04-21T01:00:16Z | 10,255,302 | 8 | 2012-04-21T01:04:34Z | [
"python",
"iteration",
"file-type"
] | I have a problem to understand iterating on a file, Here I go on what i type on the interpreter and the result:
```
>>> f = open('baby1990.html', 'rU')
>>> for line in f.readlines():
>>> print(line)
>>> ...
>>> ... all the lines from the file appear here
>>> ...
```
When I try to iterate on the same open file again... | The file object is a *buffer*. When you read from the buffer, that portion that you read is consumed (the read position is shifted forward). When you read through the entire file, the read position is at the EOF, so it returns nothing because there is nothing left to read.
If you have to, for some reason, reset the re... |
Iterating on a file using Python | 10,255,273 | 27 | 2012-04-21T01:00:16Z | 10,255,310 | 10 | 2012-04-21T01:05:29Z | [
"python",
"iteration",
"file-type"
] | I have a problem to understand iterating on a file, Here I go on what i type on the interpreter and the result:
```
>>> f = open('baby1990.html', 'rU')
>>> for line in f.readlines():
>>> print(line)
>>> ...
>>> ... all the lines from the file appear here
>>> ...
```
When I try to iterate on the same open file again... | As the file object reads the file, it uses a pointer to keep track of where it is. If you read part of the file, then go back to it later it will pick up where you left off. If you read the whole file, and go back to the same file object, it will be like reading an empty file because the pointer is at the end of the fi... |
TypeError: expected a character buffer object when doing open() | 10,255,753 | 4 | 2012-04-21T02:49:35Z | 10,255,772 | 11 | 2012-04-21T02:53:52Z | [
"python",
"compiler-errors"
] | So I'm learning Python. I was doing a simple thing with arrays and open(), and sometimes this code works, and sometimes it doesn't! Please help!
```
print('Load? (Y/N)')
load = raw_input()
if load == "y":
fin = open("myArr.bat", "r")
myArr = fin.readline()
if load == "n":
myArr = [0, 0, 0,
... | That's because the [`write`](http://docs.python.org/library/stdtypes.html#file.write) method expects a string as the first argument, but you're passing it an array. |
TypeError: expected a character buffer object when doing open() | 10,255,753 | 4 | 2012-04-21T02:49:35Z | 10,255,800 | 8 | 2012-04-21T02:58:29Z | [
"python",
"compiler-errors"
] | So I'm learning Python. I was doing a simple thing with arrays and open(), and sometimes this code works, and sometimes it doesn't! Please help!
```
print('Load? (Y/N)')
load = raw_input()
if load == "y":
fin = open("myArr.bat", "r")
myArr = fin.readline()
if load == "n":
myArr = [0, 0, 0,
... | I'm going to guess that you get this error when you test your code and input `'n'`, but when you input `'y'`, it works just fine. This is because of these lines:
```
if load == "n":
myArr = [0, 0, 0,
0, 0, 0,
0, 0, 0]
```
This makes `myArr` a `list`. One does not simply write a list to a file. You m... |
How to convert `ctime` to `datetime` in Python? | 10,256,093 | 13 | 2012-04-21T04:05:30Z | 10,256,141 | 17 | 2012-04-21T04:16:26Z | [
"python",
"datetime"
] | ```
import time
t = time.ctime()
```
For me at the moment, `t` is `'Sat Apr 21 11:58:02 2012'`. I have more data like this.
**My question is:**
* How to convert `t` to `datetime` in Python? Are there any modules to to it?
I tried to make a time `dict` and then convert `t`, but feel like thatâs not the best way to... | You should use `strptime`: this function parses a string representing a time according to a format. The return value is a struct\_time.
The format parameter defaults to `%a %b %d %H:%M:%S %Y` which matches the formatting returned by ctime().
So in your case just try the following line, since the default format is the... |
Python C Extensions - Why must callable C functions take arguments and return PyObject * | 10,256,315 | 7 | 2012-04-21T04:50:14Z | 10,257,972 | 9 | 2012-04-21T10:04:28Z | [
"python",
"c",
"python-c-extension"
] | I'm just starting to play with Python C extensions and am curious as to why a C function, which is callable from Python must take 2 PyObject\* arguments and return a PyObject\*. I wrote the following "Hello World" extension:
```
#include <Python.h>
static PyObject *
hello_world(PyObject *self, PyObject *noargs)
{
... | There are several things to say about the various `PyObject` pointers.
1. The one required as **return type** is used for the **exception handling mechanism.** Specifically, if your function returns a null pointer, the Python interpreter will throw an exception. (You should only do that after calling one of the `PyErr... |
How to get text for a root element using lxml? | 10,258,584 | 4 | 2012-04-21T11:42:30Z | 10,261,540 | 7 | 2012-04-21T17:58:23Z | [
"python",
"lxml"
] | I'm completely stumped why lxml `.text` will give me the text for a child tag but for the root tag.
```
some_tag = etree.fromstring('<some_tag class="abc"><strong>Hello</strong> World</some_tag>')
some_tag.find("strong")
Out[195]: <Element strong at 0x7427d00>
some_tag.find("strong").text
Out[196]: 'Hello'
some_tag... | ```
from lxml import etree
XML = '<some_tag class="abc"><strong>Hello</strong> World</some_tag>'
some_tag = etree.fromstring(XML)
for element in some_tag:
print element.tag, element.text, element.tail
```
Output:
```
strong Hello World
```
For information on the `.text` and `.tail` properties, see:
* <http:... |
Python functional evaluation efficiency | 10,259,342 | 3 | 2012-04-21T13:30:51Z | 10,259,411 | 7 | 2012-04-21T13:39:32Z | [
"python"
] | If I do this:
```
x=[(t,some_very_complex_computation(y)) for t in z]
```
Apparently some\_very\_complex\_computation(y) is not dependent on t. So it should be evaluated only once. Is there any way to make Python aware of this, so it won't evaluate some\_very\_complex\_computation(y) for every iteration?
Edit: I rea... | Usually you should follow San4ez's advise and just use a temporary variable here. I will still present a few techniques that might prove useful under certain circumstances:
In general, if you want to bind a name just for a sub-expression (which is usually why you need a temporary variable), you can use a lambda:
```
... |
Is x==x ever False in Python? | 10,259,519 | 8 | 2012-04-21T13:53:39Z | 10,320,967 | 22 | 2012-04-25T17:46:05Z | [
"python",
"floating-point",
"equality"
] | I stumbled upon this line of code in SciPy's source, in the [stats module](https://github.com/scipy/scipy/blob/master/scipy/stats/distributions.py#L5171):
```
return 1.0*(x==x)
```
Is this return something other than `1.0`? In other words, is there any value of x such that `x == x` holds `False`? | According to the IEEE 754 standard not-a-number (NaN) must always compare false, no matter what it is compared to.
```
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x=float("NaN")
>>> x==x
False
``` |
Is x==x ever False in Python? | 10,259,519 | 8 | 2012-04-21T13:53:39Z | 10,321,007 | 9 | 2012-04-25T17:49:14Z | [
"python",
"floating-point",
"equality"
] | I stumbled upon this line of code in SciPy's source, in the [stats module](https://github.com/scipy/scipy/blob/master/scipy/stats/distributions.py#L5171):
```
return 1.0*(x==x)
```
Is this return something other than `1.0`? In other words, is there any value of x such that `x == x` holds `False`? | A user-defined type can override the equality operator to do whatever you want:
```
Python 3.2.2 (default, Feb 10 2012, 09:23:17)
[GCC 4.4.5 20110214 (Red Hat 4.4.5-6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... def __eq__(self, other):
... return Fal... |
How do you investigate python's implementation of built-in methods? | 10,260,814 | 6 | 2012-04-21T16:24:06Z | 10,260,899 | 9 | 2012-04-21T16:34:27Z | [
"python"
] | I'm currently going through a basic compsci course. We use Python's `in` a lot. I'm curious how it's implemented, what the code that powers `in` looks like.
I can think of how *my* implementation of such a thing would work, but something I've learned after turning in a couple homework assignments is that my ways of do... | The thing about builtin functions and types and operators and so on is that they are *not* implemented in Python. Rather, they're implemented in C, which is a much more painful and verbose programming language that won't always translate well to Python (usually because things are easier some other way in Python.)
With... |
How to set up celery workers on separate machines? | 10,260,925 | 34 | 2012-04-21T16:36:47Z | 10,261,277 | 29 | 2012-04-21T17:21:18Z | [
"python",
"celery"
] | I am new to celery.I know how to install and run one server but I need to distribute the task to multiple machines.
My project uses celery to assign user requests passing to a web framework to different machines and then returns the result.
I read the documentation but there it doesn't mention how to set up multiple ma... | My understanding is that your app will push requests into a queueing system (e.g. rabbitMQ) and then you can start any number of workers on different machines (with access to the same code as the app which submitted the task). They will pick out tasks from the message queue and then get to work on them. Once they're do... |
psycopg2 out of shared memory and hints of increase max_pred_locks_per_transaction | 10,260,994 | 3 | 2012-04-21T16:45:52Z | 10,264,097 | 8 | 2012-04-21T23:58:42Z | [
"python",
"postgresql",
"isolation-level",
"postgresql-9.1"
] | While inserting a lot of data into postgresql 9.1. using a Python script, we are getting the following error on this query:
```
X: psycopg2.ProgrammingError in /home/hosting/apps/X
X_psycopg.py:162 in : Execute 'execute' (
SELECT * FROM xml_fifo.fifo
WHERE type_id IN (1,... | PostgreSQL added new functionality to `SERIALIZABLE` transactions in version 9.1, to avoid some serialization anomalies which were previously possible at that isolation level. The error you are seeing is only possible when using these new serializable transactions. Some workloads have run into the issue you describe wh... |
determine "type of value" from a string in python | 10,261,141 | 2 | 2012-04-21T17:01:27Z | 10,261,229 | 11 | 2012-04-21T17:15:12Z | [
"python",
"regex",
"types"
] | I'm trying to write a function in python, which will determine what type of value is in string; for example
if in string is 1 or 0 or True or False the value is BIT
if in string is 0-9\*, the value is INT
if in string is 0-9+.0-9+ the value is float
if in string is stg more (text, etc) value is text
so far i have ... | Before you go too far down the regex route, have you considered using [ast.literal\_eval](http://docs.python.org/library/ast.html#ast.literal_eval)
Examples:
```
In [35]: ast.literal_eval('1')
Out[35]: 1
In [36]: type(ast.literal_eval('1'))
Out[36]: int
In [38]: type(ast.literal_eval('1.0'))
Out[38]: float
In [40]... |
How to point pip at a Mercurial branch? | 10,262,306 | 28 | 2012-04-21T19:36:03Z | 10,470,015 | 43 | 2012-05-06T11:01:53Z | [
"python",
"mercurial",
"pip"
] | I'm trying to install my application via pip to a virtualenv for testing.
Works fine for installing the `default` or `tip` like so:
```
pip install -e hg+https://username@bitbucket.org/username/app_name#egg=app_name
```
But is there any way to point to a branch, rather than just getting the tip. Not sure if this wou... | In official pip documentation in section [VCS Support](http://www.pip-installer.org/en/latest/reference/pip_install.html#vcs-support):
> Mercurial
>
> The supported schemes are: hg+http, hg+https, hg+static-http and
> hg+ssh:
>
> ```
> -e hg+http://hg.myproject.org/MyProject/#egg=MyProject
> -e hg+https://hg.myproject... |
Understanding Python's call-by-object style of passing function arguments | 10,262,920 | 11 | 2012-04-21T20:54:31Z | 10,262,945 | 11 | 2012-04-21T20:57:42Z | [
"python",
"function"
] | I am not sure I understand the concept of Python's call by object style of passing function arguments (explained here <http://effbot.org/zone/call-by-object.htm>). There don't seem to be enough examples to clarify this concept well (or my google-fu is probably weak! :D)
I wrote this little contrived Python program to ... | **The key difference is that in C-style language, a variable is a box in memory in which you put stuff. In Python, a variable is a name.**
Python is neither call-by-reference nor call-by-value. It's something much more sensible! (In fact, I learned Python before I learned the more common languages, so call-by-value an... |
Understanding Python's call-by-object style of passing function arguments | 10,262,920 | 11 | 2012-04-21T20:54:31Z | 10,262,955 | 7 | 2012-04-21T20:58:58Z | [
"python",
"function"
] | I am not sure I understand the concept of Python's call by object style of passing function arguments (explained here <http://effbot.org/zone/call-by-object.htm>). There don't seem to be enough examples to clarify this concept well (or my google-fu is probably weak! :D)
I wrote this little contrived Python program to ... | Numbers, strings, and tuples in Python are immutable; using augmented assignment will **rebind** the name.
Your other types are merely **mutated**, and remain the same object. |
Understanding Python's call-by-object style of passing function arguments | 10,262,920 | 11 | 2012-04-21T20:54:31Z | 10,263,021 | 7 | 2012-04-21T21:06:26Z | [
"python",
"function"
] | I am not sure I understand the concept of Python's call by object style of passing function arguments (explained here <http://effbot.org/zone/call-by-object.htm>). There don't seem to be enough examples to clarify this concept well (or my google-fu is probably weak! :D)
I wrote this little contrived Python program to ... | Others have already posted good answers. One more thing that I think will help:
```
x = expr
```
evaluates `expr` and binds `x` to the result. On the other hand:
```
x.operate()
```
does something *to* `x` and hence can change it (resulting in the same underlying object having a different value).
The funny cases... |
Better, more accurate mime type detection in Python | 10,263,436 | 5 | 2012-04-21T22:06:30Z | 10,263,452 | 7 | 2012-04-21T22:08:53Z | [
"python",
"mime-types",
"python-2.7"
] | Python's mimetypes module isn't especially accurate and bases its results on the file extension. The only way I can think of to get a more accurate result is to call the Unix `file` command with `subprocess.Popen` as so:
```
import subprocess
mimetype = subprocess.Popen(['file', '/path/to/file', '--mime-type', '-b'], ... | You could try out : [magic's mimetype](https://github.com/ahupp/python-magic) |
Django Invalid Block Tag: 'endfor', expected 'endblock' | 10,263,495 | 5 | 2012-04-21T22:16:26Z | 10,263,528 | 13 | 2012-04-21T22:20:41Z | [
"python",
"django",
"django-templates",
"render",
"syntax-error"
] | What could be the cause of the this `TemplateSyntaxError` in Django?
```
Invalid block tag: 'endfor', expected 'endblock'
```
My template is pretty simple so far:
```
{% extends 'base.html' %}
{% block content %}
<div id='beerslist'>
{$ for beer in beers %}
{{ beer }}
{% endfor %}
</d... | ```
{$ for beer in beers %}
```
You typed a `$` instead of `%`. That's why it doesn't recognize the `for` and complains that there's no `for` block for it to close when it sees the `endfor`. |
Use datetime.strftime() on years before 1900? ("require year >= 1900") | 10,263,956 | 20 | 2012-04-21T23:32:13Z | 10,264,070 | 10 | 2012-04-21T23:53:14Z | [
"python",
"datetime",
"strftime"
] | I used :
`utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = tup[5])
last_visit_time = "Last visit time:"+ utctime.strftime('%Y-%m-%d %H:%M:%S')`
But I have the time of 1601, so the error show:
`ValueError: year=1601 is before 1900; the datetime strftime() methods require year >= 1900`
I used p... | You can do the following:
```
>>> utctime.isoformat()
'1601-01-01T00:00:00.000050'
```
Now if you want to have exactly the same format as above:
```
iso = utctime.isoformat()
tokens = iso.strip().split("T")
last_visit_time = "Last visit time: %s %s" % (tokens[0], tokens[1].strip().split(".")[0])
```
Not that there ... |
Use datetime.strftime() on years before 1900? ("require year >= 1900") | 10,263,956 | 20 | 2012-04-21T23:32:13Z | 13,661,720 | 7 | 2012-12-01T17:18:26Z | [
"python",
"datetime",
"strftime"
] | I used :
`utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = tup[5])
last_visit_time = "Last visit time:"+ utctime.strftime('%Y-%m-%d %H:%M:%S')`
But I have the time of 1601, so the error show:
`ValueError: year=1601 is before 1900; the datetime strftime() methods require year >= 1900`
I used p... | the `isoformat` method accepts a parameter specifing the character(s) dividing the date part from the time part of a datetime obj in its representation. Therefore:
```
>>> utctime.isoformat(" ")
'1601-01-01 00:00:00.000050'
```
should do it.
Furthermore, if you want to remove the microseconds you can operate a split.... |
Error with sessionmaker | 10,264,150 | 3 | 2012-04-22T00:09:55Z | 10,264,391 | 7 | 2012-04-22T01:03:08Z | [
"python",
"class",
"sqlalchemy"
] | I can see from this question [Why are session methods unbound in sqlalchemy using sqlite?](http://stackoverflow.com/questions/3221814/why-are-session-methods-unbound-in-sqlalchemy-using-sqlite) that I need to instantiate the class for sessionmaker.
I get the same error, and I assume the 'fix' will work, only I have no... | Your problem is exactly the same as the first question you posted, and the solution should be the same as the selected answer from the same question.
The function `sessionmaker` returns a **class**, binding the engine passed in the `bind` parameter.
So, after creating the class, you have to instantiate it (haven't in... |
How to get HTML representation of a child element in BeautifulSoup? | 10,264,190 | 3 | 2012-04-22T00:21:20Z | 10,264,535 | 9 | 2012-04-22T01:38:56Z | [
"python",
"beautifulsoup"
] | Assuming my HTML is:
```
<html><body><span>This is my text</span></body></html>
```
How do I get a string representation of what's contained inside , i.e:
```
<span>This is my text</span>
``` | To get the html representation of an element just use the built in `str` function:
```
soup = BeautifulSoup("<html><body><span>This is my text</span></body></html>")
span = soup.find('span')
str(span) # Outputs '<span>This is my text</span>'
``` |
Recursive Generators in Python | 10,264,459 | 7 | 2012-04-22T01:20:43Z | 10,264,613 | 17 | 2012-04-22T02:00:03Z | [
"python",
"recursion",
"generator",
"bioinformatics"
] | I wrote a function to return a generator containing every unique combination of sub-strings a given length that contain more than n elements from a primary string.
As an illustration:
if i have 'abcdefghi' and a probe of length of two, and a threshold of 4 elements per list i'd like to get:
```
['ab', 'cd', 'ef', 'g... | > I thought that a generator would precede as far down the recursion hole as necessary until it hit the yield statement
It will recurse fine, but to get the `yield`ed value to propogate back outward, you need to do it explicitly - just like if it was a `return`, you would need to explicitly `return` the result of each... |
Read the next word in a file in python | 10,264,460 | 6 | 2012-04-22T01:20:54Z | 10,264,525 | 14 | 2012-04-22T01:37:27Z | [
"python"
] | I am looking for some words in a file in python. After I find each word I need to read the next two words from the file. I've looked for some solution but I could not find reading just the next words.
```
# offsetFile - file pointer
# searchTerms - list of words
for line in offsetFile:
for word in searchTerms:
... | An easy way to deal with this is to read the file using a generator that yields one word at a time from the file.
```
def words(fileobj):
for line in fileobj:
for word in line.split():
yield word
```
Then to find the word you're interested in and read the next two words:
```
with open("offset... |
Transform unicode string in python | 10,264,618 | 4 | 2012-04-22T02:03:43Z | 10,264,685 | 8 | 2012-04-22T02:22:55Z | [
"python",
"unicode",
"dictionary"
] | ```
{u'Status': u'OK', u'City': u'Ciri\xe8', u'TimezoneName': '', u'ZipPostalCode': '', u'CountryCode': u'IT', u'Dstoffset': u'0', u'Ip': u'x.x.x.x', u'Longitude': u'7.6', u'CountryName': u'Italy', u'RegionCode': u'12', u'Latitude': u'45.2333', u'Isdst': '', u'Gmtoffset': u'0', u'RegionName': u'Piemonte'}
```
This is ... | What you want is not clear. If by 'plaintext' you mean remove accentuation, try this:
```
>>> s = u'Ciri\xe8'
>>> from unicodedata import normalize
>>> normalize('NFKD', s).encode('ASCII', 'ignore')
'Cirie'
``` |
Transform unicode string in python | 10,264,618 | 4 | 2012-04-22T02:03:43Z | 10,264,922 | 7 | 2012-04-22T03:15:41Z | [
"python",
"unicode",
"dictionary"
] | ```
{u'Status': u'OK', u'City': u'Ciri\xe8', u'TimezoneName': '', u'ZipPostalCode': '', u'CountryCode': u'IT', u'Dstoffset': u'0', u'Ip': u'x.x.x.x', u'Longitude': u'7.6', u'CountryName': u'Italy', u'RegionCode': u'12', u'Latitude': u'45.2333', u'Isdst': '', u'Gmtoffset': u'0', u'RegionName': u'Piemonte'}
```
This is ... | Read this: <http://nedbatchelder.com/text/unipain.html>
Then just print it:
```
>>> data = {u'City':u'Ciri\xe8'}
>>> data['City']
u'Ciri\xe8'
>>> print data['City']
Ciriè
```
If you don't print it, Python prints a safe representation of the string, indicating it is Unicode text `u''`, and that it contains a non-ASC... |
How to use entry widget in Tkinter | 10,264,654 | 3 | 2012-04-22T02:14:44Z | 10,264,757 | 8 | 2012-04-22T02:38:43Z | [
"python",
"tkinter"
] | I am trying to make a program in Tkinter that requires the entry widget to be used. I have looked at different websites, but none of them have CLEARLY expalined how to use the Entry widget and its functions. Will someone please explain it or give me a great link?
Help would be appreciated on how to get information fro... | This seems like a very general question, but [here](http://effbot.org/tkinterbook/entry.htm)'s a website that has great detail, and here's a very simple general example:
```
import Tkinter as tk
class application:
def __init__(self,window):
""" Initalize the Application """
self.myentrybox = tk.En... |
Python: Reducing memory usage of dictionary | 10,264,874 | 31 | 2012-04-22T03:03:18Z | 10,265,422 | 59 | 2012-04-22T05:11:57Z | [
"python",
"memory",
"dictionary",
"compression",
"n-gram"
] | I'm trying to load a couple of files into the memory. The files have either of the following 3 formats:
* string TAB int
* string TAB float
* int TAB float.
Indeed, they are ngram statics files, in case this helps with the solution. For instance:
```
i_love TAB 10
love_you TAB 12
```
Currently, the pseudocode of I'... | I cannot offer a complete strategy that would help improve memory footprint, but I believe it may help to analyse what exactly is taking so much memory.
If you look at the **Python implementation** of dictionary (which is a relatively straight-forward implementation of a hash table), as well as the implementation of t... |
Urllib2 & BeautifulSoup : Nice couple but too slow - urllib3 & threads? | 10,265,115 | 6 | 2012-04-22T03:59:31Z | 10,291,834 | 8 | 2012-04-24T04:41:29Z | [
"python",
"multithreading",
"performance",
"beautifulsoup",
"urllib2"
] | I was looking to find a way to optimize my code when I heard some good things about threads and urllib3. Apparently, people disagree which solution is the best.
The problem with my script below is the execution time: so slow!
**Step 1**: I fetch this page
<http://www.cambridgeesol.org/institutions/results.php?region=... | Consider using something like [workerpool](http://pypi.python.org/pypi/workerpool/). Referring to the [Mass Downloader](https://github.com/shazow/workerpool/wiki/Mass-Downloader) example, combined with [urllib3](http://pypi.python.org/pypi/urllib3) would look something like:
```
import workerpool
import urllib3
URL_L... |
"python -v" output too long | 10,265,409 | 3 | 2012-04-22T05:09:15Z | 10,265,419 | 8 | 2012-04-22T05:11:38Z | [
"python"
] | I just installed Ubuntu on my laptop, and I entered `python -v` in the terminal to see if Python was installed. It is indeed installed, but before the line detailing the version I have installed (e.g. `Python 2.7.2+ (default, Oct 4 2011, 20:03:08)`, there is a large amount of output with lines like:
```
# installing z... | You need to use uppercase V for the version. the `-v` flag means "verbose", and will show all its import search activity . |
Fail to get data on using read() of StringIO in python | 10,265,593 | 34 | 2012-04-22T05:55:02Z | 10,265,611 | 58 | 2012-04-22T06:00:35Z | [
"python",
"stringio"
] | Using Python2.7 version. Below is my sample code.
```
import StringIO
import sys
buff = StringIO.StringIO()
buff.write("hello")
print buff.read()
```
in the above program, read() returns me nothing where as getvalue() returns me "hello". Can anyone help me out in fixing the issue? I need read() because my following ... | You need to reset the buffer position to the beginning. You can do this by doing `buff.seek(0)`.
Every time you read or write to the buffer, the position is advanced by one. Say you start with an empty buffer.
The buffer value is `""`, the buffer pos is `0`.
You do `buff.write("hello")`. Obviously the buffer value is... |
Obtain Active window using Python | 10,266,281 | 8 | 2012-04-22T08:08:04Z | 11,141,001 | 7 | 2012-06-21T15:01:16Z | [
"python",
"active-window"
] | I would like to get the active window on the screen using python.
For example, the management interface of the router where you enter the username and password as admin
That admin interface is what I want to capture using python to automate the entry of username and password.
What imports would I require in order to... | On windows, you can use the python for windows extensions (http://sourceforge.net/projects/pywin32/):
```
from win32gui import GetWindowText, GetForegroundWindow
print GetWindowText(GetForegroundWindow())
```
(Found this on <http://scott.sherrillmix.com/blog/programmer/active-window-logger/>) |
Showing and Hiding widgets | 10,267,465 | 4 | 2012-04-22T11:16:07Z | 10,268,076 | 11 | 2012-04-22T12:50:10Z | [
"python",
"user-interface",
"tkinter"
] | How do you show and hide widgets in Tkinter? I want to have an entry box, but not have it shown at all times. Can someone show me the functions to show and hide entry widgets and other widgets in tkinter? I want to be able to do this without having multiple frames. | [This has been answered before on stackoverflow](http://stackoverflow.com/q/3819354/7432). The short answer is, you can use [grid\_remove](http://effbot.org/tkinterbook/grid.htm#Tkinter.Grid.grid_remove-method) which will cause the widget to be removed if it was previously added via grid. `grid_remove` remembers where ... |
Python class inheritance: AttributeError: '[SubClass]' object has no attribute 'xxx' | 10,268,603 | 11 | 2012-04-22T14:05:36Z | 10,268,707 | 10 | 2012-04-22T14:18:11Z | [
"python",
"inheritance"
] | I have the following base class and subclass:
```
class Event(object):
def __init__(self, sr1=None, nr1=None, foo=None, foobar=None, nr2=None, sr2=None, flag = False):
self.sr1 = sr1
self.nr1 = nr1
self.foo = foo
self.foobar = foobar
self.nr2 = nr2
self.sr2 = sr2
... | Your subclass should be:
```
class TypeTwoEvent(Event):
def __init__(self, level=None, *args, **kwargs):
super(TypeTwoEvent, self).__init__(*args, **kwargs)
self.sr1 = level
self.state = STATE_EVENT_TWO
def __repr__(self):
return "Type Two event (Level @: {0:.2f})".format(sel... |
Using decode() vs. regex to unescape this string | 10,268,918 | 7 | 2012-04-22T14:45:30Z | 10,427,583 | 13 | 2012-05-03T08:18:15Z | [
"python",
"regex",
"string",
"escaping",
"decode"
] | I have the following string and I'm trying to figure out the best practice for unescaping it.
The solution has to be somewhat flexible in that I'm receiving this input from an API and I can't be absolutely certain that the current character structure (`\n` as opposed to `\r`) will always be the same.
`'"If it ain\'t ... | The codec you're looking for is `string-escape`:
```
>>> print "\\'".decode("string-escape")
'
```
I'm not sure what version they added it in, though... could be an older version you're using that doesn't have it. I'm running:
```
Python 2.6.6 (r266:84292, Mar 25 2011, 19:36:32)
[GCC 4.5.2] on linux2
``` |
python 3.2 error saying urllib.parse.urlencode() is not defined | 10,268,966 | 27 | 2012-04-22T14:52:22Z | 10,269,001 | 49 | 2012-04-22T14:56:15Z | [
"python",
"python-3.2"
] | I am trying to use urllib.parse.urlencode() method in one of my scripts.
import urllib
```
#!/usr/bin/python3.2
import urllib
data = urllib.parse.urlencode({'type': 'device_code','client_id': 150792241632891})
```
It was working before but now I get following error.
**Output**
```
Traceback (most recent call last... | You're not showing the imports in your program, so I can't be sure, but I bet you did
```
import urllib
```
which will not import and re-export the separate module `urllib.parse`. Do
```
import urllib.parse
```
instead.
(`import urllib` is rather senseless in Python 3.x, since all the functionality is in the submo... |
PIL - Convert GIF Frames to JPG | 10,269,099 | 13 | 2012-04-22T15:11:03Z | 10,335,802 | 16 | 2012-04-26T14:44:38Z | [
"python",
"image-processing",
"python-imaging-library",
"gif",
"jpeg"
] | I tried to convert an gif to single images with Python Image Library,
but it results in weird frames
The Input gif is:

In my first try, i tried to convert the image with Image.new to an
RGB image, with 255,255,255 as white background - like in any other
example i've... | First of all, `JPEG` doesn't support transparency! But that's not the only problem.. As you move to the next frame of the `GIF` the `palette` information is lost ([problem witn PIL?](http://mail.python.org/pipermail/image-sig/2008-November/005273.html)) - so `PIL` is unable to correctly convert to the `RGBA` framework ... |
case-insensitive list sorting, without lowercasing the result? | 10,269,701 | 52 | 2012-04-22T16:20:06Z | 10,269,708 | 32 | 2012-04-22T16:21:03Z | [
"python",
"string",
"list",
"sorting",
"case-insensitive"
] | I have a list of strings like this:
```
['Aden', 'abel']
```
I want to sort the items, case-insensitive.
So I want to get:
```
['abel', 'Aden']
```
But I get the opposite with `sorted()` or `list.sort()`, because uppercase appears before lowercase.
How can I ignore the case? I've seen solutions which involves lowe... | ```
>>> x = ['Aden', 'abel']
>>> sorted(x, key=str.lower) # Or unicode.lower if all items are unicode
['abel', 'Aden']
```
In Python 3 `str` is unicode but in Python 2 you can use this more general approach which works for both `str` and `unicode`:
```
>>> sorted(x, key=lambda s: s.lower())
['abel', 'Aden']
``` |
case-insensitive list sorting, without lowercasing the result? | 10,269,701 | 52 | 2012-04-22T16:20:06Z | 10,269,828 | 74 | 2012-04-22T16:36:40Z | [
"python",
"string",
"list",
"sorting",
"case-insensitive"
] | I have a list of strings like this:
```
['Aden', 'abel']
```
I want to sort the items, case-insensitive.
So I want to get:
```
['abel', 'Aden']
```
But I get the opposite with `sorted()` or `list.sort()`, because uppercase appears before lowercase.
How can I ignore the case? I've seen solutions which involves lowe... | The following works in Python 2:
```
sorted_list = sorted(unsorted_list, key=lambda s: s.lower())
```
It works for both normal and unicode strings, since they both have a `lower` method.
In Python 2 it works for a mix of normal and unicode strings, since values of the two types can be compared with each other. Pytho... |
Is a spawned subprocess considered a new dyno on Heroku? | 10,269,845 | 8 | 2012-04-22T16:38:05Z | 10,269,954 | 9 | 2012-04-22T16:51:19Z | [
"python",
"heroku",
"web",
"backgroundworker",
"flask"
] | I just moved from Epio to Heroku and after reading about their new process model and I was wondering how Heroku handles subprocesses. The FAQ says [you can create subprocesses](https://devcenter.heroku.com/articles/python-faq#can_i_spawn_and_control_threads_and_subprocesses), but doesn't describe any of the implication... | Subprocesses are handled by a single dyno.
I'm not a python developer but I use Unicorn on my Heroku sites (Rails) usually with 4 subprocesses all contained within a single dyno. The amount of subprocesses you spawn needs to be mindful of memory consumption - you get 512Mb per dyno to play with. |
How to draw a GdkPixbuf using GTK3 and PyGObject | 10,270,080 | 4 | 2012-04-22T17:05:53Z | 10,547,095 | 7 | 2012-05-11T07:16:59Z | [
"python",
"gtk3",
"pygobject"
] | I have a small application that uses a `DrawingArea` to draw a simple map using `PyGObject` and `GTK3`.
I load a `Pixbuf` using
```
from gi.repository import Gtk, GdkPixbuf
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size("logo.png", 25, 25)
```
and then try to draw it in the `DrawingArea`'s draw event signal
```
de... | The new *draw* signal uses a callback that already passes the cairo context as a parameter, you don't need to do stuff like `window = widget.get_window()` like you did in PyGtk to get the cairo context while attending the *expose-event* signal. In PYGObject is simpler:
```
import cairo
class Foo(object):
def __in... |
Installing Theano on EPD (Windows x64) | 10,270,871 | 2 | 2012-04-22T18:34:14Z | 11,597,181 | 7 | 2012-07-22T01:41:41Z | [
"python",
"windows",
"enthought",
"theano"
] | I'm trying to install Theano on Enthought Python Distribution (EPD), but I am getting a weird error. Here is what my installation looks like:
* I have installed EPD to `C:\Python27`.
* After that, I have installed `pip` by using `easy_install pip`
* I installed Theano by using `pip install Theano`
* To test, I start `... | The last release of Theano(0.5) has some problem on Windows. You need to install the bleeding edge version. You can update your version like this:
```
pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
```
This should solve the problem. If not, you probably have some conflict with a different inst... |
python: How do I capture a variable declared in a non global ancestral outer scope? | 10,270,970 | 12 | 2012-04-22T18:47:55Z | 10,271,078 | 7 | 2012-04-22T18:59:37Z | [
"python",
"scope"
] | Given:
```
def f():
x = 0
def g():
h()
def h():
x += 1
print(x)
g()
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in f
File "<stdin>", line 4, in g
File "<stdin>", line 6, in h
UnboundLocalError: local variable 'x... | You can make `x` a [function attribute](http://www.python.org/dev/peps/pep-0232/):
```
def f():
f.x = 0
def g():
h()
def h():
f.x += 1
print(f.x)
g()
```
Also, as of Python 3, you can use [`nonlocal`](http://docs.python.org/release/3.0/reference/simple_stmts.html#the-nonlocal-s... |
Python Oauth2 - login with Google | 10,271,110 | 14 | 2012-04-22T19:03:56Z | 10,546,639 | 23 | 2012-05-11T06:41:20Z | [
"python",
"oauth",
"token"
] | I have been searching for 2 days for an answer, but nothing came up.
I am trying to make integrate Oauth2 for login with Google on Django. The code I have throws an exception - "The token is invalid".
This happens:
```
resp, content = client.request(access_token_url, "POST")
if resp['status'] != '200':
p... | After a long time, and many hours spent gone to waste, I gave up with OAuth2 since it is difficult to configure, and all I need is to log a user in. The following code should help someone who needs to do something similar, and can be customized. All I did was follow the instructions on forming the urls and such here ->... |
How to perform element-wise multiplication of two lists in Python? | 10,271,484 | 38 | 2012-04-22T19:45:55Z | 10,271,498 | 44 | 2012-04-22T19:47:43Z | [
"python",
"list",
"multiplying",
"elementwise-operations"
] | I want to perform an element wise multiplication, to multiply two lists together by value in Python, like we can do it in Matlab.
This is how I would do it in Matlab.
```
a = [1,2,3,4]
b = [2,3,4,5]
a .* b = [2, 6, 12, 20]
```
A list comprehension would give 16 list entries, for every combination `x * y` of `x` from... | Since you're already using `numpy`, it makes sense to store your data in a `numpy` array rather than a list. Once you do this, you get things like element-wise products for free:
```
In [1]: import numpy as np
In [2]: a = np.array([1,2,3,4])
In [3]: b = np.array([2,3,4,5])
In [4]: a * b
Out[4]: array([ 2, 6, 12, 2... |
How to perform element-wise multiplication of two lists in Python? | 10,271,484 | 38 | 2012-04-22T19:45:55Z | 10,271,504 | 119 | 2012-04-22T19:48:34Z | [
"python",
"list",
"multiplying",
"elementwise-operations"
] | I want to perform an element wise multiplication, to multiply two lists together by value in Python, like we can do it in Matlab.
This is how I would do it in Matlab.
```
a = [1,2,3,4]
b = [2,3,4,5]
a .* b = [2, 6, 12, 20]
```
A list comprehension would give 16 list entries, for every combination `x * y` of `x` from... | Use a list comprehension mixed with `zip()`:.
```
[a*b for a,b in zip(lista,listb)]
``` |
How to perform element-wise multiplication of two lists in Python? | 10,271,484 | 38 | 2012-04-22T19:45:55Z | 22,242,119 | 12 | 2014-03-07T05:19:03Z | [
"python",
"list",
"multiplying",
"elementwise-operations"
] | I want to perform an element wise multiplication, to multiply two lists together by value in Python, like we can do it in Matlab.
This is how I would do it in Matlab.
```
a = [1,2,3,4]
b = [2,3,4,5]
a .* b = [2, 6, 12, 20]
```
A list comprehension would give 16 list entries, for every combination `x * y` of `x` from... | You can try multiplying each element in a loop. The short hand for doing that is
```
ab = [a[i]*b[i] for i in range(len(a))]
``` |
Python: Iterating lists with different amount of dimensions, is there a generic way? | 10,271,981 | 10 | 2012-04-22T20:48:25Z | 10,272,023 | 15 | 2012-04-22T20:54:15Z | [
"python",
"arrays",
"list",
"loops",
"multidimensional-array"
] | ```
# 2x3 dimensional list
multidim_list = [
[1,2,3],
[4,5,6],
]
# 2x3x2 dimensional list
multidim_list2 = [
[
[1,2,3],
[4,5,6],
],
[
[7,8... | Recursion is your friend:
```
from collections import MutableSequence
def multiply(list_):
for index, item in enumerate(list_):
if isinstance(item, MutableSequence):
multiply(item)
else:
list_[index] *= 2
```
You could just do `isinstance(item, list)` instead of `isinstance... |
Python: Iterating lists with different amount of dimensions, is there a generic way? | 10,271,981 | 10 | 2012-04-22T20:48:25Z | 10,272,025 | 8 | 2012-04-22T20:54:26Z | [
"python",
"arrays",
"list",
"loops",
"multidimensional-array"
] | ```
# 2x3 dimensional list
multidim_list = [
[1,2,3],
[4,5,6],
]
# 2x3x2 dimensional list
multidim_list2 = [
[
[1,2,3],
[4,5,6],
],
[
[7,8... | You can make use of numpy:
```
import numpy as np
arr_1 = np.array(multidim_list)
arr_2 = np.array(multidim_list2)
```
Result:
```
>>> arr_1*2
array([[ 2, 4, 6],
[ 8, 10, 12]])
>>> arr_2*2
array([[[ 2, 4, 6],
[ 8, 10, 12]],
[[14, 16, 18],
[20, 22, 24]]])
``` |
Why does my pylab animation slow down with each update? | 10,272,478 | 6 | 2012-04-22T21:57:35Z | 10,272,967 | 7 | 2012-04-22T23:09:13Z | [
"python",
"matplotlib"
] | I'd like to display a simple animation by calling `imshow` in a for loop. Here's a demo of my problem:
```
import pylab,time
images = [pylab.uniform(0,255,(50,50)) for _ in xrange(40)]
pylab.ion()
timings = []
for img in images:
tic = time.time()
pylab.imshow(img)
pylab.draw()
toc = time.time()
timings.appen... | Things are slowing down because you're adding more and more images and drawing them *all* each time.
Either 1) clear the plot between each image (In your case, `pylab.cla()`), or better yet 2) don't make a new image, just set the data of the existing image to the new data.
As an example of using `cla()`:
```
import ... |
How do I import a Python script from a sibling directory? | 10,272,879 | 9 | 2012-04-22T22:57:18Z | 10,272,910 | 9 | 2012-04-22T23:00:37Z | [
"python",
"import",
"path",
"pythonpath"
] | Here is the directory structure:
```
parent_dir/
foo_dir/
foo.py
bar_dir/
bar.py
```
How do I import bar.py into foo.py? | If all occurring directories are Python *packages*, i.e. they all contain `__init__.py`, then you can use
```
from ..bar_dir import bar
```
If the directories aren't Python packages, you can do this by messing around with `sys.path`, but you shouldn't. |
Multiple IF conditions in a python list comprehension | 10,272,898 | 12 | 2012-04-22T22:59:31Z | 10,272,927 | 14 | 2012-04-22T23:03:08Z | [
"python",
"conditional",
"list-comprehension"
] | I was wondering, is it possible to put multiple `if` conditions in a list comprehension? I didn't find anything like this in the docs.
I want to be able to do something like this
```
ar=[]
for i in range(1,n):
if i%4 == 0: ar.append('four')
elif i%6 == 0: ar.append('six')
else: ar.append(i)
```
using a list co... | How about
```
ar = [('four' if i % 4 == 0 else ('six' if i % 6 == 0 else i)) for i in range(1, n)]
```
For example, if `n = 30` this is
```
[1, 2, 3, 'four', 5, 'six', 7, 'four', 9, 10, 11, 'four', 13, 14, 15, 'four', 17, 'six', 19, 'four', 21, 22, 23, 'four', 25, 26, 27, 'four', 29]
```
ETA: Here's how you could a... |
Concise way to find "key" difference between 2 dictionaries? | 10,272,909 | 5 | 2012-04-22T23:00:32Z | 10,272,958 | 15 | 2012-04-22T23:07:51Z | [
"python",
"dictionary",
"set",
"set-difference"
] | I needed to compare 2 dictionaries to find the set of keys in one dictionary which was not in the other.
I know that Python *set* objects support:
```
set3=set1-set2
```
but I can't do:
```
dict3=dict1-dict2
```
or:
```
missingKeys=dict1.keys()-dict2.keys()
```
(I was a little surprised by the last point, becaus... | Python 2.7:
```
>>> d = {1:2, 2:3, 3:4}
>>> d2 = {2:20, 3:30}
>>> set(d)-set(d2)
set([1])
```
Python 3.2:
```
>>> d = {1:2, 2:3, 3:4}
>>> d2 = {2:20, 3:30}
>>> d.keys()-d2.keys()
{1}
``` |
ImportError: cannot import name ABCMeta - Python Error in PyDev on Linux | 10,273,373 | 3 | 2012-04-23T00:18:00Z | 10,273,546 | 13 | 2012-04-23T00:46:46Z | [
"python",
"pydev"
] | I came across this strange error while writing code using PyDev on Linux. Even a simple code like this produces error
```
print 'Hello World'
```
and the error is here
```
True
Traceback (most recent call last):
File "/usr/lib/python2.7/site.py", line 62, in <module>
import os
File "/usr/lib/python2.7/os.py"... | My guess is that you have a file named either `abc.py` or `abc.pyc` in your working directory or PYTHONPATH and that one shadows the stdlib `abc` module. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.