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 |
|---|---|---|---|---|---|---|---|---|---|
Python - get process names,CPU,Mem Usage and Peak Mem Usage in windows | 16,326,529 | 9 | 2013-05-01T21:06:31Z | 16,331,254 | 24 | 2013-05-02T05:56:24Z | [
"python",
"windows",
"memory",
"process",
"cpu"
] | I am wanting to get a list of all the process names, CPU, Mem Usage and Peak Mem Usage. I was hoping I could use ctypes. but I am happy to hear any other options. Thanks for your time. | You can use [`psutil`](http://code.google.com/p/psutil/).
For example, to obtain the list of process names:
```
process_names = [proc.name for proc in psutil.process_iter()]
```
For info about the CPU use [`psutil.cpu_percent`](https://code.google.com/p/psutil/wiki/Documentation#CPU) or `psutil.cpu_times`.
For info ... |
How many features can scikit-learn handle? | 16,326,699 | 4 | 2013-05-01T21:18:19Z | 16,326,770 | 9 | 2013-05-01T21:23:17Z | [
"python",
"numpy",
"machine-learning",
"scipy",
"scikit-learn"
] | I have a csv file of [66k, 56k] size (rows, columns). Its a sparse matrix. I know that numpy can handle that size a matrix. I would like to know based on everyone's experience, how many features scikit-learn algorithms can handle comfortably? | Depends on the estimator. At that size, linear models still perform well, while SVMs will probably take forever to train (and forget about random forests since they won't handle sparse matrices).
I've personally used `LinearSVC`, `LogisticRegression` and `SGDClassifier` with sparse matrices of size roughly 300k à 3.3... |
Enumerate two python lists simultaneously? | 16,326,853 | 9 | 2013-05-01T21:29:58Z | 16,326,876 | 23 | 2013-05-01T21:31:20Z | [
"python",
"list"
] | How do I enumerate two lists of equal length simultaneously?
I am sure there must be a more pythonic way to do the following:
```
for index, value1 in enumerate(data1):
print index, value1 + data2[index]
```
I want to use the index and data1[index] and data2[index] inside the for loop. | Use [`zip`](https://docs.python.org/2.7/library/functions.html#zip):
```
for index, (value1, value2) in enumerate(zip(data1, data2)):
print index, value1 + value2
```
Note that `zip` runs only up to the shorter of the two lists(not a problem for equal length lists), but, in case of unequal length lists if you wan... |
Enumerate two python lists simultaneously? | 16,326,853 | 9 | 2013-05-01T21:29:58Z | 16,326,878 | 7 | 2013-05-01T21:31:34Z | [
"python",
"list"
] | How do I enumerate two lists of equal length simultaneously?
I am sure there must be a more pythonic way to do the following:
```
for index, value1 in enumerate(data1):
print index, value1 + data2[index]
```
I want to use the index and data1[index] and data2[index] inside the for loop. | ```
for i, (x, y) in enumerate(zip(data1, data2)):
```
In Python 2.x, you might want to use `itertools.izip` instead of `zip`, esp. for very long lists. |
How to add an empty column to a dataframe? | 16,327,055 | 40 | 2013-05-01T21:46:47Z | 16,327,135 | 71 | 2013-05-01T21:52:57Z | [
"python",
"pandas"
] | What's the easiest way to add an empty column to a pandas `DataFrame` object? The best I've stumbled upon is something like
```
df['foo'] = df.apply(lambda _: '', axis=1)
```
Is there a less perverse method? | IIUC, assignment should fill:
```
>>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
>>> df
A B
0 1 2
1 2 3
2 3 4
>>> df["C"] = ""
>>> df["D"] = np.nan
>>> df
A B C D
0 1 2 NaN
1 2 3 NaN
2 3 4 NaN
``` |
SyntaxError: unexpected EOF while parsing | 16,327,405 | 2 | 2013-05-01T22:18:45Z | 16,327,413 | 11 | 2013-05-01T22:20:11Z | [
"python",
"eclipse",
"python-3.x",
"pydev",
"python-3.3"
] | I have no idea why this does not work please help
```
import random
x = 0
z = input('?')
int(z)
def main():
while x < z:
n1 = random.randrange(1,3)
n2 = random.randrange(1,3)
t1 = n1+n2
print('{0}+{1}={2}'.format(n1,n2,t1)
```
When i run this it outputs this error
```
File "/User... | You're missing a closing parenthesis `)` in `print()`:
```
print('{0}+{1}={2}'.format(n1,n2,t1))
```
and you're also not storing the returned value from `int()`, so `z` is still a string.
```
z = input('?')
z = int(z)
```
or simply:
```
z = int(input('?'))
``` |
Reindexing error makes no sense | 16,327,412 | 4 | 2013-05-01T22:20:02Z | 16,327,460 | 7 | 2013-05-01T22:24:06Z | [
"python",
"indexing",
"pandas"
] | I have `DataFrames` between 100k and 2m in size. the one I am dealing with for this question is this large, but note that I will have to do the same for the other frames:
```
>>> len(data)
357451
```
now this file was created by compiling many files, so the index for it is really odd. So all I wanted to do was reinde... | When it complains that `Reindexing only valid with uniquely valued Index`, it's not objecting that your *new* index isn't unique, it's objecting that your old one isn't.
For example:
```
>>> df = pd.DataFrame(range(5), index = [1,2,3,1,2])
>>> df
0
1 0
2 1
3 2
1 3
2 4
>>> df.reindex(index=range(len(df)))
Trac... |
Django model method - create_or_update | 16,329,946 | 5 | 2013-05-02T03:37:06Z | 18,318,106 | 7 | 2013-08-19T15:56:59Z | [
"python",
"django",
"django-models",
"django-orm"
] | Similar to [`get_or_create`](https://docs.djangoproject.com/en/1.5/ref/models/querysets/#get-or-create), I would like to be able to `update_or_create` in Django.
Until now, I have using an approaching similar to how [@Daniel Roseman does it here](http://stackoverflow.com/a/6382929/1287714). However, I'd like to do thi... | See [QuerySet.update\_or\_create](https://docs.djangoproject.com/en/dev/ref/models/querysets/#update-or-create) (new in Django 1.7dev) |
Where is the Python startup banner defined? | 16,330,103 | 4 | 2013-05-02T03:56:06Z | 16,330,178 | 13 | 2013-05-02T04:07:41Z | [
"python",
"python-3.x"
] | I'm compiling several different versions of Python for my system, and I'd like to know where in the source the startup banner is defined so I can change it for each version. For example, when the interpreter starts it displays
```
Python 3.3.1 (default, Apr 28 2013, 10:19:42)
[GCC 4.7.2 20121109 (Red Hat 4.7.2-8)] on... | Let's use `grep` to get in the ballpark. I'm not going to bother searching for `default` because I'll get too many results, but I'll try `Type "Help"`, which should not appear too many times. If it's a C string, the quotes will be escaped. We should look for C strings first and Python strings later.
```
Python $ grep ... |
TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'numpy.ndarray' | 16,330,366 | 3 | 2013-05-02T04:32:06Z | 16,330,519 | 8 | 2013-05-02T04:49:05Z | [
"python",
"python-2.7",
"numpy",
"scipy",
"scikit-learn"
] | I am trying to calculate the Mean Squared Error of the predictions `y_train_actual` from my sci-kit learn model with the original values `salaries`.
**Problem:** However with `mean_squared_error(y_train_actual, salaries)`, I am getting the error `TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'numpy... | The `TypeError` problem stems from salaries being a list of strings while y\_train\_actual is a list of floats. Those cannot be subtracted.
For your second error, you should make sure that both arrays are of the same size, otherwise it cannot subtract them. |
Most efficient way to find mode in numpy array | 16,330,831 | 16 | 2013-05-02T05:20:53Z | 16,331,189 | 23 | 2013-05-02T05:50:00Z | [
"python",
"numpy",
"2d",
"mode"
] | I have a 2D array containing integers (both positive or negative). Each row represents the values over time for a particular spatial site, whereas each column represents values for various spatial sites for a given time.
So if the array is like:
```
1 3 4 2 2 7
5 2 2 1 4 1
3 3 2 2 1 1
```
The result should be
```
1... | Check [`scipy.stats.mode()`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mode.html#scipy.stats.mode) (inspired by @tom10's comment):
```
import numpy as np
from scipy import stats
a = np.array([[1, 3, 4, 2, 2, 7],
[5, 2, 2, 1, 4, 1],
[3, 3, 2, 2, 1, 1]])
m = stats.mode... |
Efficiently computing element wise product of transition matrices (m*m) * (n*n) to give (mn*mn) matrix | 16,330,971 | 6 | 2013-05-02T05:31:35Z | 16,331,078 | 8 | 2013-05-02T05:40:42Z | [
"python",
"matrix",
"numpy",
"hidden-markov-models"
] | Consider input matrices X and Y of shapes (m,m) and (n,n) respectively. As an output we need to give a (mn,mn) shape matrix such that it multiplies corresponding entries in the two matrices.
These two matrices X and Y represent transition matrices. A following example can be taken to illustrate the required output. Her... | This is [Kronecker product](http://en.wikipedia.org/wiki/Kronecker_product), see [here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.kron.html) in numpy documentation. |
Python MemoryError when doing fitting with Scikit-learn | 16,332,083 | 2 | 2013-05-02T06:54:05Z | 16,351,308 | 8 | 2013-05-03T03:51:45Z | [
"python",
"python-2.7",
"numpy",
"scipy",
"scikit-learn"
] | I am running Python 2.7 (64-bit) on a Windows 8 64-bit system with 24GB memory. When doing the fitting of the usual `Sklearn.linear_models.Ridge`, the code runs fine.
**Problem:** However when using `Sklearn.linear_models.RidgeCV(alphas=alphas)` for the fitting, I run into the `MemoryError` error shown below on the li... | Take a look at this part of your stack trace:
```
531 def _pre_compute_svd(self, X, y):
532 if sparse.issparse(X) and hasattr(X, 'toarray'):
--> 533 X = X.toarray()
534 U, s, _ = np.linalg.svd(X, full_matrices=0)
535 v = s ** 2
```
The algorithm you're using rel... |
"Adding" new fonts to Tesseract eng.traineddata | 16,332,986 | 13 | 2013-05-02T07:54:55Z | 16,338,438 | 14 | 2013-05-02T12:45:27Z | [
"python",
"ocr",
"tesseract"
] | As far as I know, Tesseract 3.x comes with 6 English (correct me if I'm wrong) fonts. I need to train Tesseract for more 5 types of fonts. I need only capital letters and digits (no special characters or symbols).
I followed various processes for example:
[Adding New Fonts to Tesseract 3 OCR Engine](http://michaeljayl... | Should use a different name, e.g., `eng1.traineddata`. That way you can use the new data with the original one by specifying the language option `-l eng+eng1`. |
Matplotlib histograms (basic questions) | 16,333,213 | 2 | 2013-05-02T08:08:51Z | 16,333,475 | 9 | 2013-05-02T08:26:14Z | [
"python",
"matplotlib"
] | I am trying to plot a simple histogram using matplotlib. I have for example (I will in practice be using different distance functions)
```
import matplotlib.pyplot as plt
import numpy as np
import itertools
def hamdist(str1, str2):
"""Count the # of differences between equal length strings str1 and str2"""
i... | Your first and third points can be solved by setting the align keyword of the histogram function (which defaults to 'mid', the center of the bin). The second by manually setting the xticks.
See:
```
fig, ax = plt.subplots(1,1)
ax.hist(hamdists, bins=bins, align='left')
ax.set_xticks(bins[:-1])
```
![enter image des... |
How do you create nested dict in Python? | 16,333,296 | 27 | 2013-05-02T08:14:40Z | 16,333,441 | 60 | 2013-05-02T08:24:17Z | [
"python",
"python-2.7",
"dictionary",
"mapping",
"nested"
] | I have 2 csv files. First one is data file and other one is mapping file. Mapping file has 4 columns `Device_Name GDN Device_Type Device_OS`
These are also the columns which are present in data file and need to be worked upon.
Data file contains data with Device\_Name column populated & rest 3 columns blank. Mapping f... | A nested dict is a dictionary within a dictionary. A very simple thing.
```
>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d
{'dict1': {'innerkey': 'value'}}
```
You can also use a [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) from the [`collectio... |
How do you create nested dict in Python? | 16,333,296 | 27 | 2013-05-02T08:14:40Z | 34,142,473 | 30 | 2015-12-07T20:22:38Z | [
"python",
"python-2.7",
"dictionary",
"mapping",
"nested"
] | I have 2 csv files. First one is data file and other one is mapping file. Mapping file has 4 columns `Device_Name GDN Device_Type Device_OS`
These are also the columns which are present in data file and need to be worked upon.
Data file contains data with Device\_Name column populated & rest 3 columns blank. Mapping f... | Use the defaultdict function from the collections.
High performance: "if key not in dict" is very expensive when the data set is large.
Low maintenance: make the code more readable and can be easily extended.
```
from collections import defaultdict
target_dict = defaultdict(dict)
target_dict[key1][key2] = val
``` |
mixed slashes with os.path.join on windows | 16,333,569 | 19 | 2013-05-02T08:31:53Z | 16,333,785 | 13 | 2013-05-02T08:45:36Z | [
"python",
"windows",
"path"
] | I tend to use only forward slashes for paths ('/') and python is happy with it also on windows.
In the description of os.path.join it says that is the correct way if you want to go cross-platform. But when I use it I get mixed slashes:
```
import os
a = 'c:/'
b = 'myFirstDirectory/'
c = 'mySecondDirectory'
d = 'myThi... | You are now providing some of the slashes yourself and letting [`os.path.join`](http://docs.python.org/2/library/os.path.html) pick others. It's better do let python pick all of them or provide them all yourself. Python uses backslashes for the latter part of the path, because backslashes are the default on Windows.
`... |
mixed slashes with os.path.join on windows | 16,333,569 | 19 | 2013-05-02T08:31:53Z | 18,776,536 | 12 | 2013-09-13T00:53:28Z | [
"python",
"windows",
"path"
] | I tend to use only forward slashes for paths ('/') and python is happy with it also on windows.
In the description of os.path.join it says that is the correct way if you want to go cross-platform. But when I use it I get mixed slashes:
```
import os
a = 'c:/'
b = 'myFirstDirectory/'
c = 'mySecondDirectory'
d = 'myThi... | You can use `.replace()` after `path.join()` to ensure the slashes are correct:
```
# .replace() all backslashes with forwardslashes
print os.path.join(a, b, c, d, e).replace("\\","/")
```
This gives the output:
```
c:/myFirstDirectory/mySecondDirectory/myThirdDirectory/myExecutable.exe
```
As @sharpcloud suggested... |
Create a figure that is reference counted | 16,334,588 | 11 | 2013-05-02T09:29:04Z | 16,337,909 | 13 | 2013-05-02T12:20:36Z | [
"python",
"memory-management",
"matplotlib"
] | It seems that the standard way of creating a figure in matplotlib doesn't behave as I'd expect in python: by default calling `fig = matplotlib.figure()` in a loop will hold on to all the figures created, and eventually run out of memory.
There are [quite](http://stackoverflow.com/q/7101404/915501) [a](http://stackover... | If you create the figure without using `plt.figure`, then it should be reference counted as you expect. For example (This is using the non-interactive Agg backend, as well.)
```
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
# The pylab figure manager ... |
Why do Numpy.all() and any() give wrong results if you use generator expressions? | 16,334,860 | 5 | 2013-05-02T09:42:24Z | 16,335,218 | 14 | 2013-05-02T10:00:25Z | [
"python",
"numpy"
] | Working with somebody else's code I stumbled across this gotcha. So what is the explanation for numpy's behavior?
```
In [1]: import numpy as np
In [2]: foo = [False, False]
In [3]: print np.any(x == True for x in foo)
True # <- bad numpy!
In [4]: print np.all(x == True for x in foo)
True # <- bad numpy!
In [5]:... | `np.any` and `np.all` don't work on generators. They need sequences. When given a non-sequence, they treat this as any other object and call `bool` on it (or do something equivalent), which will return `True`:
```
>>> false = [False]
>>> np.array(x for x in false)
array(<generator object <genexpr> at 0x31193c0>, dtype... |
Starting a stopped EC2 instance with Boto | 16,335,181 | 7 | 2013-05-02T09:58:26Z | 16,335,372 | 10 | 2013-05-02T10:08:45Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"boto"
] | I am writing a python script that starts a specific instance that is currently stopped, and I am kind of stumped on how I'd do that. As far as I can understand from the [Boto EC2 introduction](http://boto.readthedocs.org/en/latest/ec2_tut.html#launching-instances) on launching instances this creates a completely new in... | I had completely missed [this command in the API](http://boto.readthedocs.org/en/latest/ref/ec2.html#boto.ec2.instance.Instance.start)
For future reference, this is how to start a stopped instance:
```
instance = conn.get_all_instances(instance_ids=['instance_id'])
print instance[0].instances[0].start()
``` |
Mapping result rows to namedtuple in python sqlite | 16,335,772 | 6 | 2013-05-02T10:29:57Z | 16,336,132 | 14 | 2013-05-02T10:49:30Z | [
"python",
"sqlite",
"namedtuple"
] | I am playing a bit with the python api for sqlite3, i have a little table for store languages with an id, name and creation\_date fields. I am trying to map the raw query results into a `namedtuple` as the docs recommend, it that way i can manage rows in a more readable way, so here is my `namedtuple`.
```
LanguageRec... | There is a much easier way! Sqlite3 provides a way for the user to define ["row factories"](http://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.row_factory). These row factories take the cursor and the tuple row and can return whatever type of object it wants.
Once you set the row factory with
```
con.ro... |
Dictionary of Dictionaries : Sorting by a specific key | 16,336,043 | 2 | 2013-05-02T10:44:17Z | 16,336,104 | 8 | 2013-05-02T10:47:31Z | [
"python",
"python-2.7",
"dictionary"
] | I have a dictionary that looks like this
```
{'Africa': {'Name': 'Africa',
'men': 33333,
'priority': 3,
'women': 30000},
'America': {'Name': 'USA',
'men': 1114444411333L,
'priority': 4,
'women': 44430000},
'Asia': {'Name': 'China',
... | ```
>>> d = {"Africa" :
{ "Name" : "Africa", "men": 33333, "women" : 30000, "priority" :3},
"Asia":
{ "Name" : "China", "men": 444433333, "women" : 444430000, "priority" :2},
"Europe":
{ "Name" : "UK", "men": 11111333, "women" : 1111430000, "priority" :1},
"America":
{ "Name" : "USA", "men": ... |
is not JSON serializable | 16,336,271 | 29 | 2013-05-02T10:55:52Z | 16,360,956 | 55 | 2013-05-03T14:11:52Z | [
"python",
"django",
"json"
] | I have the following ListView
```
import json
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return json.dumps(self.get_queryset().values_list('code', flat=True))
```
But I get following error:
```
[u'ae', u'ag', u'ai', u'al', u'am',
u'... | I'll add a slightly more detailed answer.
It's worth noting that the [`QuerySet.values_list()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list) method doesn't actually return a list, but an object of type `django.db.models.query.ValuesListQuerySet`, in order to ... |
Log all requests from the python-requests module | 16,337,511 | 29 | 2013-05-02T11:57:58Z | 16,337,639 | 25 | 2013-05-02T12:05:35Z | [
"python",
"logging",
"python-requests"
] | I am using python [Requests](http://docs.python-requests.org/en/latest/). I need to debug some `OAuth` activity, and for that I would like it to log all requests being performed. I could get this information with `ngrep`, but unfortunately it is not possible to grep https connections (which are needed for `OAuth`)
How... | The underlying `urllib3` library logs all new connections and URLs with the [`logging` module](http://docs.python.org/2/library/logging.html), but not `POST` bodies. For `GET` requests this should be enough:
```
import logging
logging.basicConfig(level=logging.DEBUG)
```
which gives you the most verbose logging opti... |
Log all requests from the python-requests module | 16,337,511 | 29 | 2013-05-02T11:57:58Z | 24,588,289 | 42 | 2014-07-05T16:16:15Z | [
"python",
"logging",
"python-requests"
] | I am using python [Requests](http://docs.python-requests.org/en/latest/). I need to debug some `OAuth` activity, and for that I would like it to log all requests being performed. I could get this information with `ngrep`, but unfortunately it is not possible to grep https connections (which are needed for `OAuth`)
How... | You need to enable debugging at `httplib` level (`requests->urllib3->httplib`).
```
from __future__ import print_function
import requests
import logging
try:
import httplib
except ImportError:
import http.client as httplib
httplib.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setL... |
Log all requests from the python-requests module | 16,337,511 | 29 | 2013-05-02T11:57:58Z | 26,460,395 | 12 | 2014-10-20T07:24:35Z | [
"python",
"logging",
"python-requests"
] | I am using python [Requests](http://docs.python-requests.org/en/latest/). I need to debug some `OAuth` activity, and for that I would like it to log all requests being performed. I could get this information with `ngrep`, but unfortunately it is not possible to grep https connections (which are needed for `OAuth`)
How... | For those using python 3+
```
import requests
import logging
import http.client
http.client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
... |
Python: How to not print comma in last element in a for loop? | 16,338,558 | 6 | 2013-05-02T12:52:41Z | 16,338,562 | 17 | 2013-05-02T12:53:03Z | [
"python",
"string",
"list"
] | My code iterates over a set and print actor's names:
```
for actor in actorsByMovies():
print actor+",",
```
The result looks like:
```
Brad Pitt, George Clooney,
```
But I want it to detect the last element so that it won't print the last comma. The result should be instead:
```
Brad Pitt, George Clooney
```
... | ```
print ', '.join(actorsByMovies())
``` |
Grabbing selection between specific dates in a DataFrame | 16,341,367 | 2 | 2013-05-02T14:59:53Z | 16,341,595 | 7 | 2013-05-02T15:11:39Z | [
"python",
"datetime",
"pandas"
] | so I have a large pandas DataFrame that contains about two months of information with a line of info per second. Way too much information to deal with at once, so I want to grab specific timeframes. The following code will grab everything before February 5th 2012:
```
sunflower[sunflower['time'] < '2012-02-05']
```
I... | You could define a mask separately:
```
df = DataFrame('a': np.random.randn(100), 'b':np.random.randn(100)})
mask = (df.b > -.5) & (df.b < .5)
df_masked = df[mask]
```
Or in one line:
```
df_masked = df[(df.b > -.5) & (df.b < .5)]
``` |
What is the advantage of a list comprehension over a for loop? | 16,341,775 | 13 | 2013-05-02T15:20:32Z | 16,341,841 | 25 | 2013-05-02T15:23:37Z | [
"python",
"list-comprehension"
] | What is the advantage of using a [list comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) over a `for` loop in Python?
Is it mainly to make it more humanly readable, or are there other reasons to use a list comprehension instead of a loop? | List comprehensions are more compact *and* faster than an explicit `for` loop building a list:
```
def slower():
result = []
for elem in some_iterable:
result.append(elem)
return result
def faster():
return [elem for elem in some_iterable]
```
This is because calling `.append()` on a `list` c... |
SQLAlchemy error MySQL server has gone away | 16,341,911 | 7 | 2013-05-02T15:26:34Z | 17,791,117 | 7 | 2013-07-22T15:10:57Z | [
"python",
"mysql",
"sqlalchemy",
"flask"
] | Error `OperationalError: (OperationalError) (2006, 'MySQL server has gone away')` i'm already received this error when i coded project on Flask, but i cant understand why i get this error.
I have code (yeah, if code small and executing fast, then no errors) like this \
```
db_engine = create_engine('mysql://root@127.... | SQLAlchemy now has a great write-up on how you can use pinging to be pessimistic about your connection's freshness:
<http://docs.sqlalchemy.org/en/latest/core/pooling.html#disconnect-handling-pessimistic>
From there,
```
from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy.pool import Pool
@event... |
Numpy where function multiple conditions | 16,343,752 | 31 | 2013-05-02T17:03:19Z | 16,343,791 | 53 | 2013-05-02T17:04:57Z | [
"python",
"numpy"
] | I have an array of distances called dists. I want to select dists which are between two values. I wrote the following line of code to do that:
```
dists[(np.where(dists >= r)) and (np.where(dists <= r + dr))]
```
However this selects only for the condition
```
(np.where(dists <= r + dr))
```
If I do the commands ... | The best way in **your particular case** would just be to change your two criteria to one criterion:
```
dists[abs(dists - r - dr/2.) <= dr/2.]
```
It only creates one boolean array, and in my opinion is easier to read because it says, *is `dist` within a `dr` or `r`?* (Though I'd redefine `r` to be the center of you... |
Take a screenshot from a website from commandline or with python | 16,344,700 | 7 | 2013-05-02T18:01:12Z | 16,345,409 | 13 | 2013-05-02T18:41:13Z | [
"python",
"command-line",
"website",
"screenshot"
] | i will take a screenshot from this page: <http://books.google.de/books?id=gikDAAAAMBAJ&pg=PA1&img=1&w=2500> or save the image that it outputs.
But i can't find a way. With wget/curl i get an "unavailable error" and also with others tools like webkit2png/wkhtmltoimage/wkhtmltopng.
Is there a clean way to do it with py... | You can use ghost.py if you like.
<http://jeanphix.me/Ghost.py/>
Here is an example of how to use it.
```
from ghost import Ghost
ghost = Ghost(wait_timeout=4)
ghost.open('http://www.google.com')
ghost.capture_to('screen_shot.png')
```
The last line saves the image in your current directory.
Hope this helps |
Auto reloading python Flask app upon code changes | 16,344,756 | 36 | 2013-05-02T18:04:10Z | 16,344,851 | 67 | 2013-05-02T18:09:00Z | [
"python",
"apache",
"web",
"flask"
] | I'm investigating how to develop a decent web app with Python. Since I don't want some high-order structures to get in my way, my choice fell on the lightweight [Flask framework](http://flask.pocoo.org/community/). Time will tell if this was the right choice.
So, now I've set up an Apache server with mod\_wsgi, and my... | If you are talking about test/dev environments, then just use the debug option. It will auto-reload the flask app when a code change happens.
```
app.run(debug=True)
```
<http://flask.pocoo.org/docs/quickstart/#debug-mode> |
Auto reloading python Flask app upon code changes | 16,344,756 | 36 | 2013-05-02T18:04:10Z | 16,373,705 | 24 | 2013-05-04T11:20:54Z | [
"python",
"apache",
"web",
"flask"
] | I'm investigating how to develop a decent web app with Python. Since I don't want some high-order structures to get in my way, my choice fell on the lightweight [Flask framework](http://flask.pocoo.org/community/). Time will tell if this was the right choice.
So, now I've set up an Apache server with mod\_wsgi, and my... | # In test/development environments
The werkzeug debugger already has an 'auto reload' function available that can be enabled by doing one of the following:
```
app.run(debug=True)
```
or
```
app.debug = True
```
You can also use a separate configuration file to manage all your setup if you need be. For example I u... |
Auto reloading python Flask app upon code changes | 16,344,756 | 36 | 2013-05-02T18:04:10Z | 19,825,140 | 16 | 2013-11-06T23:35:30Z | [
"python",
"apache",
"web",
"flask"
] | I'm investigating how to develop a decent web app with Python. Since I don't want some high-order structures to get in my way, my choice fell on the lightweight [Flask framework](http://flask.pocoo.org/community/). Time will tell if this was the right choice.
So, now I've set up an Apache server with mod\_wsgi, and my... | If you're running using uwsgi look at the python auto reload option:
```
uwsgi --py-autoreload 1
```
Example uwsgi-dev-example.ini:
```
[uwsgi]
socket = 127.0.0.1:5000
master = true
virtualenv = /Users/xxxx/.virtualenvs/sites_env
chdir = /Users/xxx/site_root
module = site_module:register_debug_server()
callable = ap... |
Fill in missing pandas data with previous non-missing value, grouped by key | 16,345,583 | 11 | 2013-05-02T18:51:25Z | 16,345,735 | 12 | 2013-05-02T18:59:54Z | [
"python",
"pandas",
null,
"missing-data",
"data-cleansing"
] | I am dealing with pandas DataFrames like this:
```
id x
0 1 10
1 1 20
2 2 100
3 2 200
4 1 NaN
5 2 NaN
6 1 300
7 1 NaN
```
I would like to replace each NAN 'x' with the previous non-NAN 'x' from a row with the same 'id' value:
```
id x
0 1 10
1 1 20
2 2 100
3 2 200
... | You could use a [groupby-transform](http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation) and call [fillna](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html) on each group:
```
import pandas as pd
import numpy as np
df = pd.DataFrame({'id': [1,1,2,2,1,2,1,1], 'x':[10,... |
python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined> | 16,346,914 | 16 | 2013-05-02T20:13:49Z | 16,347,110 | 45 | 2013-05-02T20:26:36Z | [
"python",
"python-3.x",
"sqlite3"
] | I'm trying to make a script that gets data out from an sqlite3 database, but I have run in to a problem.
The field in the database is of type text and the contains a html formated text. see the text below
```
<html>
<head>
<title>Yahoo!</title>
</head>
<body>
<style type="text/css">
html {}
.yshortcuts {border-bottom... | When you open the file you want to write to, open it with a specific encoding that can handle all the characters.
```
with open('filename', 'w', encoding='utf-8') as f:
print(r['body'], file=f)
``` |
python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined> | 16,346,914 | 16 | 2013-05-02T20:13:49Z | 16,347,188 | 22 | 2013-05-02T20:31:59Z | [
"python",
"python-3.x",
"sqlite3"
] | I'm trying to make a script that gets data out from an sqlite3 database, but I have run in to a problem.
The field in the database is of type text and the contains a html formated text. see the text below
```
<html>
<head>
<title>Yahoo!</title>
</head>
<body>
<style type="text/css">
html {}
.yshortcuts {border-bottom... | While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you `print`, or otherwise send Unicode strings to `stdout`, and it's attached to a console/tty, Python has to encode it.
The error message indirectly tells you what character set Python was trying to use... |
python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined> | 16,346,914 | 16 | 2013-05-02T20:13:49Z | 28,041,598 | 35 | 2015-01-20T09:20:09Z | [
"python",
"python-3.x",
"sqlite3"
] | I'm trying to make a script that gets data out from an sqlite3 database, but I have run in to a problem.
The field in the database is of type text and the contains a html formated text. see the text below
```
<html>
<head>
<title>Yahoo!</title>
</head>
<body>
<style type="text/css">
html {}
.yshortcuts {border-bottom... | Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to `utf-8` or other encoder that can represent your data. Then you can print it to `sys.stdout`.
First, run following code in the console:
```
chcp 65001
set PYTHONIOENCODING=utf-8
```
... |
How to generate all possible strings in python? | 16,347,583 | 6 | 2013-05-02T20:56:58Z | 16,347,653 | 17 | 2013-05-02T21:01:19Z | [
"python",
"python-2.7",
"iterator"
] | My goal is to be able to generate all possible strings (Letters and numbers) of length x and be able to activate a block of code for each one. (like an iterator) The only problem is the ones in the itertools don't make copies of the letter in the same string. For example:
I get "ABC" "BAC" "CAB" etc. instead of "AAA".... | Use [`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product):
```
>>> import itertools
>>> map(''.join, itertools.product('ABC', repeat=3))
['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC... |
Python assigning multiple variables to same value? list behavior | 16,348,815 | 33 | 2013-05-02T22:31:18Z | 16,348,931 | 9 | 2013-05-02T22:41:21Z | [
"python",
"list"
] | I tried to use multiple assignment as show below to initialize variables, but I got confused by the behavior, I expect to reassign the values list separately, I mean b[0] and c[0] equal 0 as before.
```
a=b=c=[0,3,5]
a[0]=1
print(a)
print(b)
print(c)
```
Result is:
[1, 3, 5]
[1, 3, 5]
[1, 3, 5]
Is that correct? what... | Yes, that's the expected behavior. a, b and c are all set as labels for the same list. If you want three different lists, you need to assign them individually. You can either repeat the explicit list, or use one of the numerous ways to copy a list:
```
b = a[:] # this does a shallow copy, which is good enough for this... |
Python assigning multiple variables to same value? list behavior | 16,348,815 | 33 | 2013-05-02T22:31:18Z | 16,349,356 | 100 | 2013-05-02T23:27:16Z | [
"python",
"list"
] | I tried to use multiple assignment as show below to initialize variables, but I got confused by the behavior, I expect to reassign the values list separately, I mean b[0] and c[0] equal 0 as before.
```
a=b=c=[0,3,5]
a[0]=1
print(a)
print(b)
print(c)
```
Result is:
[1, 3, 5]
[1, 3, 5]
[1, 3, 5]
Is that correct? what... | If you're coming to Python from a language in the C/Java/etc. family, it may help you to stop thinking about `a` as a "variable", and start thinking of it as a "name".
`a`, `b`, and `c` aren't different variables with equal values; they're different names for the same identical value. Variables have types, identities,... |
Python assigning multiple variables to same value? list behavior | 16,348,815 | 33 | 2013-05-02T22:31:18Z | 21,615,586 | 7 | 2014-02-06T22:36:30Z | [
"python",
"list"
] | I tried to use multiple assignment as show below to initialize variables, but I got confused by the behavior, I expect to reassign the values list separately, I mean b[0] and c[0] equal 0 as before.
```
a=b=c=[0,3,5]
a[0]=1
print(a)
print(b)
print(c)
```
Result is:
[1, 3, 5]
[1, 3, 5]
[1, 3, 5]
Is that correct? what... | Cough cough
```
>>> a = (1,2,3)
>>> a,b,c = (1,2,3)
>>> a
1
>>> b
2
>>> c
3
>>> a,b,c = ({'test':'a'},{'test':'b'},{'test':'c'})
>>> a
{'test': 'a'}
>>> b
{'test': 'b'}
>>> c
{'test': 'c'}
>>>
``` |
Renaming series in pandas | 16,350,864 | 5 | 2013-05-03T02:54:12Z | 16,351,035 | 9 | 2013-05-03T03:20:00Z | [
"python",
"pandas"
] | I am working with series, and I was wondering how I can rename the series when writing to a file. For example, my output csv consists of the following:
```
Gene_Name,0
A2ML1,15
AAK1,8
```
I want it to be the following:
```
Gene_Name,Count
A2ML1,15
AAK1,8
```
Note: I don't want my header to be "Gene\_Name,0" but "Ge... | To make "Count" the name of your series, just set it with `your_series.name = "Count"` and then call to\_csv like this: `your_series.to_csv("c:\\output.csv", header=True, index_label="Gene_Name")`. |
Combining for and if loops | 16,351,108 | 2 | 2013-05-03T03:28:33Z | 16,351,134 | 9 | 2013-05-03T03:31:32Z | [
"python",
"loops",
"python-3.x"
] | I have the code:
```
num_for_loops = 0
for line in lines:
if line.strip().startswith('for '):
num_for_loops += 1
return num_for_loops
```
I need to condense it down to as little lines as possible. Is there a way to do this by combining the for and if statements?
The context is irrelevant. | ```
num_for_loops = sum(line.strip().startswith("for ") for line in lines)
```
since you're immediately returning `num_for_loops` I suppose you really just want
```
return sum(line.strip().startswith("for ") for line in lines)
``` |
Combine all elements of two arrays python | 16,351,197 | 2 | 2013-05-03T03:38:43Z | 16,351,220 | 7 | 2013-05-03T03:41:10Z | [
"python",
"arrays",
"numpy"
] | I have two arrays, and want to combine the ith elements in each one together:
```
import numpy as np
a = np.array(['a', 'b', 'c'])
b = np.array(['x', 'y', 'z'])
```
I want to return
```
array(['ax', 'by', 'cz'])
```
What is the function for this? Thx, | ```
>>> import numpy as np
>>> a = np.array(['a', 'b', 'c'])
>>> b = np.array(['x', 'y', 'z'])
>>> c = np.array([i+j for i, j in zip(a, b)])
>>> c
array(['ax', 'by', 'cz'],
dtype='|S2')
```
@DSM makes the point that if `a` and `b` had `dtype=object` you could simply add the two arrays together:
```
>>> a = np.a... |
Plotting two functions simultaneously with matplotlib | 16,351,436 | 3 | 2013-05-03T04:07:18Z | 16,351,748 | 10 | 2013-05-03T04:46:36Z | [
"python",
"matplotlib"
] | basically I want to graph two functions
```
g1 = x*cos(x*pi)
g2 = 1 - 0.6x^2
```
and then plot the intersection, I already have a module that takes inputs close to the two lines intersections, and then converges to those points (there's four of them)
but I want to graph these two functions and their intersections us... | Assuming you can get as far as plotting one function, with x and g1 as numpy arrays,
```
pylab.plot(x,g1)
```
just call plot again (and again) to draw any number of separate curves:
```
pylab.plot(x,g2)
```
finally display or save to a file:
```
pylab.show()
```
To indicate a special point such as an intersection... |
Link to Flask static files with url_for | 16,351,826 | 32 | 2013-05-03T04:54:52Z | 16,353,060 | 62 | 2013-05-03T06:36:46Z | [
"python",
"flask",
"jinja2"
] | How do you use `url_for` in Flask to reference a file in a folder? For example, I have some static files in the `static` folder, some of which may be in subfolders such as `static/bootstrap`.
When I try to serve a file from `static/bootstrap`, I get an error.
```
<link rel=stylesheet type=text/css href="{{ url_for('... | You have by default the [`static` endpoint](http://flask.pocoo.org/docs/quickstart/#static-files) for static files. Also [`Flask`](http://flask.pocoo.org/docs/api/#flask.Flask) application has the following arguments:
`static_url_path`: can be used to specify a different path for the static files on the web. Defaults ... |
opencv warpPerspective parameter count | 16,352,962 | 5 | 2013-05-03T06:29:15Z | 16,353,519 | 9 | 2013-05-03T07:09:34Z | [
"python",
"opencv",
"numpy"
] | In my script I have the following code:
```
src = numpy.array(cornersSheet, numpy.float32)
dst = numpy.array(cornersDesired, numpy.float32)
transform = cv2.getPerspectiveTransform(src,dst)
finished = cv2.warpPerspective(img, transform, img.shape)
```
Python says:
```
Traceback (most recent call last):
File "./script... | Problem solved. `img.shape` returns tuple with 3 elements, warpPerspective expects tuple with 2. |
Pandas: How to use apply function to multiple columns | 16,353,729 | 57 | 2013-05-03T07:25:48Z | 16,354,730 | 86 | 2013-05-03T08:40:31Z | [
"python",
"python-2.7",
"pandas",
"dataframe",
"apply"
] | I have some problems with the Pandas apply function, when using multiple columns with the following dataframe
```
df = DataFrame ({'a' : np.random.randn(6),
'b' : ['foo', 'bar'] * 3,
'c' : np.random.randn(6)})
```
and the following function
```
def my_test(a, b):
return a % b
```
When ... | Seems you forgot the `''` of your string.
```
In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)
In [44]: df
Out[44]:
a b c Value
0 -1.674308 foo 0.343801 0.044698
1 -2.163236 bar -2.046438 -0.116798
2 -0.199115 foo -0... |
How to remove tabs and newlines with a regex | 16,355,732 | 3 | 2013-05-03T09:31:29Z | 16,355,876 | 8 | 2013-05-03T09:38:08Z | [
"python",
"regex",
"python-3.x"
] | In Python 3.x, the special re sequence '\s' matches Unicode whitespace characters including [ \t\n\r\f\v].
The following piece of code is intended to replace tabs and newlines with a space.
```
import re
text = """Hello my friends.
How are you doing?
I'm fine."""
output = re.sub('\s', ' ', text)
print(output)
```... | The problem is(likely) that your tab character is just a bunch of spaces.
```
>>> re.sub(r"\s+", " ", text)
"Hello my friends. How are you doing? I'm fine."
``` |
Installing hstore extension in django nose tests | 16,355,895 | 3 | 2013-05-03T09:39:08Z | 16,369,007 | 17 | 2013-05-03T23:32:14Z | [
"python",
"django",
"postgresql",
"nose",
"hstore"
] | I've installed the hstore extension successfully, and everything works when I `syncdb`. (I'm using [djorm-ext-hstore](https://github.com/niwibe/djorm-ext-hstore))
However, nose creates a new temp database to run tests in, and hstore is not installed in it.
I need to run `CREATE EXTENSION HSTORE;` on the test db right... | This is a non-issue: The best way to fix this is to apply the hstore extension on the default database, `template1`
`psql -d template1 -c 'create extension hstore;'`
Reference: [How to create a new database with the hstore extension already installed?](http://stackoverflow.com/questions/11584749/how-to-create-a-new-d... |
String format a json String gives KeyError | 16,356,810 | 9 | 2013-05-03T10:30:17Z | 16,356,826 | 15 | 2013-05-03T10:31:26Z | [
"python",
"string",
"format"
] | Why does this code give a `KeyError`?
```
output_format = '{ "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" }'
print output_format.format(filename='My_file_name',
success=True,
error_msg='',
... | You need to double the outer braces; otherwise Python thinks `{ "File"..` is a reference too:
```
output_format = '{{ "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" }}'
```
Result:
```
>>> print output_format.format(filename='My_file_name',
... ... |
Inserting datetime into MySql db | 16,359,143 | 5 | 2013-05-03T12:38:21Z | 16,359,620 | 9 | 2013-05-03T13:06:04Z | [
"python",
"mysql",
"python-2.7"
] | I have a datetime value which is made by strptime function
```
import MySQLdb
a = time.strptime('my date', "%b %d %Y %H:%M")
```
There is a column in MySql db of type DATETIME. When I try to insert this value into db, I, obviously, get the error of
```
mysql_exceptions.OperationalError: (1305, 'FUNCTION time.struct_... | You are now passing in a `time.struct_time` object, something MySQL knows nothing about. You'll need to format the timestamp to a format MySQL understands. Unfortunately the `MySQLdb` library doesn't do this for you.
It'll be easiest using the `datetime` module, but you can do this with the `time` module too:
```
imp... |
How does Python's cmp_to_key function work? | 16,362,744 | 24 | 2013-05-03T15:41:40Z | 16,362,818 | 28 | 2013-05-03T15:44:27Z | [
"python",
"algorithm",
"sorting",
"cmp",
"python-internals"
] | I came across this function [here](http://docs.python.org/2/library/functools.html).
I am baffled as to how this would be implemented -- how does the `key` function generated by `cmp_to_key` know what "position" a given element should be without checking how the given element compares with every other element of inter... | The `cmp_to_key` method returns a special object that acts as a surrogate key:
```
class K(object):
__slots__ = ['obj']
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, o... |
Pandas error: 'DataFrame' object has no attribute 'loc' | 16,363,233 | 6 | 2013-05-03T16:07:16Z | 16,363,504 | 9 | 2013-05-03T16:24:22Z | [
"python",
"python-2.7",
"numpy",
"scipy",
"pandas"
] | I am new to `pandas` and is trying the Pandas 10 minute tutorial with pandas version 0.10.1. However when I do the following, I get the error as shown below. `print df` works fine.
Why is `.loc` not working?
**Code**
```
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(6,4), index=pd.date_ra... | `loc` was [introduced in 0.11](http://pandas.pydata.org/pandas-docs/stable/whatsnew.html), so you'll need to upgrade your pandas to follow [the 10minute introduction](http://pandas.pydata.org/pandas-docs/stable/10min.html). |
Does exist built-in function in Python to find best value that satisfies some condition? | 16,363,726 | 2 | 2013-05-03T16:36:07Z | 16,363,749 | 9 | 2013-05-03T16:37:39Z | [
"python",
"python-2.7",
"python-3.x"
] | Does exist built-in function in Python, that can find best value that satisfies some condition (specified by a funciton)? For example something instead this code:
```
def argmin(seq, fn):
best = seq[0]; best_score = fn(best)
for x in seq:
x_score = fn(x)
if x_score < best_score:
bes... | I presume by 'best' you mean highest, in which case the answer is simple - [`max()`](http://docs.python.org/3.3/library/functions.html#max).
It takes a `key` argument, which would be your function.
```
max(data, key=score)
```
Naturally, if 'best' means lowest, as DSM points out, then you just want [`min()`](http://... |
Execution order on python unittest | 16,364,433 | 5 | 2013-05-03T17:21:34Z | 16,364,514 | 13 | 2013-05-03T17:26:18Z | [
"python",
"unit-testing"
] | I need to set an order of execution for my tests, cause I need some data verified before the others. Is possible to set an order?
```
class OneTestCase(unittest.TestCase):
def setUp(self):
# something to do
def test_login (self):
# first test
pass
def test_other (self):
# an... | You can do it like this:
```
class OneTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
# something to do
pass
def test_01_login (self):
# first test
pass
def test_02_other (self):
# any order after test_login
def test_03_othermore (self):
... |
Python PyQt: QTableWidget - get cell value based on header string and selected row | 16,367,090 | 2 | 2013-05-03T20:31:50Z | 16,399,885 | 9 | 2013-05-06T13:32:20Z | [
"python",
"pyqt",
"qtablewidget"
] | For example, I have a PyQt QTableWidget which has 3 columns and 2 rows.
The column headers are labeled A, B, and C.
```
A B C
1 2 3
4 5 6
```
This is the excerpt from my current source:
```
class myform(QtGui.QMainWindow):
def __init__(self, parent=None):
super(myform, self).__init__(parent)
s... | Here is the code I came up with. Feel free to provide feedback.
```
#===================================================================
# given a tablewidget which has a selected row...
# return the column value in the same row which corresponds to a given column name
# fyi: columnname is case sensitive
#============... |
Check if object is list of list in python? | 16,367,848 | 13 | 2013-05-03T21:33:19Z | 16,367,884 | 20 | 2013-05-03T21:35:46Z | [
"python",
"list"
] | Is there any ways we can detect if an object is list in python using `type(obj)` --> `list`.
But how can we detect if the object is list of list of the form as:
```
[['a','b']['a','b'][][]]
``` | Use [`isinstance()`](http://docs.python.org/2/library/functions.html#isinstance) to check for a specific type:
```
>>> isinstance([], list)
True
```
Use [`all()`](http://docs.python.org/2/library/functions.html#all) to test if *all* elements are of a certain type:
```
all(isinstance(elem, list) for elem in list_of_l... |
Python struct.pack() for individual elements in a list? | 16,368,263 | 9 | 2013-05-03T22:05:52Z | 16,368,299 | 11 | 2013-05-03T22:09:33Z | [
"python",
"list",
"struct",
"udp",
"pack"
] | I would like to pack all the data in a list into a single buffer to send over a UDP socket. The list is relatively long, so indexing each element in the list is tedious. This is what I have so far:
```
NumElements = len(data)
buf = struct.pack('d'*NumElements,data[0],data[1],data[2],data[3],data[4])
```
But I would l... | Yes, you can use the `*args` calling syntax.
Instead of this:
```
buf = struct.pack('d'*NumElements,data) # Returns error
```
⦠do this:
```
buf = struct.pack('d'*NumElements, *data) # Works
```
See [Unpacking Argument Lists](http://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists) in the tu... |
Tkinter adding line number to text widget | 16,369,470 | 9 | 2013-05-04T00:43:31Z | 16,375,233 | 20 | 2013-05-04T14:14:12Z | [
"python",
"tkinter"
] | Trying to learn tkinter and python. I want to display line number for the Text widget in an adjacent frame
```
from Tkinter import *
root = Tk()
txt = Text(root)
txt.pack(expand=YES, fill=BOTH)
frame= Frame(root, width=25)
#
frame.pack(expand=NO, fill=Y, side=LEFT)
root.mainloop()
```
I have seen an example on a sit... | I have a relatively foolproof solution, but it's complex and will likely be hard to understand because it requires some knowledge of how Tkinter and the underlying tcl/tk text widget works. I'll present it here as a complete solution that you can use as-is because I think it illustrates a unique approach that works qui... |
maximum recursion depth exceeded in cmp error while executing python manage.py runserver | 16,369,637 | 4 | 2013-05-04T01:16:30Z | 21,834,800 | 7 | 2014-02-17T16:51:36Z | [
"python",
"django"
] | I'm trying to install Django in my mac. when I run the command python manage.py runserver. I get the error RuntimeError: maximum recursion depth exceeded in cmp. I have pasted my error message below. I even increased the setrecursion limit to 2000 and tried, it didn't work. Any of your help in fixing this is appreciate... | The problem is in functools.py file. This file is from Python. I have just installed a new version of python 2.7.5 and the file is wrong (I have another older instalation of python 2.7.5 and ther the file functools.py is correct)
To fix the problem replace this (about line 56 in python\Lib\fuctools.py):
```
conve... |
pip issue installing almost any library | 16,370,583 | 20 | 2013-05-04T04:29:21Z | 16,370,731 | 25 | 2013-05-04T04:54:00Z | [
"python",
"pip",
"nltk",
"easy-install"
] | I'm having a difficult time using pip to install almost anything. I'm new to coding, so I thought maybe this is something I've been doing wrong and have opted out to easy\_install to get most of what I needed done, wich has generally worked. However, now I'm trying to download the nltk library, and neither is getting t... | You're probably seeing [this bug](https://github.com/pypa/pip/issues/829); see also [here](http://stackoverflow.com/questions/15441224/can-i-relink-enthought-python-to-new-version-of-openssl-on-mac-os-x).
The easiest workaround is to downgrade pip to one that doesn't use SSL: `easy_install pip==1.2.1`. This loses you ... |
pip issue installing almost any library | 16,370,583 | 20 | 2013-05-04T04:29:21Z | 21,324,905 | 9 | 2014-01-24T05:07:26Z | [
"python",
"pip",
"nltk",
"easy-install"
] | I'm having a difficult time using pip to install almost anything. I'm new to coding, so I thought maybe this is something I've been doing wrong and have opted out to easy\_install to get most of what I needed done, wich has generally worked. However, now I'm trying to download the nltk library, and neither is getting t... | Another cause of SSL errors can be a bad system time â certificates won't validate if it's too far off from the present. |
pip issue installing almost any library | 16,370,583 | 20 | 2013-05-04T04:29:21Z | 38,908,406 | 8 | 2016-08-12T01:16:09Z | [
"python",
"pip",
"nltk",
"easy-install"
] | I'm having a difficult time using pip to install almost anything. I'm new to coding, so I thought maybe this is something I've been doing wrong and have opted out to easy\_install to get most of what I needed done, wich has generally worked. However, now I'm trying to download the nltk library, and neither is getting t... | I found it sufficient to specify the pypi host as trusted. Example:
```
pip install --trusted-host pypi.python.org pytest-xdist
pip install --trusted-host pypi.python.org --upgrade pip
```
This solved the following error:
```
Could not fetch URL https://pypi.python.org/simple/pytest-cov/: There was a problem confi... |
Why does re.findall() find more matches than re.sub()? | 16,371,472 | 16 | 2013-05-04T06:52:53Z | 16,372,039 | 7 | 2013-05-04T08:05:25Z | [
"python",
"regex"
] | Consider the following:
```
>>> import re
>>> a = "first:second"
>>> re.findall("[^:]*", a)
['first', '', 'second', '']
>>> re.sub("[^:]*", r"(\g<0>)", a)
'(first):(second)'
```
`re.sub()`'s behavior makes more sense initially, but I can also understand `re.findall()`'s behavior. After all, you can match an empty str... | You use the \* which allows empty matches:
```
'first' -> matched
':' -> not in the character class but, as the pattern can be empty due
to the *, an empty string is matched -->''
'second' -> matched
'$' -> can contain an empty string before,
an empty string is matched -->''
`... |
Stream results in celery | 16,371,552 | 9 | 2013-05-04T07:04:10Z | 16,528,956 | 11 | 2013-05-13T18:43:45Z | [
"python",
"celery"
] | I'm trying to use celery to schedule and run tasks on a fleet of servers. Each task is somewhat long running (few hours), and involves using subprocess to call a certain program with the given inputs. This program produces a lot of output both in stdout and stderr.
Is there some way to show the output produced by the ... | You did not specify many requirements and constraints. I'm going to assume you already have a redis instance somewhere.
What you can do is read the output from the other process line by line and publish it through redis:
Here's an example where you can `echo` data into a file `/tmp/foo` for testing:
```
import redis... |
Add Text on Image using PIL | 16,373,425 | 30 | 2013-05-04T10:44:53Z | 16,377,244 | 76 | 2013-05-04T17:49:22Z | [
"python",
"django",
"image",
"python-imaging-library"
] | I have an application that loads an Image and when the user clicks it, a text area appears for this Image (using `jquery`), where user can write some text on the Image. Which should be added on Image.
After doing some research on it, I figured that `PIL` (Python Imaging Library ) can help me do this. So I tried couple... | I think [ImageFont](http://effbot.org/imagingbook/imagefont.htm) module available in `PIL` should be helpful in solving text font size problem. Just check what font type and size is appropriate for you and use following function to change font values.
```
# font = ImageFont.truetype(<font-file>, <font-size>)
# font-fi... |
set the text of an entry using a button tkinter | 16,373,887 | 4 | 2013-05-04T11:42:19Z | 16,374,273 | 13 | 2013-05-04T12:24:52Z | [
"python",
"events",
"tkinter",
"entry"
] | Thanks for reply.
I am getting my feet wet with Tkinter.
I am trying to set the text of an entry using a button in a GUI using Tkinter.
This GUI is to help me classify thousands of words. into five categories, each of the categories has a button. I was hoping that using a button would significantly speed me up and I wa... | You might want to use `insert` method.
This script inserts a text into Entry. The inserted text can be changed in command parameter of the Button.
```
from Tkinter import *
def set_text(text):
e.delete(0,END)
e.insert(0,text)
return
win = Tk()
e = Entry(win,width=10)
e.pack()
b1 = Button(win,text="ani... |
Cannot import flask from project directory but works everywhere else | 16,373,890 | 6 | 2013-05-04T11:42:22Z | 16,373,923 | 12 | 2013-05-04T11:46:11Z | [
"python",
"flask"
] | So I have run into a funny problem when trying to use Flask, I can only run it from ~/ (home) and not from ~/Projects/projectfolder. I'm using Python 2.7.4 installed via their homepage, virtualenv and virtualenvwrapper. Every time it's the same:
```
$ mkvirtualenv project
New python executable in project/bin/python
In... | According to you traceback, you have a module of your own called `flask.py` in `~/Projects/example`.
The current directory is searched before the actual package installation path, so it shadows the "real" Flask. |
Efficient way to convert a list to dictionary | 16,374,540 | 5 | 2013-05-04T12:55:46Z | 16,374,553 | 12 | 2013-05-04T12:57:04Z | [
"python"
] | I need help in the most efficient way to convert the following list into a dictionary:
```
l = ['A:1','B:2','C:3','D:4']
```
At present, I do the following:
```
mydict = {}
for e in l:
k,v = e.split(':')
mydict[k] = v
```
However, I believe there should be a more efficient way to achieve the same. Any idea ... | use `dict()` with a generator expression:
```
>>> lis=['A:1','B:2','C:3','D:4']
>>> dict(x.split(":") for x in lis)
{'A': '1', 'C': '3', 'B': '2', 'D': '4'}
```
Using dict-comprehension ( as suggested by @PaoloMoretti):
```
>>> {k:v for k,v in (e.split(':') for e in lis)}
{'A': '1', 'C': '3', 'B': '2', 'D': '4'}
```... |
Plotting a Pandas DataSeries.GroupBy | 16,376,159 | 6 | 2013-05-04T15:56:27Z | 16,377,383 | 10 | 2013-05-04T18:05:32Z | [
"python",
"python-2.7",
"numpy",
"scipy",
"pandas"
] | I am new to python and pandas, and have the following `DataFrame`.
How can I plot the `DataFrame` where each `ModelID` is a separate plot, `saledate` is the x-axis and `MeanToDate` is the y-axis?
**Attempt**
```
data[40:76].groupby('ModelID').plot()
```
:
```
import matplotlib.pyplot as plt
for i, group in df.groupby('ModelID'):
plt.figure()
group.plot(x='saleDate', y='MeanToDate', title=str(i)... |
Using bootstrap and django | 16,376,910 | 7 | 2013-05-04T17:13:53Z | 19,848,215 | 15 | 2013-11-07T22:42:21Z | [
"python",
"html",
"django",
"twitter-bootstrap"
] | I am trying to get bootstrap working in my django project and followed the tutorial [here](http://www.pythondiary.com/blog/Sep.18,2012/bootstrap-and-django-14-guide.html)
but it did not work. When i visit the my local project in the browser it just shows a blank page with 4 blue links. not exaclty what i was expecting.... | Kevin here, the author of that article from Python Diary. Since I posted that tutorial I have created other methods of enabling Bootstrap in a Django project, including a handy Project template, which can be downloaded from here:
<http://www.pythondiary.com/templates/bootstrap>
I have also started a Project on BitBuc... |
How to pickle a namedtuple instance correctly | 16,377,215 | 26 | 2013-05-04T17:46:07Z | 16,377,267 | 35 | 2013-05-04T17:51:53Z | [
"python",
"python-2.7",
"pickle",
"namedtuple"
] | I'm learning how to use pickle. I've created a namedtuple object, appended it to a list, and tried to pickle that list. However, I get the following error:
```
pickle.PicklingError: Can't pickle <class '__main__.P'>: it's not found as __main__.P
```
I found that if I ran the code without wrapping it inside a function... | Create the named tuple *outside* of the function:
```
from collections import namedtuple
import pickle
P = namedtuple("P", "one two three four")
def pickle_test():
my_list = []
abe = P("abraham", "lincoln", "vampire", "hunter")
my_list.append(abe)
f = open('abe.pickle', 'w')
pickle.dump(abe, f)
... |
Find all links within a div using lxml | 16,378,132 | 3 | 2013-05-04T19:28:46Z | 16,378,172 | 7 | 2013-05-04T19:34:11Z | [
"python",
"web-crawler",
"lxml",
"python-2.x",
"mechanize-python"
] | I'm writing a tool that needs a collect all urls within a div on a web page but no urls outside that div. Simplified the page it looks something like this:
```
<div id="bar">
<a link I dont want>
<div id="foo">
<lots of html>
<h1 class="baz">
<a href=âlink I wantâ>
</h1>
<h1 ... | You probably want this:
```
hrefs = root.xpath('//div[@id="foo"]//a/@href')
```
This will give you a list of all `href` values from `a` tags inside `<div id="foo">` at any level |
How to use different view for django-registration? | 16,379,300 | 4 | 2013-05-04T21:48:40Z | 16,379,581 | 17 | 2013-05-04T22:34:18Z | [
"python",
"django",
"django-registration"
] | I have been trying to get django-registration to use the view RegistrationFormUniqueEmail and following the solution from this [django-registration question](http://stackoverflow.com/questions/2131533/django-registration-force-unique-e-mail). I have set my urls.py to
```
from django.conf.urls import patterns, include,... | The version of Django registration you are using has been rewritten to use class based views. This means a different approach is required in your urls.py.
First, You need to subclass the RegistrationView, and set the custom form class.
```
from registration.backends.default.views import RegistrationView
from registra... |
How to use the a k-fold cross validation in scikit with naive bayes classifier and NLTK | 16,379,313 | 14 | 2013-05-04T21:50:36Z | 16,379,570 | 17 | 2013-05-04T22:32:47Z | [
"python",
"scikit-learn",
"nltk",
"bayesian",
"cross-validation"
] | I have a small corpus and I want to calculate the accuracy of naive Bayes classifier using 10-fold cross validation, how can do it. | Your options are to either set this up yourself or use something like [NLTK-Trainer](https://github.com/japerk/nltk-trainer) since NLTK [doesn't directly support cross-validation for machine learning algorithms](https://github.com/nltk/nltk/issues/132).
I'd recommend probably just using another module to do this for y... |
How to use the a k-fold cross validation in scikit with naive bayes classifier and NLTK | 16,379,313 | 14 | 2013-05-04T21:50:36Z | 16,388,804 | 11 | 2013-05-05T20:27:04Z | [
"python",
"scikit-learn",
"nltk",
"bayesian",
"cross-validation"
] | I have a small corpus and I want to calculate the accuracy of naive Bayes classifier using 10-fold cross validation, how can do it. | I've used both libraries and NLTK for naivebayes sklearn for crossvalidation as follows:
```
import nltk
from sklearn import cross_validation
training_set = nltk.classify.apply_features(extract_features, documents)
cv = cross_validation.KFold(len(training_set), n_folds=10, indices=True, shuffle=False, random_state=Non... |
Check if substring is in a list of strings in python | 16,380,326 | 13 | 2013-05-05T00:49:21Z | 16,380,333 | 16 | 2013-05-05T00:50:26Z | [
"python",
"string",
"list"
] | I have found some answers to this question before, but they seem to be obsolete for the current Python versions (or at least they don't work for me).
I want to check if a substring is contained in a list of strings. I only need the boolean result.
I found this solution:
```
word_to_check = 'or'
wordlist = ['yellow',... | You can import `any` from `__builtin__` in case it was replaced by some other `any`:
```
>>> from __builtin__ import any as b_any
>>> lis= ['yellow', 'orange', 'red']
>>> word = "or"
>>> b_any(word in x for x in lis)
True
```
Noe that in Python 3 `__builtin__` has been renamed to `builtins`. |
Check if substring is in a list of strings in python | 16,380,326 | 13 | 2013-05-05T00:49:21Z | 16,381,580 | 8 | 2013-05-05T05:04:34Z | [
"python",
"string",
"list"
] | I have found some answers to this question before, but they seem to be obsolete for the current Python versions (or at least they don't work for me).
I want to check if a substring is contained in a list of strings. I only need the boolean result.
I found this solution:
```
word_to_check = 'or'
wordlist = ['yellow',... | The code you posted using *any()* is correct and should work unless you've redefined it somewhere.
That said, there is a simple and fast solution to be had by using the substring search on a single combined string:
```
>>> wordlist = ['yellow','orange','red']
>>> combined = '\t'.join(wordlist)
>>> 'or' in combined
T... |
Legend in python without labels | 16,380,877 | 3 | 2013-05-05T02:41:28Z | 16,381,514 | 7 | 2013-05-05T04:51:08Z | [
"python",
"matplotlib",
"legend"
] | I would like to show a fixed legend in a python matplotlib plot. I am creating a large set of plots, and some of them lack one of the datasets I am using. Let's say I have
data1, plotted in green
data2, plotted in blue
data3, plotted in blue
for some cases, dataX is missing, but I would like to show the whole legen... | For the plots where `dataX` is missing, you can call the plot command as normal, just leave the *x* and *y* arrays empty:
```
import matplotlib.pyplot as plt
plt.plot([0.1,0.5], [0.1,0.5], color='g', label='data1')
plt.plot([], [], color='b', label='data2')
plt.plot([0.2,0.6], [0.1,0.5], color='b', label='data3')
plt... |
Sending e-mails using yahoo account in python | 16,381,527 | 4 | 2013-05-05T04:53:05Z | 16,381,538 | 11 | 2013-05-05T04:55:02Z | [
"python",
"email",
"smtp"
] | I have `yahoo` account.
Is there any python code to send email from my account ? | Yes ; here is the code :
```
import smtplib
fromMy = '[email protected]' # fun-fact: from is a keyword in python, you can't use it as variable, did abyone check if this code even works?
to = '[email protected]'
subj='TheSubject'
date='2/1/2010'
message_text='Hello Or any thing you want to send'
msg = "From: %s\nT... |
How to judge a int number odd or even? (the binary way) | 16,382,403 | 5 | 2013-05-05T07:37:01Z | 16,382,427 | 11 | 2013-05-05T07:40:59Z | [
"python",
"binary",
"decimal"
] | I wanna use basic knowledge to improve the efficiency of code.
I know that in binary system. when the last digit of number is 1,this is a odd number.and 0 is even number.
How to use this way to judge a int number in python? Is that python give any build-in method to do it? | AND it with 1:
```
0000101001000101
0000000000000001
&
__________________
0000000000000001
```
If you get `1`, the number is odd. If you get `0`, the number is even. While this works, I would use the modulo operator instead:
```
>>> 8888 % 2
0
>>> 8881 % 2
1
```
It works the same way, is just as fast and look... |
How do I get the most recent Cloudwatch metric data for an instance using Boto? | 16,383,809 | 9 | 2013-05-05T11:00:48Z | 16,383,810 | 20 | 2013-05-05T11:00:48Z | [
"python",
"amazon-web-services",
"boto",
"amazon-cloudwatch"
] | I'm trying to get the most recent data for CPU utilization for an instance (actually, several instances, but just one to start with), however the following call doesn't return any data:
```
cw = boto.cloudwatch.connect_to_region(Region)
cw.get_metric_statistics(
300,
datetime.datetime.now() - datetime.timedelt... | This is a daylight savings time / time zone issue!
You need to use UTC time when receiving statistics from Cloudwatch:
```
cw = boto.cloudwatch.connect_to_region(Region)
cw.get_metric_statistics(
300,
datetime.datetime.utcnow() - datetime.timedelta(seconds=600),
datetime.datetime.utcno... |
Iterate over all combinations of values in multiple lists in python | 16,384,109 | 20 | 2013-05-05T11:36:55Z | 16,384,126 | 42 | 2013-05-05T11:38:20Z | [
"python"
] | Given multiple list of possibly varying length, I want to iterate over all combinations of values, one item from each list. For example:
```
first = [1, 5, 8]
second = [0.5, 4]
```
Then I want the output of to be:
```
combined = [(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]
```
I want to iterate over the *... | [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product) should do the trick.
```
>>> list(itertools.product([1, 5, 8], [0.5, 4]))
[(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]
```
Note that `itertools.product` returns an iterator, so you don't need to convert it into a list i... |
More Pythonic way of counting things in a heavily nested defaultdict | 16,384,174 | 6 | 2013-05-05T11:43:39Z | 16,384,416 | 8 | 2013-05-05T12:14:56Z | [
"python",
"defaultdict"
] | My code currently has to count things in a heavily nested `dict` into another. I have items that need to be indexed by 3 values and then counted. So, before my loop, I initialize a nested `defaultdict` like so:
```
from collections import defaultdict
type_to_count_dic = defaultdict(
lambda: defaultdict(
... | ```
from collections import defaultdict
class _defaultdict(defaultdict):
def __add__(self, other):
return other
def CountTree():
return _defaultdict(CountTree)
```
---
```
>>> t = CountTree()
>>> t['a']
defaultdict(<function CountTree at 0x9e5c3ac>, {})
>>> t['a']['b']['c'] += 1
>>> print t['a']['b'... |
How to speed up pandas row filtering by string matching? | 16,384,332 | 6 | 2013-05-05T12:04:30Z | 16,403,590 | 8 | 2013-05-06T17:05:07Z | [
"python",
"filter",
"pandas"
] | I often need to filter pandas dataframe `df` by `df[df['col_name']=='string_value']`, and I want to speed up the row selction operation, is there a quick way to do that ?
For example,
```
In [1]: df = mul_df(3000,2000,3).reset_index()
In [2]: timeit df[df['STK_ID']=='A0003']
1 loops, best of 3: 1.52 s per loop
```
... | I have long wanted to add binary search indexes to DataFrame objects. You can take the DIY approach of sorting by the column and doing this yourself:
```
In [11]: df = df.sort('STK_ID') # skip this if you're sure it's sorted
In [12]: df['STK_ID'].searchsorted('A0003', 'left')
Out[12]: 6000
In [13]: df['STK_ID'].sear... |
How to debug sublime plugins during development | 16,384,626 | 6 | 2013-05-05T12:39:34Z | 16,385,039 | 14 | 2013-05-05T13:30:54Z | [
"python",
"debugging",
"sublimetext2",
"sublimetext",
"pdb"
] | I want to debug my plugin with pdb but it doesn't work. I get these errors
```
Traceback (most recent call last):
File "./sublime_plugin.py", line 362, in run_
File "./useIt.py", line 14, in run
for region in self.view.sel():
File "./useIt.py", line 14, in run
for region in self.view.sel():
File ".\bdb... | The problem is that `sys.stdin` is not attached to anything *normally*. But, `sys.stdin` does work if you start SublimeText2 from a console:
* On Mac, start the application by locating the executable in the resource bundle by entering the full path in the Terminal:
```
/Applications/Sublime\ Text\ 2.app/Contents/... |
Executing Python with Gvim | 16,385,589 | 6 | 2013-05-05T14:34:11Z | 16,385,762 | 10 | 2013-05-05T14:53:44Z | [
"python",
"windows",
"vim"
] | * open gVim.
* then using the File Menu and MenuItem Open to open a
file pi.py which has the following tiny script:

How do I execute this code using gVim?
---
**EDIT**
If I use either `:! python pi.py` or `:w !python -` then I get the following:... | You don't need to save the file, you can run the current buffer as stdin to a command such as `python` by typing:
```
:w !python -
```
(The hyphen at the end probably isn't necessary, python will generally use stdin by default)
edit: seeing as you are new to vim, note that this will not save the file, it will just r... |
Add days to dates in dataframe | 16,385,785 | 3 | 2013-05-05T14:56:02Z | 16,385,853 | 7 | 2013-05-05T15:04:17Z | [
"python",
"pandas"
] | I am stymied at the moment. I am sure that I am missing something simple, but how do you move a series of dates forward by x units? In my more specific case I want to add 180 days to a date series within a dataframe.
Here is what I have so far:
```
import pandas, numpy, StringIO, datetime
txt = '''ID,DATE
002691c9c... | If I understand you, you don't actually want `shift`, you simply want to make a new column next to the existing `DATE` which is 180 days after. In that case, you can use `timedelta`:
```
>>> from datetime import timedelta
>>> df.head()
ID DATE
8 0103bd73af66e5a44f7867c0... |
Open images? Python | 16,387,069 | 2 | 2013-05-05T17:21:05Z | 16,387,154 | 12 | 2013-05-05T17:29:40Z | [
"python",
"image"
] | Im creating a text based labryinth game, but I figured it needed some pictures to illustrate whats going on. For some reason it just dies when I try to go to a2(Where the picture should pop up). I am a beginner so dont judge my code so much ^^
```
import Image
a1 = ("a1 Go to the start of the Labyrinth", "You're at th... | Instead of
```
Image.open(picture.jpg)
Img.show
```
You should have
```
from PIL import Image
#...
img = Image.open('picture.jpg')
img.show()
```
You should probably also think about an other system to show your messages, because this way it will be a lot of manual work. Look into string substitution (using `%s` ... |
How to prepend data to the binary file? | 16,387,639 | 3 | 2013-05-05T18:23:22Z | 16,387,689 | 7 | 2013-05-05T18:27:31Z | [
"python",
"file",
"python-3.x"
] | I have a big binary file. How I can write (prepend) to the begin of the file?
Ex:
```
file = 'binary_file'
string = 'bytes_string'
```
I expected get new file with content: `bytes_string_binary_file`.
Construction `open("filename", ab)` appends only.
I'm using Python 3.3.1. | There is no way to prepend to a file. You **must** rewrite the file completely:
```
with open("oldfile", "rb") as old, open("newfile", "wb") as new:
new.write(string)
new.write(old.read())
```
If you want to avoid reading the whole file into memory, simply read it by chunks:
```
with open("oldfile", "rb") as... |
How to integrate SimpleGUI with Python 2.7 and 3.0 shell | 16,387,770 | 17 | 2013-05-05T18:36:25Z | 16,400,940 | 7 | 2013-05-06T14:30:38Z | [
"python",
"python-2.7",
"python-3.x",
"python-imaging-library",
"codeskulptor"
] | I am learning Python from Coursera. In this course they use **SimpleGUI** module on [CodeSkulptor](http://www.codeskulptor.org/). Can anyone tell me how to integrate SimpleGUI with python 2.7 and 3.0 shell? | From the coursera forums by Darren Gallagher
> From the CodeSkulptor Documentation:
>
> <http://www.codeskulptor.org/docs.html>
>
> "... implements a subset of Python 2.6...CodeSkulptor's Python is not a subset in one respect...Implemented on top of JavaScript..."
>
> I don't think that CodeSkulptor / SimpleGUI is a P... |
How to integrate SimpleGUI with Python 2.7 and 3.0 shell | 16,387,770 | 17 | 2013-05-05T18:36:25Z | 17,039,935 | 16 | 2013-06-11T08:47:55Z | [
"python",
"python-2.7",
"python-3.x",
"python-imaging-library",
"codeskulptor"
] | I am learning Python from Coursera. In this course they use **SimpleGUI** module on [CodeSkulptor](http://www.codeskulptor.org/). Can anyone tell me how to integrate SimpleGUI with python 2.7 and 3.0 shell? | You can just use SimpleGUITk (<http://pypi.python.org/pypi/SimpleGUITk>) which implements a Tk version of simplegui.
To use your CodeSkulptor code in the desktop, you just need to replace
```
import simplegui
```
with
```
import simpleguitk as simplegui
```
and that's it, your program made for CodeSkulptor code sh... |
How to integrate SimpleGUI with Python 2.7 and 3.0 shell | 16,387,770 | 17 | 2013-05-05T18:36:25Z | 19,612,310 | 14 | 2013-10-26T21:52:05Z | [
"python",
"python-2.7",
"python-3.x",
"python-imaging-library",
"codeskulptor"
] | I am learning Python from Coursera. In this course they use **SimpleGUI** module on [CodeSkulptor](http://www.codeskulptor.org/). Can anyone tell me how to integrate SimpleGUI with python 2.7 and 3.0 shell? | You can use my

**SimpleGUICS2Pygame** package.
Objectively, this is the best solution :-)
**The package implement *simplegui*, *codeskulptor*, *numeric* and *simpleplot* modules.**
* Online HTML **documentation**: <https://simpleguics2pygame.readth... |
How to center a window with PyGObject | 16,389,188 | 5 | 2013-05-05T21:12:41Z | 16,389,270 | 10 | 2013-05-05T21:22:47Z | [
"python",
"window",
"pygobject"
] | I'm currently trying to center my application window, but it seems to be impossible with PyGObject (GTK+ 3). Indeed, with pyGTK, I was doing it this way:
```
window.set_position(gtk.WIN_POS_CENTER)
```
So this time I'm trying this:
```
window.set_position(Gtk.WIN_POST_CENTER)
```
set\_position seems still existing,... | pydoc tells you what you need to know:
```
>>> help(window.set_position)
Help on method set_position in module gi.repository.Gtk:
set_position(*args, **kwargs) method of gi.overrides.Gtk.Window instance
set_position(self, position:Gtk.WindowPosition)
```
`Gtk.WindowPosition` wraps the enum values, so try:
```
... |
Verbose deprecation warnings in Django | 16,389,572 | 7 | 2013-05-05T22:01:11Z | 16,457,346 | 15 | 2013-05-09T08:14:37Z | [
"python",
"django",
"warnings",
"django-1.5",
"deprecation-warning"
] | After upgrading from django 1.3 to django 1.5 I started to see these `DeprecationWarnings` during the test run:
> path\_to\_virtualenv/lib/python2.6/site-packages/django/http/request.py:193:
> DeprecationWarning: HttpRequest.raw\_post\_data has been deprecated. Use
> HttpRequest.body instead.
I've searched inside the... | You can set [Python warning control](http://docs.python.org/2/using/cmdline.html#cmdoption-W) by command line option `-W` to raise an exception with a **traceback** on **DeprecationWarning** like for errors instead of normal simple warning once. Any specific warning can by filtered by message, category, module, line or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.