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
How to get the list of options that Python was compiled with?
10,192,758
29
2012-04-17T14:02:05Z
25,047,505
7
2014-07-30T21:43:09Z
[ "python", "compilation", "packages" ]
You can compile Python in various ways. I'd like to find out with which options my Python was compiled. Concrete use-case: was my Python compiled with readline? I know I can see this by doing "import readline", but I'd like to see a list of compilation setting for my Python binary. Edit: I mean the Python executable ...
And another way to do it... Python supplies scripts per installed version... ``` ls -l /usr/bin/python*config* 16 Dec 21 2013 /usr/bin/python-config -> python2.7-config 16 Dec 21 2013 /usr/bin/python2-config -> python2.7-config 33 Mar 22 18:57 /usr/bin/python2.7-config -> x86_64-linux-gnu-pytho...
Python - translate a table to a hierarchical dictionary
10,193,235
5
2012-04-17T14:31:06Z
10,193,310
8
2012-04-17T14:35:25Z
[ "python", "dictionary", "nested" ]
I have a table of the form: ``` A1, B1, C1, (value) A1, B1, C1, (value) A1, B1, C2, (value) A1, B2, C1, (value) A1, B2, C1, (value) A1, B2, C2, (value) A1, B2, C2, (value) A2, B1, C1, (value) A2, B1, C1, (value) A2, B1, C2, (value) A2, B1, C2, (value) A2, B2, C1, (value) A2, B2, C1, (value) A2, B2, C2, (value) A2, B2,...
``` input = [('A1', 'B1', 'C1', 'Value'), (...)] from collections import defaultdict tree = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) #Alternatively you could use partial() rather than lambda: #tree = defaultdict(partial(defaultdict, partial(defaultdict, list))) for x, y, z, value in input: tre...
custom matplotlib plot : chess board like table with colored cells
10,194,482
8
2012-04-17T15:45:10Z
10,195,347
23
2012-04-17T16:38:52Z
[ "python", "matplotlib", "pandas" ]
I am starting to render plots with matplotlib as I learn both python and this interesting plotting library. I need help with a custom plot for a problem I am working on. May be there is an inbuilt function already for this. Problem: I am trying to draw a table(rectangle) as a plot with 96 individual cells ( 8 rows X 1...
Basically, you can just use `imshow` or `matshow`. However, I'm not quite clear what you mean. If you want a chessboard with every "white" cell colored by some other vector, you could do something like this: ``` import matplotlib.pyplot as plt import numpy as np # Make a 9x9 grid... nrows, ncols = 9,9 image = np.ze...
Sorting a defaultdict by value in python
10,194,713
8
2012-04-17T15:57:36Z
10,194,976
22
2012-04-17T16:13:04Z
[ "python", "sorting", "dictionary", "defaultdict" ]
I have a data-structure which is something like this: The population of three cities for different year are as follows. ``` Name 1990 2000 2010 A 10 20 30 B 20 30 10 C 30 10 20 ``` I am using a `defaultdict` to store the data. ``` from collections import defaultdict cityPopulation=defaultdi...
``` >>> sorted(cityPopulation.iteritems(),key=lambda (k,v): v[0],reverse=True) #1990 [('C', [30, 10, 20]), ('B', [20, 30, 10]), ('A', [10, 20, 30])] >>> sorted(cityPopulation.iteritems(),key=lambda (k,v): v[2],reverse=True) #2010 [('A', [10, 20, 30]), ('C', [30, 10, 20]), ('B', [20, 30, 10])] ``` Note in python 3 you ...
How to dynamically add / remove periodic tasks to Celery (celerybeat)
10,194,975
31
2012-04-17T16:13:04Z
10,225,736
16
2012-04-19T10:00:53Z
[ "python", "celery", "celerybeat" ]
If I have a function defined as follows: ``` def add(x,y): return x+y ``` Is there a way to dynamically add this function as a celery PeriodicTask and kick it off at runtime? I'd like to be able to do something like (pseudocode): ``` some_unique_task_id = celery.beat.schedule_task(add, run_every=crontab(minute="*/...
No, I'm sorry, this is not possible with the regular celerybeat. But it's easily extensible to do what you want, e.g. the django-celery scheduler is just a subclass reading and writing the schedule to the database (with some optimizations on top). Also you can use the django-celery scheduler even for non-Django proje...
How to dynamically add / remove periodic tasks to Celery (celerybeat)
10,194,975
31
2012-04-17T16:13:04Z
17,524,879
26
2013-07-08T10:55:52Z
[ "python", "celery", "celerybeat" ]
If I have a function defined as follows: ``` def add(x,y): return x+y ``` Is there a way to dynamically add this function as a celery PeriodicTask and kick it off at runtime? I'd like to be able to do something like (pseudocode): ``` some_unique_task_id = celery.beat.schedule_task(add, run_every=crontab(minute="*/...
This question was answered on [google groups](https://groups.google.com/forum/#!msg/celery-users/CZXCh8sCK5Q/ihZgMV2HWWYJ). I AM NOT THE AUTHOR, all credit goes to Jean Mark > Here's a proper solution for this. Confirmed working, In my scenario, > I sub-classed Periodic Task and created a model out of it since I can ...
Why does django-lint tell me the `auto_now_add` is deprecated?
10,195,020
7
2012-04-17T16:15:42Z
10,195,058
10
2012-04-17T16:18:06Z
[ "python", "django", "datetime", "last-modified", "pylint" ]
Hi fellow Djangonauts: I checked my project with [django-lint](https://chris-lamb.co.uk/projects/django-lint/), and it yields: ``` W:211,16:MyModel: timestamp: Uses superceded auto_now or auto_now_add ``` The [commit message](https://github.com/lamby/django-lint/commit/131d6cdaa83e7e196246387471c321991ef59696): ```...
The correct fix is to pass a callable as the field's `default` that returns the appropriate datetime, e.g. `datetime.datetime.now`.
How to retrieve SQL result column value using column name in Python?
10,195,139
15
2012-04-17T16:23:43Z
10,195,344
31
2012-04-17T16:38:38Z
[ "python", "mysql" ]
Is there a way to retrieve SQL result column value using column name instead of column index in Python? I'm using Python 3 with mySQL. The syntax I'm looking for is pretty much like the Java construct: ``` Object id = rs.get("CUSTOMER_ID"); ``` I've a table with quite a number of columns and it is a real pain to cons...
The [MySQLdb](http://sourceforge.net/projects/mysql-python/) module has a [DictCursor](http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.cursors.DictCursor-class.html): Use it like this (taken from [Writing MySQL Scripts with Python DB-API](http://www.kitebird.com/articles/pydbapi.html)): ``` cursor = ...
Python: urllib2.HTTPError: HTTP Error 401: Unauthorized
10,195,915
6
2012-04-17T17:18:28Z
11,162,326
16
2012-06-22T18:48:07Z
[ "python", "authentication" ]
I was trying to load a web page, but I ran into this problem. I do have the username and password, but I don't know how to use them in python code. I looked up on python tutorial, and this is what I wrote: ``` import urllib2 password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() username = 'user' password = 'pass' ...
Here is working code ``` import urllib2 url = 'http://www.abc.com/index.html' username = 'user' password = 'pass' p = urllib2.HTTPPasswordMgrWithDefaultRealm() p.add_password(None, url, username, password) handler = urllib2.HTTPBasicAuthHandler(p) opener = urllib2.build_opener(handler) urllib2.install_opener(opener...
How to remove convexity defects in a Sudoku square?
10,196,198
125
2012-04-17T17:39:18Z
10,226,971
174
2012-04-19T11:22:54Z
[ "python", "opencv", "computer-vision", "sudoku" ]
I was doing a fun project: Solving a Sudoku from an input image using OpenCV (as in Google goggles etc). And I have completed the task, but at the end I found a little problem for which I came here. I did the programming using Python API of OpenCV 2.3.1. Below is what I did : 1. Read the image 2. Find the contours 3...
I have a solution that works, but you'll have to translate it to OpenCV yourself. It's written in Mathematica. The first step is to adjust the brightness in the image, by dividing each pixel with the result of a closing operation: ``` src = ColorConvert[Import["http://davemark.com/images/sudoku.jpg"], "Grayscale"]; w...
How to remove convexity defects in a Sudoku square?
10,196,198
125
2012-04-17T17:39:18Z
11,366,549
146
2012-07-06T16:58:32Z
[ "python", "opencv", "computer-vision", "sudoku" ]
I was doing a fun project: Solving a Sudoku from an input image using OpenCV (as in Google goggles etc). And I have completed the task, but at the end I found a little problem for which I came here. I did the programming using Python API of OpenCV 2.3.1. Below is what I did : 1. Read the image 2. Find the contours 3...
Nikie's answer solved my problem, but his answer was in Mathematica. So I thought I should give its OpenCV adaptation here. But after implementing I could see that OpenCV code is much bigger than nikie's mathematica code. And also, I couldn't find interpolation method done by nikie in OpenCV ( although it can be done u...
Python Pandas: how to turn a DataFrame with "factors" into a design matrix for linear regression?
10,196,860
10
2012-04-17T18:26:39Z
11,705,182
7
2012-07-28T22:32:03Z
[ "python", "dataframe", "regression", "factors" ]
If memory servies me, in R there is a data type called factor which when used within a DataFrame can be automatically unpacked into the necessary columns of a regression design matrix. For example, a factor containing True/False/Maybe values would be transformed into: ``` 1 0 0 0 1 0 or 0 0 1 ``` for the purpose of u...
There is a new module called patsy that solves this problem. The quickstart linked below solves exactly the problem described above in a couple lines of code. * <http://patsy.readthedocs.org/en/latest/overview.html> * <http://patsy.readthedocs.org/en/latest/quickstart.html> Here is an example usage: ``` import panda...
Pythonic Way To Call A Class Function If I have A List of Instances
10,198,609
3
2012-04-17T20:27:03Z
10,198,654
10
2012-04-17T20:30:16Z
[ "class", "python" ]
So I have a list containing a number of instances of a class. As time moves forward, I would like, at each step, to call the `run` method of the class. So far, I have what's below. But is there a better or more Pythonic way of achieving the `for c in objs:` block? Thanks! ``` #!/usr/bin/python class the_class: ...
No, what you have is perfectly reasonable and Pythonic. The list comprehension syntax: ``` [c.run() for c in objs] ``` Saves you one line, but using list comprehensions for side effects is generally considered bad style.
Python - Numpy: How can I simultaneously select all odd rows and all even columns of an array
10,198,747
9
2012-04-17T20:37:03Z
10,198,840
32
2012-04-17T20:43:26Z
[ "python", "numpy" ]
Im new to programming and i need a programm, that can select all odd rows and all even columns of a Numpy array at the same time in one code. here is what i tried: ``` >In [78]: a >Out[78]: >array([[ 1, 2, 3, 4, 5], > [ 6, 7, 8, 9, 10], > [11, 12, 13, 14, 15], > [16, 17, 18, 19, 20]]) > >In [...
Let's say you have this array, x: ``` >>> import numpy >>> x = numpy.array([[ 1, 2, 3, 4, 5], ... [ 6, 7, 8, 9, 10], ... [11, 12, 13, 14, 15], ... [16, 17, 18, 19, 20]]) ``` To get every other odd row, like you mentioned above: ``` >>> x[::2] array([[ 1, 2, 3, 4, 5], [11, 12, 13, 14, 15]]) ``` To ...
python: using io.BufferedReader on a stream obtained with open()?
10,199,226
8
2012-04-17T21:11:58Z
10,199,522
9
2012-04-17T21:34:19Z
[ "python", "io", "python-2.7", "buffered" ]
I want to use a buffered stream because I want to use a `peek()` method to peek ahead but use my stream with another method that expects a file-like object. (I'd use `seek()` but may have to handle piped-in I/O that doesn't support random access.) But this test case fails: AttributeError: 'file' object has no attribu...
By the looks of your `print` statement, you're using Python 2. On that version, a `file` is not a valid argument to the `BufferedReader` constructor: > Under Python 2.x, this is proposed as an alternative to the built-in `file` object, but in Python 3.x it is the default interface to access files and streams. ([1](htt...
Can sphinx link to documents that are not located in directories below the root document?
10,199,233
36
2012-04-17T21:12:24Z
10,210,779
12
2012-04-18T13:48:33Z
[ "python", "python-sphinx" ]
I am using Sphinx to document a non-Python project. I want to distribute `./doc` folders in each submodule, containing `submodule_name.rst` files to document that module. I then want to suck those files into the master hierarchy to create a spec for the entire design. I.e.: ``` Project docs spec project_s...
It seems that the answer is no, the documents listed in the toc-tree must reside within the [source directory](http://sphinx.pocoo.org/glossary.html#term-source-directory), that is, the directory containing your [master document](http://sphinx.pocoo.org/glossary.html#term-master-document) and `conf.py` (and any subdire...
Can sphinx link to documents that are not located in directories below the root document?
10,199,233
36
2012-04-17T21:12:24Z
17,217,041
50
2013-06-20T14:58:10Z
[ "python", "python-sphinx" ]
I am using Sphinx to document a non-Python project. I want to distribute `./doc` folders in each submodule, containing `submodule_name.rst` files to document that module. I then want to suck those files into the master hierarchy to create a spec for the entire design. I.e.: ``` Project docs spec project_s...
Yes, you can! In lieu of a symlink (which won't work on Windows), create a stub document that has nothing in it but a `.. include::` directive. I ran into this trying to link to a README file that was in the top of the source tree. I put the following in a file called `readme_link.rst`: ``` .. include:: ../README ``...
What does .shape[] do in "for i in range(Y.shape[0])"?
10,200,268
10
2012-04-17T22:42:43Z
10,200,284
36
2012-04-17T22:44:44Z
[ "python", "numpy", "matplotlib", "scipy" ]
I'm trying to break down a program line by line. `Y` is a matrix of data but I can't find any concrete data on what `.shape[0]` does exactly. ``` for i in range(Y.shape[0]): if Y[i] == -1: ``` This program uses numpy, scipy, matplotlib.pyplot, and cvxopt.
The `shape` attribute for numpy arrays returns the dimensions of the array. If `Y` has `n` rows and `m` columns, then `Y.shape` is `(n,m)`. So `Y.shape[0]` is `n`. ``` In [46]: Y = np.arange(12).reshape(3,4) In [47]: Y Out[47]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In [48]: Y.s...
What does .shape[] do in "for i in range(Y.shape[0])"?
10,200,268
10
2012-04-17T22:42:43Z
21,200,291
10
2014-01-18T05:12:12Z
[ "python", "numpy", "matplotlib", "scipy" ]
I'm trying to break down a program line by line. `Y` is a matrix of data but I can't find any concrete data on what `.shape[0]` does exactly. ``` for i in range(Y.shape[0]): if Y[i] == -1: ``` This program uses numpy, scipy, matplotlib.pyplot, and cvxopt.
shape is a tuple that gives dimensions of the array.. ``` >>> c = arange(20).reshape(5,4) >>> c array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]) c.shape[0] 5 ``` Gives the number of rows ``` c.shape[1] 4 ``` Gives number of columns
Django Deploy using Heroku - [Errno 2] No such file or directory
10,200,732
4
2012-04-17T23:38:28Z
10,213,729
8
2012-04-18T16:24:43Z
[ "python", "django", "heroku" ]
I get this error ([Errno 2] No such file or directory) after I push the repo to heroku master. Here are my logs. ``` 2012-04-17T18:24:53+00:00 app[web.1]: python: can't open file '/test/project/manage.py': [Errno 2] No such file or directory 2012-04-17T18:24:54+00:00 heroku[web.1]: Process exited with status 2 2...
Your current setup in your Procfile references an absolute path '/test/project/manage.py' that doesn't exist on Heroku. The '/test/ is the root of the instance you're running in and is incorrect. You should first change this to be the relative path, this is likely something like: ``` web: python project/manage.py runs...
SqlAlchemy won't accept datetime.datetime.now value in a DateTime column
10,201,648
5
2012-04-18T01:40:45Z
20,085,233
13
2013-11-20T00:42:00Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
I should first mention that I'm using SqlAlchemy through Flask-SqlAlchemy. I don't believe this affects the issue but if it does, please let me know. Here is the relevant part of the error message I'm getting when running the create\_all function in SqlAlchemy `InterfaceError: (InterfaceError) Error binding parameter...
Try to use `datetime.datetime.utcnow()`. This works for me.
Maximize WebDriver (Selenium 2) in Python
10,202,148
8
2012-04-18T02:54:19Z
10,247,860
14
2012-04-20T14:06:45Z
[ "python", "selenium", "window", "webdriver", "maximize" ]
I'm attempting to write a simple script that checks if I have any gmail emails labeled SOMETHING and then opens a firefox browser window to a login page, after which it goes to something else. Here's what I'm doing: ``` from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from seleni...
I've never used this functionality before, so I tried it out. ``` driver.maximize_window() ``` This seems to work fine - unless I am using Chrome. I'm not sure if this is a defect, as it works flawlessly in IE9 and Firefox. edit: This is a feature which has yet to be implemented in Chromedriver [-= Link to issue =-]...
python bindings, how does it work?
10,202,306
10
2012-04-18T03:20:57Z
10,202,569
21
2012-04-18T03:59:47Z
[ "python", "c", "binding" ]
I am exploring python. I curious about python bindings. Could anybody explain, how it is possible that you can have access to C libraries from Python.
There are several ways to call code written in C from Python. First, there is the [ctypes](http://docs.python.org/library/ctypes.html) module in the standard library. It allows you to load a dynamic-link library (DLL on Windows, shared libraries `.so` on Linux) and call functions from these libraries, directly from Py...
Pandas DataFrame - Find row where values for column is maximal
10,202,570
54
2012-04-18T03:59:55Z
10,202,789
57
2012-04-18T04:31:30Z
[ "python", "pandas" ]
How can I find the row for which the value of a specific column is maximal? `df.max()` will give me the maximal value for each column, I don't know how to get the corresponding row.
You just need the `argmax()` (*now called `idxmax`*) function. It's straightforward: ``` >>> import pandas >>> import numpy as np >>> df = pandas.DataFrame(np.random.randn(5,3),columns=['A','B','C']) >>> df A B C 0 1.232853 -1.979459 -0.573626 1 0.140767 0.394940 1.068890 2 0.742023 1.3...
Pandas DataFrame - Find row where values for column is maximal
10,202,570
54
2012-04-18T03:59:55Z
10,213,167
46
2012-04-18T15:51:32Z
[ "python", "pandas" ]
How can I find the row for which the value of a specific column is maximal? `df.max()` will give me the maximal value for each column, I don't know how to get the corresponding row.
You might also try `idxmax`: ``` In [5]: df = pandas.DataFrame(np.random.randn(10,3),columns=['A','B','C']) In [6]: df Out[6]: A B C 0 2.001289 0.482561 1.579985 1 -0.991646 -0.387835 1.320236 2 0.143826 -1.096889 1.486508 3 -0.193056 -0.499020 1.536540 4 -2.083647 -3.074591 0.17577...
How do I use method overloading in Python?
10,202,938
48
2012-04-18T04:47:50Z
10,202,988
68
2012-04-18T04:53:05Z
[ "python", "class", "method-overloading" ]
I am trying to implement method overloading in Python: ``` class A: def stackoverflow(self): print 'first method' def stackoverflow(self, i): print 'second method', i ob=A() ob.stackoverflow(2) ``` but the output is `second method 2`; similarly: ``` class A: def stackoverflow(self): ...
It's method *overloading* not method *overriding*. And in Python, you do it all in one function: ``` class A: def stackoverflow(self, i='some_default_value'): print 'only method' ob=A() ob.stackoverflow(2) ob.stackoverflow() ``` You can't have two methods with the same name in Python -- and you don'...
How do I use method overloading in Python?
10,202,938
48
2012-04-18T04:47:50Z
10,203,009
8
2012-04-18T04:54:54Z
[ "python", "class", "method-overloading" ]
I am trying to implement method overloading in Python: ``` class A: def stackoverflow(self): print 'first method' def stackoverflow(self, i): print 'second method', i ob=A() ob.stackoverflow(2) ``` but the output is `second method 2`; similarly: ``` class A: def stackoverflow(self): ...
I think the word you're looking for is "overloading". There is no method overloading in python. You can however use default arguments, as follows. ``` def stackoverflow(self, i=None): if i != None: print 'second method', i else: print 'first method' ``` When you pass it an argument it wil...
How do I use method overloading in Python?
10,202,938
48
2012-04-18T04:47:50Z
10,203,013
23
2012-04-18T04:55:24Z
[ "python", "class", "method-overloading" ]
I am trying to implement method overloading in Python: ``` class A: def stackoverflow(self): print 'first method' def stackoverflow(self, i): print 'second method', i ob=A() ob.stackoverflow(2) ``` but the output is `second method 2`; similarly: ``` class A: def stackoverflow(self): ...
In Python, you don't do things that way. When people do that in languages like Java, they generally want a default value (if they don't, they generally want a method with a different name). So, in Python, [you can have default values](http://docs.python.org/tutorial/controlflow.html#default-argument-values). ``` class...
How do I use method overloading in Python?
10,202,938
48
2012-04-18T04:47:50Z
10,203,933
12
2012-04-18T06:24:51Z
[ "python", "class", "method-overloading" ]
I am trying to implement method overloading in Python: ``` class A: def stackoverflow(self): print 'first method' def stackoverflow(self, i): print 'second method', i ob=A() ob.stackoverflow(2) ``` but the output is `second method 2`; similarly: ``` class A: def stackoverflow(self): ...
You can't, never need to and don't really want to. In Python, everything is an object. Classes are things, so they are objects. So are methods. There is an object called `A` which is a class. It has an attribute called `stackoverflow`. It can only have one such attribute. When you write `def stackoverflow(...): ...`...
Plotting dendrogram in Scipy error for large dataset
10,204,173
6
2012-04-18T06:42:45Z
18,005,236
11
2013-08-01T21:48:21Z
[ "python", "scipy", "cluster-analysis", "dendrogram" ]
I am using Scipy for hierarchial clustering. I do manage to get flat clusters on a threshold using fcluster. But I need to visualize the dendrogram formed. When I use the dendrogram method, it works fine for 5-6k user vectors. But my dataser consists of 16k user vectors. When I run it for 16k users dendrogram function ...
This may be a bit late, but if you feel comfortable with increasing your recursion limit to subvert the recursion depth limit, you could do so. It's not recommended, and definitely not 'pythonic', but it will likely get you the results you want. ``` import sys sys.setrecursionlimit(10000) ```
Error in a minimal tkSimpleDialog example
10,205,295
6
2012-04-18T08:00:28Z
10,211,143
8
2012-04-18T14:08:36Z
[ "python", "tkinter" ]
I was trying out a python code example at [Rosetta Code](http://rosettacode.org/wiki/User_input/Graphical#Python) - a [programming chrestomathy](http://en.wikipedia.org/wiki/Chrestomathy) site, where solutions to the same task are presented in as many different programming languages as possible. For this task, the goal...
The error message is telling you that the dialog needs a parent window. With Python 2.x, you create the root window with: ``` import Tkinter root = Tkinter.Tk() ``` To hide the root window if you don't want it, use: ``` root.withdraw() ``` See the [Python Tkinter Docs](http://docs.python.org/library/tkinter.html) ...
python celery max-tasks-per-child-setting default
10,205,473
4
2012-04-18T08:16:23Z
10,216,514
7
2012-04-18T19:27:04Z
[ "python", "celery", "celery-task" ]
I am using celery and i want to use the [max-tasks-per-child-setting](http://ask.github.com/celery/userguide/workers.html#max-tasks-per-child-setting) because some of the celery process get high memory usage. I am trying to find the default value for this setting before i change but i cant find that information. I lo...
By default there is no limit <http://celery.readthedocs.org/en/latest/configuration.html#celeryd-max-tasks-per-child> You can check out all default config values from defaults.py <https://github.com/celery/celery/blob/master/celery/app/defaults.py> ``` >>> from celery import conf >>> conf.CELERYD_MAX_TASKS_PER_CHIL...
Opening sqlite3 database from python in read-only mode
10,205,744
9
2012-04-18T08:36:50Z
21,794,758
13
2014-02-15T07:33:59Z
[ "python", "sqlite3" ]
While using sqlite3 from C/C++ I learned that it has a open-in-read-only mode option, which is very handy to avoid accidental data-corruption. Is there such a thing in the Python binding?
As of Python 3.4.0 you can open the database in read only mode with the following: ``` db = sqlite3.connect('file:/path/to/database?mode=ro', uri=True) ``` Also see [the documentation](https://docs.python.org/3/library/sqlite3.html#sqlite3.connect).
why 'in' operator with tuple as a key in python so slow?
10,205,969
5
2012-04-18T08:51:00Z
10,206,010
12
2012-04-18T08:53:50Z
[ "python", "dictionary", "key" ]
I have a dict such as: ``` d=dict() d[('1','2')] = 'value' ``` Then I query the key : ``` if (k1,k2) in d.keys(): ``` When there is million records,the speed is a suffering, any problem with the 'in' operator? Is it sequential search? I have to concat str as key to bypass this issue.
You should use ``` (k1,k2) in d ``` instead of calling `d.keys()`. Doing it your way, in Python 2 will result in a linear search and rather negates the benefits of a `dict`. In Python 3 your code is efficient (see comments below) but my version is clearer.
python suds wrong namespace prefix in SOAP request
10,207,167
5
2012-04-18T10:05:34Z
10,236,354
8
2012-04-19T20:37:15Z
[ "python", "soap", "xsd", "wsdl", "suds" ]
I use python/suds to implement a client and I get wrong namespace prefixes in the sent SOAP header for a spefic type of parameters defined by `element ref=` in the wsdl. The .wsdl is referencing a data types .xsd file, see below. The issue is with the function `GetRecordAttributes` and its first argument of type `gbt:...
Write a [Suds plugin](https://fedorahosted.org/suds/wiki/Documentation#PLUGINS) to modify the XML before it is sent. ``` from suds.client import Client from suds.plugin import MessagePlugin class MyPlugin(MessagePlugin): def marshalled(self, context): #modify this line to reliably find the "recordReferenc...
How to make Fabric continue running the next command after getting the exit status: 1?
10,207,600
12
2012-04-18T10:34:26Z
10,208,396
18
2012-04-18T11:28:30Z
[ "python", "fabric", "exitstatus" ]
I'm going to install [check\_mk](http://mathias-kettner.de/check_mk.html) plugin by writing a simple fabfile like this: ``` from fabric.api import env, run, roles, execute, parallel env.roledefs = { 'monitoring': ['192.168.3.118'], 'mk-agent': ['192.168.3.230', '192.168.3.231', '192.168.3.232'] } @roles('mon...
Go over the tutorial ([specific section](http://docs.fabfile.org/en/1.4.1/tutorial.html#failure-handling)), and [here](http://docs.fabfile.org/en/1.4.1/usage/execution.html#failure-handling) is more info in the main docs. You want to warn\_only.
How to make Fabric continue running the next command after getting the exit status: 1?
10,207,600
12
2012-04-18T10:34:26Z
18,605,326
10
2013-09-04T04:17:27Z
[ "python", "fabric", "exitstatus" ]
I'm going to install [check\_mk](http://mathias-kettner.de/check_mk.html) plugin by writing a simple fabfile like this: ``` from fabric.api import env, run, roles, execute, parallel env.roledefs = { 'monitoring': ['192.168.3.118'], 'mk-agent': ['192.168.3.230', '192.168.3.231', '192.168.3.232'] } @roles('mon...
since stackoverflow doesn't let me upvote Morgan's answer without more rep, I'll contribute more detail from <http://docs.fabfile.org/en/1.4.1/api/core/context_managers.html#fabric.context_managers.settings> In case anyone else should come across this page in learning fabric, it looks like following is a useful soluti...
Colormap for errorbars in x-y scatter plot using matplotlib
10,208,814
12
2012-04-18T11:53:32Z
10,212,681
12
2012-04-18T15:25:44Z
[ "python", "matplotlib", "scatter-plot", "color-mapping" ]
I have a time series of data for which I have the quantity, y, and its error, yerr. I would now like to create a plot that shows y against phase (i.e. time / period % 1) with vertical errorbars (yerr). For this, I typically use pyplot.errorbar(time, y, yerr=yerr, ...) However, I would like to use a colorbar/map to ind...
In addition to changing the color, another suggestion is to change the `zorder` of the error bars versus the scatter plot. This focuses the user on the data and draws out the general shape of the errors (which I think is your intention). ``` from pylab import * # Generate some random data that looks like yours N = 10...
How to disable SQLAlchemy caching?
10,210,080
8
2012-04-18T13:10:20Z
10,212,030
27
2012-04-18T14:51:50Z
[ "python", "mysql", "sqlalchemy", "innodb" ]
I meet a cache problem when I use `sqlalchemy`. I use `sqlalchemy` insert a data into mysql database. I have the other application process this data then update this data directly. But my `sqlalchemy` always got old data rather than updated data.. I think `sqlalchemy` cached my request.. so .. How to disable it?
The usual cause for people thinking there's a "cache" at play, besides the usual SQLAlchemy identity map which is local to a transaction, is that they are observing the effects of transaction isolation. SQLAlchemy's session works by default in a transactional mode, meaning it waits until `session.commit()` is called in...
How to disable SQLAlchemy caching?
10,210,080
8
2012-04-18T13:10:20Z
18,225,372
8
2013-08-14T07:11:55Z
[ "python", "mysql", "sqlalchemy", "innodb" ]
I meet a cache problem when I use `sqlalchemy`. I use `sqlalchemy` insert a data into mysql database. I have the other application process this data then update this data directly. But my `sqlalchemy` always got old data rather than updated data.. I think `sqlalchemy` cached my request.. so .. How to disable it?
This issue has been really frustrating for me, but I have finally figured it out. I have a Flask/SQLAlchemy Application running alongside an older PHP site. The PHP site would write to the database and SQLAlchemy would not be aware of any changes. I tried the sessionmaker setting autoflush=True unsuccessfully I tried...
Use Django's RedirectView with a named url
10,210,084
4
2012-04-18T13:10:52Z
10,210,683
9
2012-04-18T13:42:40Z
[ "python", "django", "django-urls", "django-class-based-views" ]
I'm trying to make my `a_detail` redirect to my `a_detail_slug` url. I want to use the named url for this but I haven't succeeded yet, this is what I've tried: ``` url(r'^a/(?P<pk>\d+)/(?P<filler>[\w-]+)/$', AList.as_view(template_name="a.html"), name="a_detail_slug"), url(r'^a/(?P<pk>\d+)/$', RedirectView.as_view(ur...
`a_detail_slug` requires 2 params (`pk` and `filler`) but you pass none of them. The easiest way will be extend RedirectView: ``` class ARedirect(RedirectView): def get_redirect_url(self, pk): filler = get_filler_somehow() return reverse('a_detail_slug', args=(pk, filler)) ```
Python List Class __contains__ Method Functionality
10,210,233
5
2012-04-18T13:19:02Z
10,210,342
7
2012-04-18T13:24:35Z
[ "python", "list", "class", "function", "contains" ]
Does the `__contains__` method of a list class check whether an object itself is an element of a list, or does it check whether the list contains an element equivalent to the given parameter? Could you give me an example to demonstrate?
``` >>> a = [[]] >>> b = [] >>> b in a True >>> b is a[0] False ``` This proves that it is a value check (by default at least), not an identity check. Keep in mind though that a class can if desired override `__contains__()` to make it an identity check. But again, by default, no.
Python asks for older paths on mac after deleting duplicate python installation
10,212,270
9
2012-04-18T15:05:14Z
10,213,719
7
2012-04-18T16:24:09Z
[ "python", "osx", "python-2.7", "virtualenv" ]
I am having the below error after a clean installation of python via brew install python. The link belongs to a previous python installation which I deleted manually. ``` $ virtualenv ENV python: posix_spawn: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: No such f...
It looks like you have deleted the Apple-supplied Python 2.7 that is part of OS X 10.7. That's a bad thing to do. You may have inadvertently broken parts of OS X that depend on it. In general, never delete anything in `/usr` (other than `/usr/local`) or in `/System/Library`. If you install a newer version of something,...
Python asks for older paths on mac after deleting duplicate python installation
10,212,270
9
2012-04-18T15:05:14Z
18,099,233
12
2013-08-07T09:10:14Z
[ "python", "osx", "python-2.7", "virtualenv" ]
I am having the below error after a clean installation of python via brew install python. The link belongs to a previous python installation which I deleted manually. ``` $ virtualenv ENV python: posix_spawn: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: No such f...
I had the very same situation after done stupid thing of deleting whole `/System/Library/Frameworks/Python.framework/` what results in error: `python: posix_spawn: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: No such file or directory` I managed to restore it, b...
Python map list item to function with arguments
10,212,445
11
2012-04-18T15:15:02Z
10,212,468
15
2012-04-18T15:16:19Z
[ "python" ]
Is there any way to map list items to a function along with arguments. I have a list: ``` pages = [p1, p2, p3, p4, p5...] ``` And I have to call function `myFunc` corresponding to each list elements along with additional arguments such that the following can be computed ``` myFunc(p1, additionalArgument) myFunc(p2, ...
Use a list comprehension: ``` result = [myFunc(p, additionalArgument) for p in pages] ```
Python map list item to function with arguments
10,212,445
11
2012-04-18T15:15:02Z
10,212,475
18
2012-04-18T15:16:34Z
[ "python" ]
Is there any way to map list items to a function along with arguments. I have a list: ``` pages = [p1, p2, p3, p4, p5...] ``` And I have to call function `myFunc` corresponding to each list elements along with additional arguments such that the following can be computed ``` myFunc(p1, additionalArgument) myFunc(p2, ...
You could use a list comprehension ``` [myFunc(p, additionalArgument) for p in pages] ``` or `functools.partial()` ``` map(functools.partial(myFunc, some_arg=additionalArgument), pages) ```
Python map list item to function with arguments
10,212,445
11
2012-04-18T15:15:02Z
31,995,624
10
2015-08-13T18:17:30Z
[ "python" ]
Is there any way to map list items to a function along with arguments. I have a list: ``` pages = [p1, p2, p3, p4, p5...] ``` And I have to call function `myFunc` corresponding to each list elements along with additional arguments such that the following can be computed ``` myFunc(p1, additionalArgument) myFunc(p2, ...
You can also use a lambda function: ``` map(lambda p: myFunc(p, additionalArgument), pages) ```
Naming convention for descriptors
10,212,556
7
2012-04-18T15:20:21Z
10,212,815
7
2012-04-18T15:32:53Z
[ "python", "coding-style", "naming-conventions" ]
I have a descriptor ``` class ReferredItem(): def __init__(self, method): self.method = method def __get__(self, obj, objtype): ... ``` I use it as decorator: ``` class MyClass(): @ReferredItem some_method(self): ... ``` I've seen the decorators are lower case. But classes...
[PEP8](http://www.python.org/dev/peps/pep-0008/) states that > Almost without exception, class names use the CapWords convention. without explaining what the exceptions are, but in the standard library, classes that are most commonly used as functions usually follow the function naming convention. E.g. `itertools.gro...
Import error on django models.py
10,212,929
7
2012-04-18T15:38:19Z
10,213,080
7
2012-04-18T15:46:30Z
[ "python", "django" ]
I wrote this funcion on a utils.py located on the app direcroty: ``` from bm.bmApp.models import Client def get_client(user): try: client = Client.objects.get(username=user.username) except Client.DoesNotExist: print "User Does not Exist" return None else: return cli...
You are creating a circular import. ``` utils.py from bm.bmApp.models import Client # Rest of the file... models.py from bm.bmApp.utils import to_safe_uppercase # Rest of the file... ``` I would suggest your refactor your code so that you don't have a circular dependency (i.e. utils should not need to import models....
Import error on django models.py
10,212,929
7
2012-04-18T15:38:19Z
10,213,232
7
2012-04-18T15:54:53Z
[ "python", "django" ]
I wrote this funcion on a utils.py located on the app direcroty: ``` from bm.bmApp.models import Client def get_client(user): try: client = Client.objects.get(username=user.username) except Client.DoesNotExist: print "User Does not Exist" return None else: return cli...
You are doing what is known as a Circular import. models.py: ``` from bm.bmApp.utils import to_safe_uppercase ``` utils.py: ``` from bm.bmApp.models import Client ``` Now when you do `import bm.bmApp.models` The interpreter does the following: 1. `models.py - Line 1`: try to import `bm.bmApp.utils` 2. `utils.py -...
Python, PIL and JPEG on Heroku
10,213,509
14
2012-04-18T16:12:03Z
10,267,949
21
2012-04-22T12:31:49Z
[ "python", "heroku", "python-imaging-library", "virtualenv", "libjpeg" ]
I have a **Django** site, hosted on **Heroku**. One of the models has an image field, that takes uploaded images, resizes them, and pushes them to Amazon S3 so that they can be stored persistently. This is working well, using **PIL** ``` def save(self, *args, **kwargs): # Save this one super(Product, self)....
I use this PIL fork in requirements.txt: ``` -e hg+https://bitbucket.org/etienned/pil-2009-raclette/#egg=PIL ``` and can use JPEG without issues: ``` -------------------------------------------------------------------- PIL 1.2a0 SETUP SUMMARY -----------------------------------------------------...
Python, PIL and JPEG on Heroku
10,213,509
14
2012-04-18T16:12:03Z
17,034,012
7
2013-06-10T22:45:11Z
[ "python", "heroku", "python-imaging-library", "virtualenv", "libjpeg" ]
I have a **Django** site, hosted on **Heroku**. One of the models has an image field, that takes uploaded images, resizes them, and pushes them to Amazon S3 so that they can be stored persistently. This is working well, using **PIL** ``` def save(self, *args, **kwargs): # Save this one super(Product, self)....
Also please consider using [Pillow](https://pypi.python.org/pypi/Pillow), the "friendly" PIL fork which offers: * Setuptools compatibility * Python 3 compatibility * Frequent release cycle * Many bug fixes
Hexadecimal convertion error in python
10,213,544
2
2012-04-18T16:14:01Z
10,213,603
7
2012-04-18T16:17:46Z
[ "python", "hex" ]
I need to make calculations with long hexadecimal number so I want to convert it to integer but, firstly, I try to remove spaces and EOL characters. But when I try conversion I get an error: "invalid literal for int() with base 16". Here is the code: ``` p = """670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B E39...
I think you want ``` pps = int(''.join(p.split()), 16) ```
Can SQLAlchemy be configured to be non-blocking?
10,214,042
20
2012-04-18T16:45:24Z
10,216,120
20
2012-04-18T19:00:02Z
[ "python", "database", "asynchronous", "sqlalchemy", "nonblocking" ]
I'm under the impression that database calls through SQLAlchemy will block and aren't suitable for use in anything other than synchronous code. Am I correct (I hope I'm not!) or is there a way to configure it to be non-blocking?
You can use SQLA in a non-blocking style using [gevent](http://www.gevent.org/). Here's an example using psycopg2, using psycopg2's [coroutine support](http://initd.org/psycopg/docs/advanced.html#support-to-coroutine-libraries): <https://bitbucket.org/zzzeek/green_sqla/> I've also heard folks use the same idea with [...
Find which version of package is installed with pip
10,214,827
245
2012-04-18T17:37:20Z
10,215,100
307
2012-04-18T17:53:51Z
[ "python", "pip" ]
Using pip, is it possible to figure out which version of a package is currently installed? I know about `pip install XYZ --upgrade` but I am wondering if there is anything like `pip info XYZ`. If not what would be the best way to tell what version I am currently using.
As of [pip 1.3](https://github.com/pypa/pip/blob/1.3/CHANGES.txt#L54), there is a `pip show` command. ``` $ pip show Jinja2 --- Name: Jinja2 Version: 2.7.3 Location: /path/to/virtualenv/lib/python2.7/site-packages Requires: markupsafe ``` In older versions, `pip freeze` and `grep` should do the job nicely. ``` $ pip...
Find which version of package is installed with pip
10,214,827
245
2012-04-18T17:37:20Z
10,215,664
12
2012-04-18T18:30:37Z
[ "python", "pip" ]
Using pip, is it possible to figure out which version of a package is currently installed? I know about `pip install XYZ --upgrade` but I am wondering if there is anything like `pip info XYZ`. If not what would be the best way to tell what version I am currently using.
You can also install `yolk` and then run `yolk -l` which also gives some nice output. Here is what I get for my little virtualenv: ``` (venv)CWD> /space/vhosts/pyramid.xcode.com/venv/build/unittest project@pyramid 43> yolk -l Chameleon - 2.8.2 - active Jinja2 - 2.6 - active Mako ...
Find which version of package is installed with pip
10,214,827
245
2012-04-18T17:37:20Z
10,300,036
43
2012-04-24T14:28:43Z
[ "python", "pip" ]
Using pip, is it possible to figure out which version of a package is currently installed? I know about `pip install XYZ --upgrade` but I am wondering if there is anything like `pip info XYZ`. If not what would be the best way to tell what version I am currently using.
I just sent a pull request in pip with the enhancement Hugo Tavares said: (specloud as example) ``` $ pip show specloud Package: specloud Version: 0.4.4 Requires: nose figleaf pinocchio ```
Find which version of package is installed with pip
10,214,827
245
2012-04-18T17:37:20Z
21,305,641
15
2014-01-23T10:36:22Z
[ "python", "pip" ]
Using pip, is it possible to figure out which version of a package is currently installed? I know about `pip install XYZ --upgrade` but I am wondering if there is anything like `pip info XYZ`. If not what would be the best way to tell what version I am currently using.
Pip 1.3 now also has a [list](https://pip.pypa.io/en/latest/reference/pip_list.html) command: ``` $ pip list argparse (1.2.1) pip (1.5.1) setuptools (2.1) wsgiref (0.1.2) ```
Find which version of package is installed with pip
10,214,827
245
2012-04-18T17:37:20Z
23,386,328
16
2014-04-30T11:00:48Z
[ "python", "pip" ]
Using pip, is it possible to figure out which version of a package is currently installed? I know about `pip install XYZ --upgrade` but I am wondering if there is anything like `pip info XYZ`. If not what would be the best way to tell what version I am currently using.
and with --outdated as an extra argument, you will get the Current and Latest versions of the packages you are using : ``` $ pip list --outdated distribute (Current: 0.6.34 Latest: 0.7.3) django-bootstrap3 (Current: 1.1.0 Latest: 4.3.0) Django (Current: 1.5.4 Latest: 1.6.4) Jinja2 (Current: 2.6 Latest: 2.8) ``` So co...
'easy_install' is not recognized as an in internal or external command, operable program or batch file
10,215,810
8
2012-04-18T18:40:35Z
10,215,883
10
2012-04-18T18:44:23Z
[ "python", "windows-7", "python-2.7", "easy-install" ]
I have just downloaded and installed the latest version of Python on my Windows 7 machine. ``` Python 2.7.3 ``` Now I want to install a [Twitter library](http://tweepy.github.com/) I found online: However when I try to run `easy_install tweepy`, I get this error message: > 'easy\_install' is not recognized as an in...
You need to: 1. Install easy\_install: <http://pypi.python.org/pypi/setuptools> 2. Add `C:\Python27\Scripts` to your `PATH`
Reading 3 bytes as an integer
10,216,650
5
2012-04-18T19:33:49Z
10,216,773
10
2012-04-18T19:42:15Z
[ "python" ]
How can I read 3 bytes as an integer? Does struct module provide something like that? I can read in 3 bytes and add an extra \x00 and then interpret it as a 4-byte integer, but that seems unnecessary.
The struct module has no option for 3-byte integers, so I think your idea of appending '\x00' is the easiest way. ``` In [30]: import struct In [38]: struct.pack('>3b',0,0,1) Out[38]: '\x00\x00\x01' In [39]: struct.unpack('>i','\x00'+'\x00\x00\x01') Out[39]: (1,) ```
Django static files won't load
10,216,827
11
2012-04-18T19:45:39Z
10,243,622
18
2012-04-20T09:32:50Z
[ "python", "django", "static", "django-static" ]
i'm a Django newbie working on my first project and having a problem with static files. I have created a simple auth system using `django.contrib.auth` consisting of two templates: `mysite/templates/index.html` and `mysite/templates/registration/login.html`. I have global static content in `mysite/static` which I want...
Your problem is that you arent listening to the URL "/static/" nowhere in your urls.py If you serve your application via a webserver like apache or nginx then this is normal as the webserver would handle the static files itself. For development Django comes with a built-in static server to urls.py, at the very end a...
Python integer to hexadecimal extra characters
10,218,164
11
2012-04-18T21:18:07Z
10,218,215
24
2012-04-18T21:21:54Z
[ "python", "hex" ]
I am trying to convert big integer number to hexadecimal, but in result I get extra "0x" in the beginning and "L" at the and. Is there any way to remove them. Thanks. The number is: ``` 44199528911754184119951207843369973680110397865530452125410391627149413347233422 3402221225182145688412447288761849232925436443281804...
Sure, go ahead and remove them. ``` hex(bignum).rstrip("L").lstrip("0x") or "0" ``` (Went the `strip()` route so it'll still work if those extra characters happen to not be there.)
Python integer to hexadecimal extra characters
10,218,164
11
2012-04-18T21:18:07Z
10,218,221
46
2012-04-18T21:22:21Z
[ "python", "hex" ]
I am trying to convert big integer number to hexadecimal, but in result I get extra "0x" in the beginning and "L" at the and. Is there any way to remove them. Thanks. The number is: ``` 44199528911754184119951207843369973680110397865530452125410391627149413347233422 3402221225182145688412447288761849232925436443281804...
The `0x` is literal representation of hex numbers. And `L` at the end means it is a *Long* integer. If you just want a hex representation of the number as a string without `0x` and `L`, you can use string formatting with `%x`. ``` >>> a = 44199528911754184119951207843369973680110397 >>> hex(a) '0x1fb62bdc9e54b041e618...
Set nested dict value and create intermediate keys
10,218,486
7
2012-04-18T21:43:35Z
10,218,517
12
2012-04-18T21:45:20Z
[ "python", "dictionary" ]
I feel like I saw a way to do this recently. Say I've got an empty dict and I want to set a value in a nested dict inside that empty dict, but obviously that nested dict hasn't been created yet. Is there a 1-line way to create the intermediate keys? This is what I want to do: ``` mydict = {} mydict['foo']['bar']['foob...
``` from collections import defaultdict recursivedict = lambda: defaultdict(recursivedict) mydict = recursivedict() ``` When you access `mydict['foo']`, it sets `mydict['foo']` to another `recursivedict`. It'll actually construct a `recursivedict` for `mydict['foo']['bar']['foobar']` as well, but then it'll get thrown...
Upgrade python in a virtualenv
10,218,946
74
2012-04-18T22:21:43Z
11,060,240
33
2012-06-16T02:11:04Z
[ "python", "version", "virtualenv", "pip" ]
Is there a way to upgrade the version of python used in a virtualenv (e.g. if a bugfix release comes out)? I could `pip freeze --local > requirements.txt` then remove the directory and `pip install -r requirements.txt` but this requires a lot of reinstallation of large libraries, for instance numpy which I use a lot. ...
Did you see [this](http://stackoverflow.com/questions/2170252/can-existing-virtualenv-be-upgraded-gracefully)? If I haven't misunderstand that answer, you may try to create a new virtualenv on top of the old one. You just need to know which python is going to use your virtualenv (you will need to see your virtualenv ve...
Upgrade python in a virtualenv
10,218,946
74
2012-04-18T22:21:43Z
24,724,360
12
2014-07-13T15:36:51Z
[ "python", "version", "virtualenv", "pip" ]
Is there a way to upgrade the version of python used in a virtualenv (e.g. if a bugfix release comes out)? I could `pip freeze --local > requirements.txt` then remove the directory and `pip install -r requirements.txt` but this requires a lot of reinstallation of large libraries, for instance numpy which I use a lot. ...
***Updated:*** I changed the answer 5 months after I originally answered. The following method is more convenient and robust. ***Side effect:*** it also fixes the `Symbol not found: _SSLv2_method` exception when you do `import ssl` in a virtual environment after upgrading Python to v2.7.8. ***Notice:*** Currently, **...
PyQt4 trouble creating a simple GUI application
10,219,367
10
2012-04-18T23:04:18Z
10,219,473
18
2012-04-18T23:16:56Z
[ "python", "qt", "pyqt4" ]
so I'm creating a simple windows application with Python and PyQt4. I've designed my UI the way I want it in QtCreator and I've created the necessary .py file from the .ui file. When I try to actually open an instance of the window however I'm given the following error: ``` AttributeError: 'Window' object has no attri...
You need to inherit from `QMainWindow`, not `QWidget`. `setCentralWidget` is a method of `QMainWindow`. ``` from PyQt4.QtCore import Qt, SIGNAL from PyQt4.QtGui import * from ui_mainwindow import Ui_MainWindow class Window(QMainWindow, Ui_MainWindow): def __init__(self, parent = None): QMainWindow.__ini...
Flask POST request is causing server to crash
10,219,486
13
2012-04-18T23:17:55Z
10,219,621
18
2012-04-18T23:33:39Z
[ "python", "json", "api", "rest", "flask" ]
I am trying to make a simple api in Flask, the first step being getting the POST json data. (I just want to print it for now) This is my code and when I request /api with json data, it returns a 500 error. Any thoughts on why this is happening? ``` from flask import Flask, request, Response app = Flask(__name__) @app...
First what you want to do is enable debug mode so Flask will actually tell you what the error is. (And you get the added benefit of flask reloading every time you modify your code!) ``` if __name__ == '__main__': app.debug = True app.run() ``` Then we find out our error: ``` TypeError: 'dict' object is not c...
Convert tab-delimited txt file into a csv file using Python
10,220,412
12
2012-04-19T01:24:34Z
10,220,428
24
2012-04-19T01:27:00Z
[ "python", "csv", "text-files" ]
So I want to convert a simple tab delimited text file into a csv file. If I convert the txt file into a string using string.split('\n') I get a list with each list item as a string with '\t' between each column. I was thinking I could just replace the '\t' with a comma but it won't treat the string within the list like...
`csv` supports tab delimited files. Supply the [`delimiter` argument to `reader`](http://docs.python.org/library/csv.html#csv.reader): ``` import csv txt_file = r"mytxt.txt" csv_file = r"mycsv.csv" # use 'with' if the program isn't going to immediately terminate # so you don't leave files open # the 'b' is necessary...
How to hash *args **kwargs for function cache?
10,220,599
8
2012-04-19T01:53:18Z
10,220,908
8
2012-04-19T02:37:25Z
[ "python" ]
I'm working with `xlwt` which has a 4k limit on how many styles can be defined in an excel doc. Normally, one creates styles like so: ``` style = xlwt.easyxf("font: bold 1") ``` Which I simply replaced with ``` def cached_easyxf(self, format): return self._cache.setdefault(format, xlwt.easyxf(format)) ``` Whic...
Here is the technique used in functools.lru\_cache(): ``` kwd_mark = object() # sentinel for separating args from kwargs def cached_call(*args, **kwargs): key = args + (kwd_mark,) + tuple(sorted(kwargs.items())) return cache.get(key) ``` Note, the above code handles keyword arguments but makes no attempt...
Parsing large (20GB) text file with python - reading in 2 lines as 1
10,220,862
15
2012-04-19T02:30:49Z
10,220,977
7
2012-04-19T02:45:17Z
[ "python", "large-files" ]
I'm parsing a 20Gb file and outputting lines that meet a certain condition to another file, however occasionally python will read in 2 lines at once and concatenate them. ``` inputFileHandle = open(inputFileName, 'r') row = 0 for line in inputFileHandle: row = row + 1 if line_meets_condition: output...
The 4GB mark is suspiciously near the maximum value that can be stored in a 32-bit register (2\*\*32). The code you've posted looks fine by itself, so I would suspect a bug in your Python build. FWIW, the snippet would be a little cleaner if it used *enumerate*: ``` inputFileHandle = open(inputFileName, 'r') for ro...
Parsing large (20GB) text file with python - reading in 2 lines as 1
10,220,862
15
2012-04-19T02:30:49Z
10,221,031
23
2012-04-19T02:53:01Z
[ "python", "large-files" ]
I'm parsing a 20Gb file and outputting lines that meet a certain condition to another file, however occasionally python will read in 2 lines at once and concatenate them. ``` inputFileHandle = open(inputFileName, 'r') row = 0 for line in inputFileHandle: row = row + 1 if line_meets_condition: output...
Quick google search for "python reading files larger than 4gb" yielded many many results. See [here for such an example](http://bugs.python.org/issue1672853) [and another one which takes over from the first](http://bugs.python.org/issue1744752). It's a bug in Python. > Now, the explanation of the bug; it's not easy t...
Can't use fabric put - Is there any server configuration needed?
10,221,839
6
2012-04-19T04:53:29Z
10,229,772
7
2012-04-19T14:03:12Z
[ "python", "ubuntu", "fabric" ]
I'm using `fabric` to do a remote deployment of my app on a rackspace server. I've tried my scripts on virtual machines using the same OS (Ubuntu Server 10.04) on my home computer and they all seem to work. Strangely, all `put` fabric commands fail on the real server. All other commands (`run`, `cd`, `sudo`, etc) seem...
Thanks to @Drake I found out that there was an issue with the `sftp` server on the remote machine. To test for this: ``` $ sftp remote-server subsystem request failed on channel 0 Couldn't read packet: Connection reset by peer ``` I read that in order to enable `sftp` I needed to add the line ``` Subsystem sftp /us...
Get sublayers from group layer with Python in Gimp
10,221,926
4
2012-04-19T05:02:21Z
10,239,894
7
2012-04-20T03:36:13Z
[ "python", "layer", "gimp", "xcf", "python-fu" ]
I have an XCD file with a nested layers structure: ``` image front-layer content-layer content-layer-name-1 content-layer-name-2 content-layer-name-3 back-layer ``` I open the file with `image = pdb.gimp_file_load(xcf_file, xcf_file)` and can get `front-layer`, `content-layer` and ...
GIMP Python went mostly unmaintained over this development cycle (you can blame much of that on myself). One of the few updates done was the creation of the "Item" class - and the implementation of a class method on it that allows one to use the numeric ID returned by the PDB methods to retreive an item. So, you can ...
memcache in google app engine
10,222,121
3
2012-04-19T05:23:13Z
10,240,523
8
2012-04-20T05:00:37Z
[ "python", "google-app-engine" ]
I am having an application developed in python and google app engine, but when i am try to customize this application then it is giving me compile time error in the previous code which is running fine on live. Code is: ``` if version in ['beta', 'alpha'] : type=version version = memcache.get(ty...
Did you perhaps name a file memcache.py? If so remove it and also memcache.pyc.
Why not True == True:
10,222,516
5
2012-04-19T06:07:43Z
10,222,545
7
2012-04-19T06:11:24Z
[ "python" ]
The last point of the style guide <http://www.python.org/dev/peps/pep-0008> reads ... Don't compare boolean values to True or False using ==. Why? Edit Just to make it clear what im asking (and it's indicative of the problem itself), when you write ``` if something: print "something is true" ``` You are doing...
It means that you should write ``` if greeting: ``` Instead of: ``` if greeting == True: ``` Similarly, you shouldn't write this either: ``` if (greeting == True) == True: ``` The extra tests are redundant and don't add any value to the code, so they should be removed.
Django - ModelForm Dynamic field update
10,223,891
3
2012-04-19T07:59:16Z
10,230,117
7
2012-04-19T14:19:13Z
[ "python", "django", "django-forms" ]
I'm trying to update certain fields a ModelForm, these fields are not fixed. (I have only `tutor` that is autopopulated by the view) Model: ``` class Session(models.Model): tutor = models.ForeignKey(User) start_time = models.DateTimeField() end_time = models.DateTimeField() status = models.CharField(max_lengt...
I've had to do something similar before, and while it isn't exactly pretty, it is quite effective. It involves dynamically creating a type at runtime, and using that type. For some documentation, you can see [DynamicModels for django.](https://code.djangoproject.com/wiki/DynamicModels) Here we go.. your requirements. ...
NameError: global name 'reduce' is not defined
10,226,381
13
2012-04-19T10:43:53Z
10,226,421
27
2012-04-19T10:46:55Z
[ "python", "reduce" ]
I'm new to Python. Would you please tell me what's wrong with the following code? When I run it, I got an error message of "NameError: global name 'reduce' is not defined". I asked Goolge but it's useless. :( ``` def main(): def add(x,y): return x+y reduce(add, range(1, 11)) if __name__=='__main__': main(...
I'm going to guess that: 1. You are using Python 3, and 2. You are following a tutorial designed for Python 2. The `reduce` function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the `functools` module, so you can do: ``` import functools def main(): ...
Whats the most pythonic way to calculate percentage changes on a list of numbers
10,226,551
2
2012-04-19T10:55:28Z
10,226,674
9
2012-04-19T11:04:31Z
[ "python" ]
I have a list of floating point numbers and I want to generate another list of period returns from my first list. This is a run of the mill implementation (not tested - and OBVIOUSLY no error checking/handling): ``` a = [100,105,100,95,100] def calc_period_returns(values, period): output = [] startpos, endpo...
Here you go: ``` >>> [100.0 * a1 / a2 - 100 for a1, a2 in zip(a[1:], a)] [5.0, -4.7619047619047592, -5.0, 5.2631578947368354] ``` Since you want to compare neighbor elements of a list, you better create a list of pairs you are interested in, like this: ``` >>> a = range(5) >>> a [0, 1, 2, 3, 4] >>> zip(a, a[1:]) [(0...
Whats the most pythonic way to calculate percentage changes on a list of numbers
10,226,551
2
2012-04-19T10:55:28Z
10,226,927
9
2012-04-19T11:19:53Z
[ "python" ]
I have a list of floating point numbers and I want to generate another list of period returns from my first list. This is a run of the mill implementation (not tested - and OBVIOUSLY no error checking/handling): ``` a = [100,105,100,95,100] def calc_period_returns(values, period): output = [] startpos, endpo...
I don't know how large your list of numbers is going to be, but if you are going to process large amounts of numbers, you should have a look at numpy. The side effect is that calculations look a lot simpler. With numpy, you create an array for your data ``` >>> import numpy as np >>> a = np.array([100,105,100,95,100]...
NameError: global name 'execfile' is not defined trying to run an app on Google App Engine Launcher
10,227,142
47
2012-04-19T11:35:19Z
10,227,164
66
2012-04-19T11:36:35Z
[ "python", "google-app-engine" ]
![Google App Engine Launcher](http://i.stack.imgur.com/PEOzw.png) I get this error in windows, I have both 3.2 and 2.7 versions of python. How can I fix this?
![solution](http://i.stack.imgur.com/wJ4sk.png) You just need to go to edit/preferences and specify correct version of python path
Understand a regular expression
10,227,359
2
2012-04-19T11:47:50Z
10,227,478
9
2012-04-19T11:54:31Z
[ "python", "c", "regex", "gcc" ]
I am trying parse a map file that is generated by gcc, for function addresses. There is a possible [solution here](http://stackoverflow.com/questions/48426/whats-the-best-tool-to-graphically-display-memory-layout-from-a-map-file)(python), but it's not working for me. I am trying to understand the solution provided. It...
``` ^\[([0-9 ]+)\]\s+(.+)\s*$ ^ start of the line \[ literal [ ([0-9 ]+) group of 0-9 or space, one or more times \] literal ] \s+ one or more spaces (.+) group of anything one or moretimes \s* zero or more spaces $ ...
Python Colon operator
10,228,655
3
2012-04-19T07:03:18Z
10,228,657
7
2012-04-19T07:55:43Z
[ "python" ]
I am trying to port some Python code and I am a little lost on small issue which I would appreciate some advice. I understand the `in` operator but I am a little unclear on what the `:` operator does in this example. ``` if foo in bar[i][:2]: # do something ``` In <http://docs.python.org/tutorial/introduction.ht...
This is called list slicing, you already link to the proper part of the documentation in your question. If you find documentation confusing, there is a video tutorial for that: <http://www.youtube.com/watch?v=iD6a0G8MnjA>
How to send an integer over a socket to a Java application using python?
10,228,927
2
2012-04-19T13:16:00Z
10,228,979
7
2012-04-19T13:19:02Z
[ "java", "python", "sockets", "integer", "byte" ]
I have a client in Python that sends data (preceded by a data length message): ``` s = socket.socket() s.connect((host, port)) data = 'hello world' s.sendall('%16s' % len(data)) #send data length s.sendall(data) #send data s.close() ``` And a server in Java that receives the data. The server uses [DataInputStream.rea...
Java expects the binary representation of your integer. You can use the [struct](http://docs.python.org/library/struct.html) module to generate binary representations. In your case, this would be: ``` import struct s.sendall(struct.pack('i', len(data))) ``` Also make sure you use the correct [byte order](http://docs...
Check if none of the multiple chars appears in string A?
10,229,965
3
2012-04-19T14:12:46Z
10,230,067
11
2012-04-19T14:17:01Z
[ "python" ]
I have a string, `A = "abcdef"`, and several chars `"a"`, `"f"` and `"m"`. I want a condition to make sure none of the chars appears in `A`, i.e., ``` if a not in A and f not in A and m not in A: # do something ``` Is there a better way to do this? Thanks!
[Sets](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) are useful for this -- see the `isdisjoint()` method: > Return True if the set has no elements in common with other. > Sets are disjoint if and only if their intersection is the empty set. > > new in version 2.6. ``` >>> a = "abcde" >>> b = ...
Can scipy.stats identify and mask obvious outliers?
10,231,206
13
2012-04-19T15:14:37Z
16,166,069
13
2013-04-23T09:43:34Z
[ "python", "statistics", "scipy", "linear-regression" ]
With scipy.stats.linregress I am performing a simple linear regression on some sets of highly correlated x,y experimental data, and initially visually inspecting each x,y scatter plot for outliers. More generally (i.e. programmatically) is there a way to identify and mask outliers?
The `statsmodels` package has what you need. Look at this little code snippet and its output: ``` # Imports # import statsmodels.api as smapi import statsmodels.graphics as smgraphics # Make data # x = range(30) y = [y*10 for y in x] # Add outlier # x.insert(6,15) y.insert(6,220) # Make graph # regression = smapi.OLS...
Hosting my Django site
10,232,673
11
2012-04-19T16:36:28Z
10,232,768
21
2012-04-19T16:41:59Z
[ "python", "django", "web-services" ]
Hi I'm looking for some advice I currently own a resseller package with Heart internet as I host a few personal websites. However I'm currently learning Django (The python Framework) and want to be able to host my own server. I have been setting up virtual servers to play around with. Anyway to have SSH access you hav...
It sounds like you're describing a shared hosting situation where you have SSH access but the webserver is preconfigured for you. You cannot practically install and serve Django on that machine, because you will not have access to the Apache or other webserver configuration. You could theoretically serve Django from a ...
Where do you set the task_id of a celery task?
10,235,136
6
2012-04-19T19:13:15Z
10,237,666
13
2012-04-19T22:19:58Z
[ "python", "django-celery", "celery-task" ]
I am having trouble finding any example of setting a task\_id with my own task\_id something along these lines... ``` def testview1(request): for i in xrange(0,1000): result = add.delay( i, 4,task_id = i) print result.info #value = result.wait() return HttpResponse("Done") @task() d...
delay doesn't support options, it's a shortcut to apply\_async: ``` add.apply_async(args, kwargs, task_id=i) add.apply_async((1, 4), task_id=i) ``` Also the id of the current task is in `task.request.id` not `task.id` like you have above.
django 1.4 how to automatically get user's timezone from client
10,235,956
12
2012-04-19T20:09:12Z
10,236,012
10
2012-04-19T20:13:44Z
[ "python", "django", "timezone" ]
I would like to know if there is a way to automatically retrieve user's timezone from client. Especially during login. I tried to add this in the login page (using `auth.login`): ``` {% get_current_timezone as TIME_ZONE %} ``` and then add this in the login form ``` <input type="hidden" name="next" value="/redirect...
From the [documentation](https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/): > Selecting the current time zone > > The current time zone is the > equivalent of the current locale for translations. However, there's no > equivalent of the Accept-Language HTTP header that Django could use to > determine the us...
django 1.4 how to automatically get user's timezone from client
10,235,956
12
2012-04-19T20:09:12Z
17,695,922
10
2013-07-17T09:21:04Z
[ "python", "django", "timezone" ]
I would like to know if there is a way to automatically retrieve user's timezone from client. Especially during login. I tried to add this in the login page (using `auth.login`): ``` {% get_current_timezone as TIME_ZONE %} ``` and then add this in the login form ``` <input type="hidden" name="next" value="/redirect...
I've simplified it even further, and you can plug in in here: <https://github.com/Miserlou/django-easy-timezones> or <http://gun.io/blog/django-easy-timezones/>
Modifying global variable with same name as local variable
10,235,973
17
2012-04-19T20:10:38Z
10,236,110
23
2012-04-19T20:21:05Z
[ "python", "global-variables" ]
Suppose I have a global variable `a`. And within a function definition, we also have a local variable named `a`. Is there any way to assign the value of the global variable to that of the local variable? ``` a = 'foo' def my_func(a = 'bar'): # how to set global a to value of the local a? ```
Use [build in function `globals()`](http://docs.python.org/library/functions.html#globals). > **`globals()`** > > *Return a dictionary representing the current global symbol > table. This is always the dictionary of the current module (inside a > function or method, this is the module where it is defined, not the > mo...
Celery: auto discovery does not find tasks module in app
10,236,318
9
2012-04-19T20:34:59Z
10,236,402
15
2012-04-19T20:40:40Z
[ "python", "django", "celery", "django-celery" ]
I have the following setup with a fresh installed celery and django 1.4: settings.py: ``` import djcelery djcelery.setup_loader() BROKER_HOST = 'localhost' BROKER_PORT = 5672 BROKER_USER = 'user' BROKER_PASSWORD = 'password' BROKER_VHOST = 'test' [...] INSTALLED_APPS = [ 'django.contrib.auth', 'django.cont...
Add [`CELERY_IMPORTS`](http://docs.celeryproject.org/en/master/configuration.html#celery-imports) to your settings.py: ``` CELERY_IMPORTS = ('testapp.tasks',) ``` Import all the tasks in `testapp.tasks.__init__` file Then **Celery** will import all tasks from testapp.tasks folder and name them as they are
Celery: auto discovery does not find tasks module in app
10,236,318
9
2012-04-19T20:34:59Z
10,237,638
10
2012-04-19T22:17:46Z
[ "python", "django", "celery", "django-celery" ]
I have the following setup with a fresh installed celery and django 1.4: settings.py: ``` import djcelery djcelery.setup_loader() BROKER_HOST = 'localhost' BROKER_PORT = 5672 BROKER_USER = 'user' BROKER_PASSWORD = 'password' BROKER_VHOST = 'test' [...] INSTALLED_APPS = [ 'django.contrib.auth', 'django.cont...
This was a bug in django-celery 2.5.4, please upgrade to 2.5.5!
Python Tkinter Error, "Too Early to Create Image"
10,236,857
5
2012-04-19T21:12:44Z
10,236,909
7
2012-04-19T21:16:57Z
[ "python", "tkinter" ]
So I have an assignment that I have to use Tkinter to create a board game. This is just one part of the program where I want to bring in the image of the board. But I keep on getting the error, "Too early to create image" and I'm not sure what I'm doing wrong. Here's my code so far: ``` from Tkinter import * from ppr...
You forgot to declare root - `root = Tk()`. The Tk system must be ON before using it.
Does Python have a similar control mechanism to Java's CountDownLatch?
10,236,947
8
2012-04-19T21:19:53Z
24,796,823
9
2014-07-17T06:58:44Z
[ "python", "multithreading" ]
So, I will start by saying that this is for a homework problem. My professor gave us an assignment which must be written once in Java and once in another language; I chose the second language to be Python since I'm at least a little familiar with it. The program must work in the following way: Start the main method/th...
you can implement CountDownLatch using threading.Condition like this: ``` import threading class CountDownLatch(object): def __init__(self, count=1): self.count = count self.lock = threading.Condition() def count_down(self): self.lock.acquire() self.count -= 1 if self....
Python: What do double parenthesis do?
10,237,902
2
2012-04-19T22:43:45Z
10,237,914
11
2012-04-19T22:45:00Z
[ "python", "syntax", "parentheses" ]
Can anyone tell me why the parenthesis are doubled here? ``` self.__items.append((module, item)) ```
The inner parenthesis create a [tuple](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences). ``` >>> type(('a', 'b')) <type 'tuple'> ``` Technically, tuples can be created without parenthesis: ``` >>> 'a', 'b' ('a', 'b') ``` But sometimes they need parenthesis: ``` >>> 'a', 'b' + 'c', 'd' ('a'...
Convert string to list of bits and viceversa
10,237,926
6
2012-04-19T22:45:49Z
10,238,101
18
2012-04-19T23:06:19Z
[ "python", "python-3.x" ]
I need to convert an ASCII string into a list of bits and vice versa: ``` str = "Hi" -> [0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1] [0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1] -> "Hi" ```
There are many ways to do this with library functions. But I am partial to the third-party [`bitarray`](http://pypi.python.org/pypi/bitarray) module. ``` >>> import bitarray >>> ba = bitarray.bitarray() ``` Conversion from strings is a little strange; you have to create the object first, and then pack in the string: ...
Convert string to list of bits and viceversa
10,237,926
6
2012-04-19T22:45:49Z
10,238,140
11
2012-04-19T23:10:55Z
[ "python", "python-3.x" ]
I need to convert an ASCII string into a list of bits and vice versa: ``` str = "Hi" -> [0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1] [0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1] -> "Hi" ```
There are probably faster ways to do this, but using no extra modules: ``` def tobits(s): result = [] for c in s: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return result def frombits(bits): chars = [] for b in range(le...
Python 2.x sorted puzzlement
10,238,060
2
2012-04-19T23:01:48Z
10,238,166
11
2012-04-19T23:13:48Z
[ "python", "python-2.x" ]
I have a partially sorted tuple in Python 2.x. Why Python reverse it instead of sort it? ``` >>> data = (u'a', (1,), 'b ', u'b', (2,), 'c ', u'c', (3,), 'd ', u'd', (4,), 'e') >>> sorted(data) == list(reversed(data)) True ``` I look forward to Python 3.
It fails because the sorting algorithm depends on a total ordering of the elements, which implies transitive `<`. The ordering of unicode strings, tuples, and strings isn't transitive: ``` >>> a = 'x' >>> b = (1,) >>> c = u'x' >>> a < b True >>> b < c True >>> a < c False ``` I.e., there exists no valid sort for you...