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
Replace string within file contents
4,128,144
30
2010-11-08T21:16:35Z
4,128,199
9
2010-11-08T21:21:35Z
[ "python", "string", "file-io" ]
How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"?
Something like ``` file = open('Stud.txt') contents = file.read() replaced_contents = contents.replace('A', 'Orange') <do stuff with the result> ```
Replace string within file contents
4,128,144
30
2010-11-08T21:16:35Z
17,548,459
25
2013-07-09T12:43:34Z
[ "python", "string", "file-io" ]
How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"?
If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing: I am using [the with statement](https://docs.python.org/2/reference/compound_stmts.html#grammar-token-with_stmt) in this example, which closes the file after the `w...
How do I display real-time graphs in a simple UI for a python program?
4,129,697
15
2010-11-09T01:28:44Z
4,130,011
18
2010-11-09T02:37:15Z
[ "python", "matplotlib", "pyqt", "vispy" ]
I have a complicated algorithm that updates 3 histograms that are stored in arrays. I want to debug my algorithm, so I was thinking of showing the arrays as histograms in a user interface. What is the easiest way to do this. (Rapid application development is more important than optimized code.) I have some experience ...
Edit: Nowadays, it is easier and better to use `matplotlib.animation`: ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def animate(frameno): x = mu + sigma * np.random.randn(10000) n, _ = np.histogram(x, bins, normed=True) for rect, h in zip(patches, n): ...
How do I display real-time graphs in a simple UI for a python program?
4,129,697
15
2010-11-09T01:28:44Z
14,791,730
9
2013-02-09T21:21:18Z
[ "python", "matplotlib", "pyqt", "vispy" ]
I have a complicated algorithm that updates 3 histograms that are stored in arrays. I want to debug my algorithm, so I was thinking of showing the arrays as histograms in a user interface. What is the easiest way to do this. (Rapid application development is more important than optimized code.) I have some experience ...
For realtime plotting, I recommend trying Chaco, pyqtgraph, or any of the opengl-based libraries like glumpy or visvis. Matplotlib, wonderful as it is, is generally not suitable for this kind of application. **Edit:** the developers of glumpy, visvis, galry, and pyqtgraph are all collaborating on a visualization libra...
Why aren't anonymous (C)Python objects deallocated immediately?
4,129,950
4
2010-11-09T02:23:12Z
4,129,987
8
2010-11-09T02:33:04Z
[ "python", "garbage-collection" ]
I noticed something about CPython's object deallocation which piqued my curiosity. Let's say I define a type that prints a message from its `tp_dealloc` function: ``` static void pyfoo_Bar_dealloc(pyfoo_Bar* self) { PySys_WriteStdout("Bar freed\n"); self->ob_type->tp_free((PyObject*)self); } ``` I've a...
Because after you called `pyfoo.Bar()` the object is still accessible using the special object `_` This works with pure Python, by the way: ``` class X: def __del__(self): print 'deleted' ``` And later: ``` >>>a = X() >>>a = None deleted >>>X() <__main__.X instance at 0x7f391bb066c8> >>> _ <__ma...
The new file/directory structure of Pyramid (Pylons) is causing me some confusion
4,130,014
9
2010-11-09T02:37:49Z
4,130,836
26
2010-11-09T05:42:06Z
[ "python", "frameworks", "pylons", "pyramid" ]
I've been developing in Pylons for a little while now and have recently learned they're merging with another framework to create Pyramid. I've been looking over [example code](https://github.com/Pylons/pyramid/tree/master/docs/tutorials/wiki2/src/basiclayout/tutorial) to see the differences and it's causing a bit of c...
Since the various view-related configuration methods (config.add\_view, config.add\_handler) require you to pass a dotted name as the class or function to be used as a view or handler, you can arrange your code however you like. For example, if your project package name were `myproject` and wanted to arrange all your ...
python matplotlib framework under macosx?
4,130,355
13
2010-11-09T03:49:40Z
34,583,958
7
2016-01-04T02:32:17Z
[ "python", "matplotlib", "fink" ]
I am getting this error: > /sw/lib/python2.7/site-packages/matplotlib/backends/backend\_macosx.py:235: > UserWarning: Python is not installed as a framework. The MacOSX > backend may not work correctly if Python is not installed as a > framework. Please see the Python documentation for more information on > installing...
Some users may not want to change the backend for all of their scripts. This page -- <http://matplotlib.org/faq/usage_faq.html#what-is-a-backend> -- tells another way: ``` import matplotlib matplotlib.use('TkAgg') ``` You have to do this before importing peplos.
Finding the most frequent character in a string
4,131,123
7
2010-11-09T06:43:13Z
4,131,173
13
2010-11-09T06:54:09Z
[ "python", "algorithm", "optimization", "time-complexity" ]
I found this programming problem while looking at a job posting on SO. I thought it was pretty interesting and as a beginner Python programmer I attempted to tackle it. However I feel my solution is quite...messy...can anyone make any suggestions to optimize it or make it cleaner? I know it's pretty trivial, but I had ...
There are many ways to do this shorter. For example, you can use the [`Counter`](http://docs.python.org/py3k/library/collections.html#counter-objects) class (in Python 2.7 or later): ``` import collections s = "helloworld" print(collections.Counter(s).most_common(1)[0]) ``` If you don't have that, you can do the tall...
boolean 'and' in Python
4,131,468
3
2010-11-09T07:53:10Z
4,131,477
7
2010-11-09T07:54:08Z
[ "python", "boolean" ]
Can somebody explain the reasoning behind the following tests ?? ``` >>> 1 and True True >>> {'foo': 'Foo'} and True True >>> {} and True {} >>> ```
Python doesn't *have* a boolean and or boolean or. Its `and` and `or` operators are **coalescing**, which means that they return the first non-true or true operand, or the second operand.
How upload folder by FTP using cURL?
4,131,782
7
2010-11-09T08:38:42Z
4,131,822
14
2010-11-09T08:44:02Z
[ "python", "curl", "ftp", "pycurl" ]
I need to create FTP-uploader, i am using pycurl and python, but i dont know how to make folder with cURL on ftp's host. Help me please.
You can use the curl option while uploading a file : --ftp-create-dirs * <http://curl.haxx.se/docs/manpage.html#--ftp-create-dirs> Ex: ``` curl --ftp-create-dirs -T uploadfilename -u username:password ftp://sitename.com/directory/myfile ```
HDF5 : storing NumPy data
4,133,327
2
2010-11-09T11:51:57Z
4,133,563
9
2010-11-09T12:22:06Z
[ "python", "c", "numpy", "hdf5", "pytables" ]
when I used NumPy I stored it's data in the native format \*.npy. It's very fast and gave me some benefits, like this one * I could read \*.npy from C code as simple binary data(I mean \*.npy are binary-compatibly with C structures) Now I'm dealing with HDF5 (PyTables at this moment). As I read in the tutorial, t...
The proper way to read hdf5 files from C is to use the hdf5 API - see this [tutorial](http://www.hdfgroup.org/HDF5/Tutor/). In principal it is possible to directly read the raw data from the hdf5 file as you would with the .npy file, assuming you have not used advanced storage options such as compression in your hdf5 f...
Python: pip installs sub-packages in root dir
4,134,209
4
2010-11-09T13:36:30Z
4,134,523
7
2010-11-09T14:08:03Z
[ "python", "setuptools", "distutils", "pip" ]
I have such structure: ``` setup.py package __init__.py sub_package ___init__.py sub_package2 __init__.py ``` If I install package via setup.py install, then it works as appreciated (by copying whole package to site-packages dir): ``` site_packages package sub_package ...
**NOTE: This answer is not valid anymore, it's only kept for historical reasons, the right answer right now is to use setuptools, more info <https://mail.python.org/pipermail/distutils-sig/2013-March/020126.html>** --- First of all i will recommend to drop setuptools : ![alt text](http://i.stack.imgur.com/5bfcQ.jpg)...
Is there any direct way to generate pdf from markdown file by python
4,135,344
18
2010-11-09T15:26:25Z
4,136,113
13
2010-11-09T16:37:48Z
[ "python", "pdf-generation", "markdown" ]
As the title, I want to use markdown as my main write format and I need to generate PDF files from markdown using pure python.
I have done and would do it in two steps. First, I'd use [python-markdown](https://pypi.python.org/pypi/Markdown) to make HTML out of my Markdown, and then I'd use [xhtml2pdf](https://github.com/xhtml2pdf/xhtml2pdf) to make a PDF file. **Edit (2014):** If I were doing this now, I might choose [WeasyPrint](http://weas...
Matplotlib/pyplot: How to enforce axis range?
4,136,244
35
2010-11-09T16:52:02Z
4,136,486
17
2010-11-09T17:17:29Z
[ "python", "graph", "matplotlib", "axes" ]
I would like to draw a standard 2D line graph with pylot, but force the axes' values to be between 0 and 600 on the x, and 10k and 20k on the y. Let me go with an example... ``` import pylab as p p.title(save_file) p.axis([0.0,600.0,1000000.0,2000000.0]) #define keys and items elsewhere.. p.plot(keys,items) p.savefi...
To answer my own question, the trick is to turn auto scaling off... ``` p.axis([0.0,600.0, 10000.0,20000.0]) ax = p.gca() ax.set_autoscale_on(False) ```
Matplotlib/pyplot: How to enforce axis range?
4,136,244
35
2010-11-09T16:52:02Z
4,136,571
26
2010-11-09T17:25:54Z
[ "python", "graph", "matplotlib", "axes" ]
I would like to draw a standard 2D line graph with pylot, but force the axes' values to be between 0 and 600 on the x, and 10k and 20k on the y. Let me go with an example... ``` import pylab as p p.title(save_file) p.axis([0.0,600.0,1000000.0,2000000.0]) #define keys and items elsewhere.. p.plot(keys,items) p.savefi...
Calling `p.plot` after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling `xlim()` or `ylim()` **after** your `plot` command. I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is ba...
Ctrl-c i.e. KeyboardInterrupt to kill threads in python
4,136,632
13
2010-11-09T17:30:52Z
8,864,601
10
2012-01-14T19:03:45Z
[ "python", "multithreading", "kill", "keyboardinterrupt" ]
I read somewhere that KeyboardInterrupt exception is only read by the main thread in Python. I also read that the main thread is blocked while the child thread executes. So, does this mean that Ctrl-c can never reach to the child thread. I tried the following code: ``` def main(): try: thread1.start() #thr...
If you want to have main thread to receive the ctrl+c signal while joining, it can be done by adding timeout to `join()` call. The following seems to be working (don't forget to add `daemon=True` if you want main to actually end): ``` thread1.start() while True: thread1.join(600) if not thread1.isAlive(): ...
Order of default and non-default arguments
4,137,770
12
2010-11-09T19:43:20Z
4,137,838
8
2010-11-09T19:50:35Z
[ "python", "argument-passing" ]
In Python, I understand that default arguments come at the end and that non-default arguments cannot follow a default argument. That is fine. Like for example: ``` >>> def foo(x=0, y): return x, y SyntaxError: non-default argument follows default argument ``` That is OK as expected. However, what about the c...
Well, `range` is C code which can do this slightly better. Anyways, you can do this: ``` def range(start, stop=None): if stop is None: # only one arg, treat stop as start ... stop = start start = 0 ... ``` and document the function accordingly.
Command-line options to IPython *scripts*?
4,138,145
26
2010-11-09T20:18:19Z
4,138,203
22
2010-11-09T20:23:36Z
[ "python", "ipython" ]
I am often asked to debug Python scripts written by others. I would like to send these scripts to IPython so it will drop into an IPython shell at the point the script fails. Unfortunately, I cannot find a way to send (required) command-line options required by the scripts. IPython assumes everything in is for IPytho...
``` ipython -i -c "%run test.py 1 2 3 4" ```
Command-line options to IPython *scripts*?
4,138,145
26
2010-11-09T20:18:19Z
5,344,347
36
2011-03-17T19:45:06Z
[ "python", "ipython" ]
I am often asked to debug Python scripts written by others. I would like to send these scripts to IPython so it will drop into an IPython shell at the point the script fails. Unfortunately, I cannot find a way to send (required) command-line options required by the scripts. IPython assumes everything in is for IPytho...
``` ipython -- sometest.py 1 2 3 4 ```
Python - Using isdigit for floats?
4,138,202
13
2010-11-09T20:23:29Z
4,138,231
19
2010-11-09T20:25:57Z
[ "python" ]
``` a = raw_input('How much is 1 share in that company? ') while not a.isdigit(): print "You need to write a number!\n" a = raw_input('How much is 1 share in that company? ') ``` This only works if the user enters an int, but I want it to work even if they enter a float, but not when they enter a str....
EAFP ``` try: x = float(a) except ValueError: print("You must enter a number") ```
Python - Using isdigit for floats?
4,138,202
13
2010-11-09T20:23:29Z
4,138,301
7
2010-11-09T20:33:25Z
[ "python" ]
``` a = raw_input('How much is 1 share in that company? ') while not a.isdigit(): print "You need to write a number!\n" a = raw_input('How much is 1 share in that company? ') ``` This only works if the user enters an int, but I want it to work even if they enter a float, but not when they enter a str....
Use regular expressions. ``` import re p = re.compile('\d+(\.\d+)?') a = raw_input('How much is 1 share in that company? ') while p.match(a) == None: print "You need to write a number!\n" a = raw_input('How much is 1 share in that company? ') ```
bind HTTServer to local ip:port so that others in LAN can see it?
4,139,170
2
2010-11-09T22:06:39Z
4,139,226
10
2010-11-09T22:14:10Z
[ "python", "networking" ]
I want to run simple HTTP server on LAN to test it, how can I bind my local ip to this server so that everyone in the same LAN can see it? ``` addr = ("192.168.10.14", 8765) srvr = HTTPServer(addr,RequestHandler) ``` I get this error : **error: [Errno 10049] The requested address is not valid in its context**
try this: ``` addr = ("0.0.0.0", 8765) ``` Here is what i did: ``` import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler addr = ("0.0.0.0", 8765) serv = BaseHTTPServer.HTTPServer(addr, SimpleHTTPRequestHandler) serv.serve_forever() ``` And got from an other machine: ``` 192.168.1.2 - - [09...
In Python can one implement mixin behavior without using inheritance?
4,139,508
4
2010-11-09T22:47:37Z
4,143,512
8
2010-11-10T10:35:09Z
[ "python", "ruby", "inheritance", "mixins" ]
Is there a reasonable way in Python to implement mixin behavior similar to that found in Ruby -- that is, without using inheritance? ``` class Mixin(object): def b(self): print "b()" def c(self): print "c()" class Foo(object): # Somehow mix in the behavior of the Mixin class, # so that all of the meth...
``` def mixer(*args): """Decorator for mixing mixins""" def inner(cls): for a,k in ((a,k) for a in args for k,v in vars(a).items() if callable(v)): setattr(cls, k, getattr(a, k).im_func) return cls return inner class Mixin(object): def b(self): print "b()" def c(self): p...
What is a simple way to extract the list of URLs on a webpage using python?
4,139,989
2
2010-11-10T00:02:21Z
4,140,102
7
2010-11-10T00:21:03Z
[ "python", "web-applications" ]
I want to create a simple web crawler for fun. I need the web crawler to get a list of all links on one page. Does the python library have any built in functions that would make this any easier? Thanks any knowledge appreciated.
This is actually very simple with [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). ``` from BeautifulSoup import BeautifulSoup [element['href'] for element in BeautifulSoup(document_contents).findAll('a', href=True)] # [u'http://example.com/', u'/example', ...] ``` One last thing: you can use [`urlpa...
defaultdict with a parameter to the class constructor
4,139,995
5
2010-11-10T00:03:00Z
4,140,021
13
2010-11-10T00:08:31Z
[ "python", "collections", "dictionary", "python-3.x" ]
[Python 3.1] I want `defaultdict(int)`, except I'd like the default value to be `1` rather than `0`. 1. Is there any neat way to do that? 2. Should I do that?
``` >>> def f(): return 1 >>> a = defaultdict(f) >>> a[1] 1 ``` Here is an other implementation using lambda expression (from **kindall**): ``` >>> a = defaultdict(lambda: 1) ```
Interactively validating Entry widget content in tkinter
4,140,437
34
2010-11-10T01:24:48Z
4,140,988
81
2010-11-10T03:29:01Z
[ "python", "validation", "textbox", "tkinter", "entry" ]
What is the recommended technique for interactively validating content in a tkinter `Entry` widget? I've read the posts about using `validate=True` and `validatecommand=command`, and it appears that these features are limited by the fact that they get cleared if the `validatecommand` command updates the `Entry` widget...
The correct answer is, use the `validatecommand` attribute of the widget. The problem is, this feature is severely under-documented in the Tkinter world (but quite sufficiently documented in the Tk world). Even though it's not documented well, it has everything you need to do validation without resorting to bindings or...
Why shouldn't I use async (evented) IO
4,140,656
9
2010-11-10T02:13:34Z
4,291,204
8
2010-11-27T10:37:00Z
[ "python", "asynchronous", "libevent", "gevent" ]
I am writing now writing some evented code (In python using gevent) and I use the nginx as a web server and I feel both are great. I was told that there is a trade off with events but was unable to see it. Can someone please shed some light? James
The only difficulty of evented programming is that you mustn't block, ever. This can be hard to achieve if you use some libraries that were designed with threads in mind. If you don't control these libraries, a fork() + message ipc is the way to go.
pyparsing, forward, and recursion
4,140,884
8
2010-11-10T03:07:55Z
4,141,064
8
2010-11-10T03:46:15Z
[ "python", "recursion", "forward", "pyparsing" ]
I'm using pyparsing to parse vcd (value change dump) files. Essentially, I want to read in the files, parse it into an internal dictionary, and manipulate the values. Without going into details on the structure, my problem occurs with identifying nested categories. In vcd files, you have 'scopes' which include wires ...
According to your definition, a scope cannot contain another scope, followed by some maps, followed by another scope. If the parser has a debug mode where it prints its parse tree, you will be able to see this immediately. But in short, you're saying there are zero or more maps, followed by zero or more scopes, follow...
What are the SCons alternatives?
4,141,511
6
2010-11-10T05:32:04Z
4,141,518
7
2010-11-10T05:33:41Z
[ "java", "c++", "python", "scons", "gyp" ]
I have projects in C++, Java and Python. Projects in C++ export SWIG interfaces so they can be used by Java and Python projects. My question is: what building mechanism can I use to manage dependencies and build these projects? I have used SCons and GYP. They are fairly easy to use and allow plugins (code-generators,...
One promising alternative is waf: * <http://code.google.com/p/waf/> Others: * <http://code.google.com/p/fabricate/> Not exactly but very relevant: * <http://www.buildout.org/docs/index.html>
What are the SCons alternatives?
4,141,511
6
2010-11-10T05:32:04Z
4,141,589
9
2010-11-10T05:47:40Z
[ "java", "c++", "python", "scons", "gyp" ]
I have projects in C++, Java and Python. Projects in C++ export SWIG interfaces so they can be used by Java and Python projects. My question is: what building mechanism can I use to manage dependencies and build these projects? I have used SCons and GYP. They are fairly easy to use and allow plugins (code-generators,...
### CMake I use and prefer it for my projects. There's also Rake (comes with Ruby, but can be used for anything), which I regard rather highly.
python: how to import the class within the same directory or sub directory
4,142,151
181
2010-11-10T07:32:23Z
4,142,178
284
2010-11-10T07:36:10Z
[ "python", "python-import" ]
I have a directory that stores all the **.py** files. ``` bin/ main.py user.py # where class User resides dir.py # where class Dir resides ``` I want to use classes from **user.py** and **dir.py** in **main.py**. How can I import these Python classes into **main.py**? Furthermore, how can I import class ...
# Python 2 Make an empty file called `__init__.py` in the same directory as the files. That will signify to Python that it's "ok to import from this directory". Then just do... ``` from user import User from dir import Dir ``` The same holds true if the files are in a subdirectory - put an `__init__.py` in the subd...
python: how to import the class within the same directory or sub directory
4,142,151
181
2010-11-10T07:32:23Z
4,142,197
15
2010-11-10T07:38:33Z
[ "python", "python-import" ]
I have a directory that stores all the **.py** files. ``` bin/ main.py user.py # where class User resides dir.py # where class Dir resides ``` I want to use classes from **user.py** and **dir.py** in **main.py**. How can I import these Python classes into **main.py**? Furthermore, how can I import class ...
In your `main.py`: ``` from user import Class ``` where `Class` is the name of the class you want to import. If you want to call a method of `Class`, you can call it using: `Class.method` Note that there should be an empty `__init__.py` file in the same directory.
python: how to import the class within the same directory or sub directory
4,142,151
181
2010-11-10T07:32:23Z
28,392,732
42
2015-02-08T10:07:43Z
[ "python", "python-import" ]
I have a directory that stores all the **.py** files. ``` bin/ main.py user.py # where class User resides dir.py # where class Dir resides ``` I want to use classes from **user.py** and **dir.py** in **main.py**. How can I import these Python classes into **main.py**? Furthermore, how can I import class ...
I just learned (thanks to [martineau's comment](http://stackoverflow.com/questions/4142151/python-how-to-import-the-class-within-the-same-directory-or-sub-directory#comment42933868_4142178)) that, in order to import classes from files within the same directory, you would now write in Python 3: ``` from .user import Us...
Why tuple is being used in string format
4,142,243
4
2010-11-10T07:46:47Z
4,142,306
14
2010-11-10T07:56:44Z
[ "python", "syntax" ]
I came across code like ``` print "Users connected: %d" % (userCount, ) ``` I was wondering, is there any reason of not writing them in ``` print "Users connected: %d" % userCount ``` They seem having the same output
The code without an explicid tuple may bite you if your variable contains a tuple. ``` >>> nums = (1, 2, 3, 4) >>> print "debug: %r" % (nums, ) debug: (1, 2, 3, 4) >>> print "debug: %r" % nums Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: not all arguments converted during string ...
How to do a scatter plot with empty circles in Python?
4,143,502
53
2010-11-10T10:34:09Z
4,146,321
27
2010-11-10T15:52:38Z
[ "python", "matplotlib", "circle", "scatter-plot", "scatter" ]
In Python, with Matplotlib, how can a scatter plot with *empty* circles be plotted? The goal is to draw empty circles around *some* of the colored disks already plotted by `scatter()`, so as to highlight them, ideally without having to redraw the colored circles.
Would these work? ``` plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none') ``` ![example image](http://i.stack.imgur.com/fVrxE.png) or using plot() ``` plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none') ``` ![example image](http://i.stack.imgur.com/FbOQu.png)
How to do a scatter plot with empty circles in Python?
4,143,502
53
2010-11-10T10:34:09Z
4,146,439
72
2010-11-10T16:07:16Z
[ "python", "matplotlib", "circle", "scatter-plot", "scatter" ]
In Python, with Matplotlib, how can a scatter plot with *empty* circles be plotted? The goal is to draw empty circles around *some* of the colored disks already plotted by `scatter()`, so as to highlight them, ideally without having to redraw the colored circles.
From the [documentation](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.scatter) for scatter: ``` Optional kwargs control the Collection properties; in particular: edgecolors: The string ‘none’ to plot faces with no outlines facecolors: The string ‘none’ to plo...
How to do a scatter plot with empty circles in Python?
4,143,502
53
2010-11-10T10:34:09Z
4,255,944
7
2010-11-23T12:20:06Z
[ "python", "matplotlib", "circle", "scatter-plot", "scatter" ]
In Python, with Matplotlib, how can a scatter plot with *empty* circles be plotted? The goal is to draw empty circles around *some* of the colored disks already plotted by `scatter()`, so as to highlight them, ideally without having to redraw the colored circles.
Here's another way: this adds a circle to the current axes, plot or image or whatever : ``` from matplotlib.patches import Circle # $matplotlib/patches.py def circle( xy, radius, color="lightsteelblue", facecolor="none", alpha=1, ax=None ): """ add a circle to ax= or current axes """ # from .../pylab...
Python: split by (different) n spaces
4,143,531
2
2010-11-10T10:37:10Z
4,143,577
7
2010-11-10T10:41:16Z
[ "python", "split" ]
I have lines like this: ``` 2 20 164 "guid" Some name^7 0 ip.a.dd.res:port -21630 25000 6 30 139 "guid" Other name^7 0 ip.a.dd.res:port 932 25000 ``` I would like to split this, but the problem is that there is different number of spaces between this "words"... How can...
Python's split function doesn't care about the number of spaces: ``` >>> ' 2 20 164 "guid" Some name^7 0 ip.a.dd.res:port -21630 25000'.split() ['2', '20', '164', '"guid"', 'Some', 'name^7', '0', 'ip.a.dd.res:port', '-21630', '25000'] ```
Python and MySQLdb - Using DROP TABLE IF EXISTS seems to throw exception
4,143,686
6
2010-11-10T10:54:26Z
4,830,497
20
2011-01-28T16:16:51Z
[ "python", "mysql" ]
I got this code.. ``` ..... try: task_db.cursor.execute('DROP TABLE IF EXISTS `tasks`') print "Affected: %d" % task_db.cursor.rowcount except MySQLdb.Error, e: print "Error ocurred: %s " % e.args[0] print e ``` If the tasks table doesn't exist, then I get a warning like ``` create_database.py:11: Wa...
Catching the MySQLdb.Warning didn't work for me, so I found another way to suppress warnings: ``` import warnings warnings.filterwarnings("ignore", "Unknown table.*") ``` And you can edit the second parameter with whatever you want to suppress.
Python and MySQLdb - Using DROP TABLE IF EXISTS seems to throw exception
4,143,686
6
2010-11-10T10:54:26Z
18,276,232
7
2013-08-16T14:54:36Z
[ "python", "mysql" ]
I got this code.. ``` ..... try: task_db.cursor.execute('DROP TABLE IF EXISTS `tasks`') print "Affected: %d" % task_db.cursor.rowcount except MySQLdb.Error, e: print "Error ocurred: %s " % e.args[0] print e ``` If the tasks table doesn't exist, then I get a warning like ``` create_database.py:11: Wa...
The most elegant way to avoid Mysql warnings : ``` from warnings import filterwarnings import MySQLdb filterwarnings('ignore', category = MySQLdb.Warning) ```
Create or append to a list in a dictionary - can this be shortened?
4,143,698
19
2010-11-10T10:55:10Z
4,143,719
20
2010-11-10T10:57:27Z
[ "python", "dictionary" ]
Can this Python code be shortened and still be readable using itertools and sets? ``` result = {} for widget_type, app in widgets: if widget_type not in result: result[widget_type] = [] result[widget_type].append(app) ``` I can think of this only: ``` widget_types = zip(*widgets)[0] dict([k, [v for w...
You can use a `defaultdict(list)`. ``` from collections import defaultdict result = defaultdict(list) for widget_type, app in widgets: result[widget_type].append(app) ```
Create or append to a list in a dictionary - can this be shortened?
4,143,698
19
2010-11-10T10:55:10Z
4,143,837
48
2010-11-10T11:12:40Z
[ "python", "dictionary" ]
Can this Python code be shortened and still be readable using itertools and sets? ``` result = {} for widget_type, app in widgets: if widget_type not in result: result[widget_type] = [] result[widget_type].append(app) ``` I can think of this only: ``` widget_types = zip(*widgets)[0] dict([k, [v for w...
An alternative to `defaultdict` is to use the `setdefault` method of standard dictionaries: ``` result = {} for widget_type, app in widgets: result.setdefault(widget_type, []).append(app) ``` This relies on the fact that lists are mutable, so what is returned from setdefault is the same list as the one in the ...
Django Admin - Disable the 'Add' action for a specific model
4,143,886
84
2010-11-10T11:18:03Z
4,144,088
191
2010-11-10T11:41:41Z
[ "python", "django", "django-admin" ]
I have a django site with lots of models and forms. I have many custom forms and formsets and inlineformsets and custom validation and custom querysets. Hence the add model action depends on forms that need other things, and the 'add model' in the django admin throughs a 500 from a custom queryset. Is there anyway to ...
It is easy, just overload has\_add\_permission method in your Admin class like so: ``` class MyAdmin(admin.ModelAdmin): def has_add_permission(self, request): return False ```
ImportError: No module named pythoncom
4,145,079
8
2010-11-10T13:44:14Z
4,145,183
11
2010-11-10T13:54:32Z
[ "python", "django-mssql" ]
I am a newbie (just 1 week) to this Python world. I tried installing django-mssql, but when I tried to import the library (using `import sqlserver_ado.dbapi`), I got this error message: ``` ImportError: No module named pythoncom ``` I tried to look for that library without success. Can you guys point me in the right...
You are missing the `pythoncom` package. It comes with [ActivePython](http://www.activestate.com/activepython) but you can get it separately on [SourceForge](https://sourceforge.net/projects/pywin32/files/) as part of pywin32.
Using a regular expression to replace upper case repeated letters in python with a single lowercase letter
4,145,451
19
2010-11-10T14:21:46Z
4,145,486
32
2010-11-10T14:27:49Z
[ "python", "regex", "capitalization" ]
I am trying to replace any instances of uppercase letters that repeat themselves twice in a string with a single instance of that letter in a lower case. I am using the following regular expression and it is able to match the repeated upper case letters, but I am unsure as how to make the letter that is being replaced ...
[Pass a function](http://docs.python.org/library/re.html#re.sub) as the `repl` argument. The [`MatchObject`](http://docs.python.org/library/re.html#match-objects) is passed to this function and `.group(1)` gives the first parenthesized subgroup: ``` import re s = 'start TT end' callback = lambda pat: pat.group(1).lowe...
How do I convert a Python list into a C array by using ctypes?
4,145,775
24
2010-11-10T14:58:13Z
4,145,859
47
2010-11-10T15:08:32Z
[ "python", "c", "ctypes" ]
If I have the follow 2 sets of code, how do I glue them together? ``` void c_function(void *ptr) { int i; for (i = 0; i < 10; i++) { printf("%p", ptr[i]); } return; } def python_routine(y): x = [] for e in y: x.append(e) ``` How can I call the c\_function with a contiguous ...
The following code works on arbitrary lists: ``` import ctypes arr = (ctypes.c_int * len(pyarr))(*pyarr) ```
Python: get list indexes using regular expression?
4,146,009
19
2010-11-10T15:26:02Z
4,146,052
21
2010-11-10T15:29:22Z
[ "python" ]
In Python, how do you get the position of an item in a list (using `list.index`) using fuzzy matching? For example, how do I get the indexes of all fruit of the form `*berry` in the following list? ``` fruit_list = ['raspberry', 'apple', 'strawberry'] # Is it possible to do something like the following? berry_fruit_a...
Try: ``` fruit_list = ['raspberry', 'apple', 'strawberry'] [ i for i, word in enumerate(fruit_list) if word.endswith('berry') ] ``` returns: ``` [0, 2] ``` Replace `endswith` with a different logic according to your matching needs.
Python: get list indexes using regular expression?
4,146,009
19
2010-11-10T15:26:02Z
4,146,090
26
2010-11-10T15:33:05Z
[ "python" ]
In Python, how do you get the position of an item in a list (using `list.index`) using fuzzy matching? For example, how do I get the indexes of all fruit of the form `*berry` in the following list? ``` fruit_list = ['raspberry', 'apple', 'strawberry'] # Is it possible to do something like the following? berry_fruit_a...
With regular expressions: ``` import re fruit_list = ['raspberry', 'apple', 'strawberry'] berry_idx = [i for i, item in enumerate(fruit_list) if re.search('berry$', item)] ``` And without regular expressions: ``` fruit_list = ['raspberry', 'apple', 'strawberry'] berry_idx = [i for i, item in enumerate(fruit_list) if...
best way to python table?
4,146,254
3
2010-11-10T15:47:08Z
4,146,316
13
2010-11-10T15:52:19Z
[ "python", "database", "table" ]
Any thoughts on the best way to implement a table (i.e. a small relational database) in python without using any external databases extra modules and **when the sqlite3 module is broken or missing**. ``` user:~ $ python3 >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File...
Use [`sqlite3`](http://docs.python.org/library/sqlite3.html). * It comes with python, you don't need external databases or extra modules. * It can create the whole database on memory. You don't need extra files on disk if you don't want to. * It's lightning fast. * It can do modern queries on the tables, like ...
IRC client in python
4,147,457
3
2010-11-10T17:54:11Z
10,057,399
7
2012-04-07T18:59:28Z
[ "python", "irc" ]
I'm writing python code for IRC client. I want to understand how IRC client and server communicating each other. Can anyone give me good tutorial or IRC communication architecture to understand it in depth? Thanks
The IRC RFC documentation is an important reference, but the most helpful first introduction I've found on communication between IRC client and server was really simple. First, you need access to a \*nix shell (e.g. ssh into your web host running Linux). In the command line, open up a direct connection to an IRC serv...
Python - mysqlDB, sqlite result as dictionary
4,147,707
13
2010-11-10T18:23:21Z
4,236,960
10
2010-11-21T08:01:01Z
[ "python", "mysql", "sqlite", "dictionary" ]
When I do someting like ``` sqlite.cursor.execute("SELECT * FROM foo") result = sqlite.cursor.fetchone() ``` I think have to remember the order the columns appear to be able to fetch them out, eg ``` result[0] is id result[1] is first_name ``` is there a way to return a dictionary? so I can instead just use result[...
Doing this in mysqlDB you just add the following to the connect function call ``` cursorclass = MySQLdb.cursors.DictCursor ```
Python - mysqlDB, sqlite result as dictionary
4,147,707
13
2010-11-10T18:23:21Z
15,423,453
21
2013-03-15T01:57:17Z
[ "python", "mysql", "sqlite", "dictionary" ]
When I do someting like ``` sqlite.cursor.execute("SELECT * FROM foo") result = sqlite.cursor.fetchone() ``` I think have to remember the order the columns appear to be able to fetch them out, eg ``` result[0] is id result[1] is first_name ``` is there a way to return a dictionary? so I can instead just use result[...
``` import MySQLdb dbConn = MySQLdb.connect(host='xyz', user='xyz', passwd='xyz', db='xyz') dictCursor = dbConn.cursor(MySQLdb.cursors.DictCursor) dictCursor.execute("SELECT a,b,c FROM table_xyz") resultSet = dictCursor.fetchall() for row in resultSet: print row['a'] dictCursor.close dbConn.close() ```
python bytecode, the interpreter and virtual machine
4,147,928
4
2010-11-10T18:50:46Z
4,147,941
9
2010-11-10T18:52:25Z
[ "python", "operating-system", "bytecode", "vm-implementation" ]
This is a really vast question and I'm mostly looking for resources where I can learn more about the following. I know the python interpreter is written in C and produces bytecode to be run on the python virtual machine also written in C (right?). My question is would it be possible to implement both of these in pytho...
Compiler, not interpreter. But you're looking for [PyPy](http://pypy.org/).
How do I select a window from a numpy array with periodic boundary conditions?
4,148,292
9
2010-11-10T19:30:18Z
4,148,440
12
2010-11-10T19:48:54Z
[ "python", "numpy" ]
Suppose I make a 2d array like this: ``` >>> A=np.arange(16).reshape((4,4)) >>> A array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) ``` and I want to be able to select a 3x3 window around any given element so that the window wraps around the boundaries how would I do...
``` import numpy as np A=np.arange(16).reshape((4,4)) def neighbors(arr,x,y,n=3): ''' Given a 2D-array, returns an nxn array whose "center" element is arr[x,y]''' arr=np.roll(np.roll(arr,shift=-x+1,axis=0),shift=-y+1,axis=1) return arr[:n,:n] print(A) # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11] # ...
Overwriting a specific row in a csv file using Python's CSV module
4,148,772
3
2010-11-10T20:30:23Z
4,148,985
7
2010-11-10T20:53:59Z
[ "python", "csv" ]
I'm using Python's csv module to do some reading and writing of csv files. I've got the reading fine and appending to the csv fine, but I want to be able to overwrite a specific row in the csv. For reference, here's my reading and then writing code to append: ``` #reading b = open("bottles.csv", "rb") bo...
I will add to [Steven](http://stackoverflow.com/questions/4148772/overwriting-a-specific-row-in-a-csv-file-using-pythons-csv-module/4148813#4148813) Answer : ``` import csv bottle_list = [] # Read all data from the csv file. with open('a.csv', 'rb') as b: bottles = csv.reader(b) bottle_list.extend(bottles) ...
Lazy logger message string evaluation
4,148,790
39
2010-11-10T20:33:31Z
4,149,190
14
2010-11-10T21:20:22Z
[ "python", "logging" ]
I'm using standard python logging module in my python application: ``` import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("log") while True: logger.debug('Stupid log message " + ' '.join([str(i) for i in range(20)]) ) # Do something ``` The issue is that although debug level is not ...
``` import logging import time logging.basicConfig(level=logging.INFO) logger = logging.getLogger("log") class Lazy(object): def __init__(self,func): self.func=func def __str__(self): return self.func() logger.debug(Lazy(lambda: time.sleep(20))) logger.info(Lazy(lambda: "Stupid log message "...
Lazy logger message string evaluation
4,148,790
39
2010-11-10T20:33:31Z
4,149,231
56
2010-11-10T21:25:35Z
[ "python", "logging" ]
I'm using standard python logging module in my python application: ``` import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("log") while True: logger.debug('Stupid log message " + ' '.join([str(i) for i in range(20)]) ) # Do something ``` The issue is that although debug level is not ...
The logging module already has partial support for what you want to do. Do this: ``` log.debug("Some message: a=%s b=%s", a, b) ``` ... instead of this: ``` log.debug("Some message: a=%s b=%s" % (a, b)) ``` The logging module is smart enough to not produce the complete log message unless the message actually gets l...
Lazy logger message string evaluation
4,148,790
39
2010-11-10T20:33:31Z
14,725,112
7
2013-02-06T09:02:10Z
[ "python", "logging" ]
I'm using standard python logging module in my python application: ``` import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("log") while True: logger.debug('Stupid log message " + ' '.join([str(i) for i in range(20)]) ) # Do something ``` The issue is that although debug level is not ...
As Shane points out, using ``` log.debug("Some message: a=%s b=%s", a, b) ``` ... instead of this: ``` log.debug("Some message: a=%s b=%s" % (a, b)) ``` saves some time by only performing the string formatting if the message is actually logged. This does not completely solve the problem, though, as you may have to...
Lazy logger message string evaluation
4,148,790
39
2010-11-10T20:33:31Z
22,205,835
18
2014-03-05T18:13:28Z
[ "python", "logging" ]
I'm using standard python logging module in my python application: ``` import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("log") while True: logger.debug('Stupid log message " + ' '.join([str(i) for i in range(20)]) ) # Do something ``` The issue is that although debug level is not ...
Of course the following is not as efficient as a Macro: ``` if logger.isEnabledFor(logging.DEBUG): logger.debug( 'Stupid log message ' + ' '.join([str(i) for i in range(20)]) ) ``` but simple, [evaluates in lazy fashion](https://en.wikipedia.org/wiki/Lazy_evaluation) and is **4 times faster than the a...
Is this a bug in Python 2.7?
4,148,974
4
2010-11-10T20:52:40Z
4,148,996
12
2010-11-10T20:54:50Z
[ "python", "string" ]
Trying to strip the "0b1" from the left end of a binary number. The following code results in stripping all of binary object. (not good) ``` >>> bbn = '0b1000101110100010111010001' #converted bin(2**24+**2^24/11) >>> aan=bbn.lstrip("0b1") #Try stripping all left-end junk at once. >>> print aan #oops all gone. '' ...
No. Stripping removes all characters in the sequence passed, not just the literal sequence. Slice the string if you want to remove a fixed length.
Is this a bug in Python 2.7?
4,148,974
4
2010-11-10T20:52:40Z
4,149,008
13
2010-11-10T20:57:03Z
[ "python", "string" ]
Trying to strip the "0b1" from the left end of a binary number. The following code results in stripping all of binary object. (not good) ``` >>> bbn = '0b1000101110100010111010001' #converted bin(2**24+**2^24/11) >>> aan=bbn.lstrip("0b1") #Try stripping all left-end junk at once. >>> print aan #oops all gone. '' ...
The strip family treat the arg as a **set** of characters to be removed. The default set is "all whitespace characters". You want: ``` if strg.startswith("0b1"): strg = strg[3:] ```
Python-style pickling for C++?
4,149,086
9
2010-11-10T21:07:54Z
4,149,141
7
2010-11-10T21:13:49Z
[ "c++", "python", "serialization", "boost", "pickle" ]
Does anyone know of a "language level" facility for pickling in C++? I don't want something like Boost serialization, or Google Protocol Buffers. Instead, something that could automatically serialize all the members of a class (with an option to exclude some members, either because they're not serializable, or else bec...
I don't believe there's any way to do this in a language with no run-time introspection capabilities.
On linux SUSE or RedHat, how do I load Python 2.7
4,149,361
55
2010-11-10T21:41:36Z
4,149,444
114
2010-11-10T21:50:22Z
[ "python", "linux", "rhel", "suse" ]
Can someone provide the steps needed to install python version 2.7 on SUSE and RedHat? It version that is on there is like 2.4 and I need to have it at at least 2.6 to make my script work. So after the install, I can type Python in a xTerm and get the Python 2.7 command line interface.
<http://www.python.org/download/> <http://diveintopython.net/installing_python/source.html> Download source and install from source. NOTE: You should check for the latest version of python 2.7.x. (Originally had `wget http://www.python.org/ftp/python/2.7/Python-2.7.tgz`), while now the latest version is 2.7.3 ``` w...
On linux SUSE or RedHat, how do I load Python 2.7
4,149,361
55
2010-11-10T21:41:36Z
11,738,128
7
2012-07-31T10:31:35Z
[ "python", "linux", "rhel", "suse" ]
Can someone provide the steps needed to install python version 2.7 on SUSE and RedHat? It version that is on there is like 2.4 and I need to have it at at least 2.6 to make my script work. So after the install, I can type Python in a xTerm and get the Python 2.7 command line interface.
The accepted answer by dr jimbob (using `make altinstall`) got me most of the way there, with `python2.7` in `/usr/local/bin` but I also needed to install some third party modules. The nice thing is that easy\_install gets its installation locations from the version of Python you are running, but I found I still needed...
On linux SUSE or RedHat, how do I load Python 2.7
4,149,361
55
2010-11-10T21:41:36Z
16,774,391
11
2013-05-27T13:31:46Z
[ "python", "linux", "rhel", "suse" ]
Can someone provide the steps needed to install python version 2.7 on SUSE and RedHat? It version that is on there is like 2.4 and I need to have it at at least 2.6 to make my script work. So after the install, I can type Python in a xTerm and get the Python 2.7 command line interface.
RHEL 6.2 using. Which is having Python 2.6, i need Python 2.7.3. So: ``` $ sudo sh -c 'wget -qO- http://people.redhat.com/bkabrda/scl_python27.repo >> /etc/yum.repos.d/scl.repo' $ yum search python27 Loaded plugins: amazon-id, rhui-lb, security scl_python27 ...
logging hierarchy vs. root logger?
4,150,148
12
2010-11-10T23:33:32Z
4,150,236
7
2010-11-10T23:53:09Z
[ "python", "logging" ]
Somewhere in the bowels of my code I have something like: ``` logger = logging.getLogger('debug0.x') ``` The way I understand it, this should **only** respond when I have previously done something like: ``` logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG, name='debug0') ``` note that **name** has ...
If you check out the code or the doc: ``` >>> print logging.basicConfig.__doc__ Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. ............... A number of optional keyword arguments may be specified, which can alter th...
logging hierarchy vs. root logger?
4,150,148
12
2010-11-10T23:33:32Z
4,150,322
40
2010-11-11T00:07:19Z
[ "python", "logging" ]
Somewhere in the bowels of my code I have something like: ``` logger = logging.getLogger('debug0.x') ``` The way I understand it, this should **only** respond when I have previously done something like: ``` logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG, name='debug0') ``` note that **name** has ...
The Python `logging` module organises logger in a hierarchy. All loggers are descendants of the root logger. Each logger passes log messages on to its parent. New loggers are created with the `getLogger()` function. The function call `logging.getLogger('debug0.x')` creates a logger `x` which is a child of `debug0` whi...
How to create a density plot in matplotlib?
4,150,171
68
2010-11-10T23:39:59Z
4,150,486
27
2010-11-11T00:40:13Z
[ "python", "numpy", "matplotlib", "scipy" ]
In R I can create the desired output by doing: ``` data = c(rep(1.5, 7), rep(2.5, 2), rep(3.5, 8), rep(4.5, 3), rep(5.5, 1), rep(6.5, 8)) plot(density(data, bw=0.5)) ``` ![Density plot in R](http://i.stack.imgur.com/YFEin.png) In python (with matplotlib) the closest I got was with a simple histogram: ``` i...
Maybe try something like: ``` import matplotlib.pyplot as plt import numpy from scipy import stats data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 density = stats.kde.gaussian_kde(data) x = numpy.arange(0., 8, .1) plt.plot(x, density(x)) plt.show() ``` You can easily replace `gaussian_kde()` by a dif...
How to create a density plot in matplotlib?
4,150,171
68
2010-11-10T23:39:59Z
4,152,016
76
2010-11-11T06:49:04Z
[ "python", "numpy", "matplotlib", "scipy" ]
In R I can create the desired output by doing: ``` data = c(rep(1.5, 7), rep(2.5, 2), rep(3.5, 8), rep(4.5, 3), rep(5.5, 1), rep(6.5, 8)) plot(density(data, bw=0.5)) ``` ![Density plot in R](http://i.stack.imgur.com/YFEin.png) In python (with matplotlib) the closest I got was with a simple histogram: ``` i...
Sven has shown how to use the class `gaussian_kde` from Scipy, but you will notice that it doesn't look quite like what you generated with R. This is because `gaussian_kde` tries to infer the bandwidth automatically. You can play with the bandwidth in a way by changing the function `covariance_factor` of the `gaussian_...
How to create a density plot in matplotlib?
4,150,171
68
2010-11-10T23:39:59Z
32,803,224
36
2015-09-26T23:57:03Z
[ "python", "numpy", "matplotlib", "scipy" ]
In R I can create the desired output by doing: ``` data = c(rep(1.5, 7), rep(2.5, 2), rep(3.5, 8), rep(4.5, 3), rep(5.5, 1), rep(6.5, 8)) plot(density(data, bw=0.5)) ``` ![Density plot in R](http://i.stack.imgur.com/YFEin.png) In python (with matplotlib) the closest I got was with a simple histogram: ``` i...
Five years later, when I Google "how to create a kernel density plot using python", this thread still shows up at the top! Today, a much easier way to do this is to use [seaborn](http://stanford.edu/~mwaskom/software/seaborn/), a package that provides many convenient plotting functions and good style management. ``` ...
How to create a density plot in matplotlib?
4,150,171
68
2010-11-10T23:39:59Z
33,474,410
8
2015-11-02T09:28:05Z
[ "python", "numpy", "matplotlib", "scipy" ]
In R I can create the desired output by doing: ``` data = c(rep(1.5, 7), rep(2.5, 2), rep(3.5, 8), rep(4.5, 3), rep(5.5, 1), rep(6.5, 8)) plot(density(data, bw=0.5)) ``` ![Density plot in R](http://i.stack.imgur.com/YFEin.png) In python (with matplotlib) the closest I got was with a simple histogram: ``` i...
**Option 1:** Use `pandas` dataframe plot (built on top of `matplotlib`): ``` import pandas as pd data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 df = pd.DataFrame(data) df.plot(kind='density') ``` [![enter image description here](http://i.stack.imgur.com/dNjzz.png)](http://i.stack.imgur.com/dNjzz.p...
Can Pip install dependencies not specified in setup.py at install time?
4,150,423
20
2010-11-11T00:28:48Z
4,483,029
35
2010-12-19T12:56:55Z
[ "python", "setuptools", "pip" ]
Hi all I'd like pip to install a dependency that I have on GitHub when the user issues the command to install the original software, also from source on GitHub. Neither of these packages are on PyPi (and never will be). The user issues the command: ``` pip -e git+https://github.com/Lewisham/cvsanaly@develop#egg=cvsan...
[This answer](http://stackoverflow.com/questions/3472430/how-can-i-make-setuptools-install-a-package-thats-not-on-pypi/3472494#3472494) helped me solve the same problem you're talking about. There doesn't seem to be an easy way for setup.py to use the requirements file directly to define its dependencies, but the same...
Can Pip install dependencies not specified in setup.py at install time?
4,150,423
20
2010-11-11T00:28:48Z
9,125,399
11
2012-02-03T07:55:32Z
[ "python", "setuptools", "pip" ]
Hi all I'd like pip to install a dependency that I have on GitHub when the user issues the command to install the original software, also from source on GitHub. Neither of these packages are on PyPi (and never will be). The user issues the command: ``` pip -e git+https://github.com/Lewisham/cvsanaly@develop#egg=cvsan...
Here's a small script I used to generate `install_requires` and `dependency_links` from a requirements file. ``` import os import re def which(program): """ Detect whether or not a program is installed. Thanks to http://stackoverflow.com/a/377028/70191 """ def is_exe(fpath): return os.path...
Python: Nesting counters
4,150,467
6
2010-11-11T00:36:41Z
4,150,483
7
2010-11-11T00:39:50Z
[ "python", "iteration" ]
For my customers, iterating through multiple counters is turning into a recurring task. The most straightforward way would be something like this: ``` cntr1 = range(0,2) cntr2 = range(0,5) cntr3 = range(0,7) for li in cntr1: for lj in cntr2: for lk in cntr3: print li, lj, lk ``` The number o...
What you want is `itertools.product` ``` for li, lj, lk in itertools.product(cntr1, cntr2, cntr3): print li, lj, lk ``` Will do exactly what you are requesting. The name derives from the concept of a Cartesian product.
Unable to connect to SQL Server via pymssql
4,150,524
7
2010-11-11T00:47:26Z
4,159,760
10
2010-11-11T22:10:52Z
[ "python", "pymssql" ]
I am attempting to connect to SQL Server running on Windows XP system from a \*nix system on a local server via pymssql. However, the connection fails as shown below ``` db = pymssql.connect(host='192.168.1.102',user='www',password='test',database='TestDB') Traceback (most recent call last): File "<stdin>", line 1, i...
Got it! I think the source of the problem was not giving Free TDS the attention it needs. Free TDS is apparently the driver behind pymssql and provides for connectivity to other databases - SQL Server being one of them. The freetds.conf file is located in /usr/local/etc on my system (Mac Book Pro). This file contains...
Determine Index of Highest Value in Python's NumPy
4,150,542
11
2010-11-11T00:52:13Z
4,150,557
19
2010-11-11T00:57:16Z
[ "python", "numpy" ]
I want to generate an array with the index of the highest max value of each row. ``` a = np.array([ [1,2,3], [6,5,4], [0,1,0] ]) maxIndexArray = getMaxIndexOnEachRow(a) print maxIndexArray [[2], [0], [1]] ``` There's a np.argmax function but it doesn't appear to do what I want...
The `argmax()` function *does* do what you want: ``` print a.argmax(axis=1) array([2, 0, 1]) ```
Python: how to set virtualenv for a crontab?
4,150,671
50
2010-11-11T01:22:26Z
4,150,693
54
2010-11-11T01:28:18Z
[ "python", "cron", "virtualenv", "crontab", "virtualenvwrapper" ]
I want to set up a crontab to run a Python script. Say the script is something like: ``` #!/usr/bin/python print "hello world" ``` Is there a way I could specify a virtualenv for that Python script to run in? In shell I'd just do: ``` ~$ workon myenv ``` Is there something equivalent I could do in crontab to activ...
If you're using "workon" you're actually using "virtualenv wrapper" which is another layer of abstraction that sits on top of virtualenv. virtualenv alone can be activated by cd'ing to your virtualenv root directory and running: ``` source bin/activate ``` workon is a command provided by virtualenv wrapper, not virtu...
Python: how to set virtualenv for a crontab?
4,150,671
50
2010-11-11T01:22:26Z
12,848,443
65
2012-10-11T21:00:20Z
[ "python", "cron", "virtualenv", "crontab", "virtualenvwrapper" ]
I want to set up a crontab to run a Python script. Say the script is something like: ``` #!/usr/bin/python print "hello world" ``` Is there a way I could specify a virtualenv for that Python script to run in? In shell I'd just do: ``` ~$ workon myenv ``` Is there something equivalent I could do in crontab to activ...
Another solution that works well for me... ``` 0 9 * * * /path/to/virtenv/bin/python /path/to/cron_script.py ``` I prefer using python directly from the virtualenv...
Python: how to set virtualenv for a crontab?
4,150,671
50
2010-11-11T01:22:26Z
30,222,231
7
2015-05-13T18:04:38Z
[ "python", "cron", "virtualenv", "crontab", "virtualenvwrapper" ]
I want to set up a crontab to run a Python script. Say the script is something like: ``` #!/usr/bin/python print "hello world" ``` Is there a way I could specify a virtualenv for that Python script to run in? In shell I'd just do: ``` ~$ workon myenv ``` Is there something equivalent I could do in crontab to activ...
With bash, you can create a generic virtual env wrapper that you can use to invoke ***any*** command, much like how [`time`](http://linux.about.com/library/cmd/blcmdl1_time.htm) can wrapper any command. # `virt_env_wrapper.bash`: ``` #!/bin/bash source path/to/virtual/env/bin/activate "$@" ``` Bash's magical inc...
Pythonic way to rewrite the following C++ string processing code
4,150,832
2
2010-11-11T02:01:53Z
4,150,857
7
2010-11-11T02:08:07Z
[ "c++", "python" ]
Previous, I am having a C++ string processing code which is able to do this. ``` input -> Hello 12 output-> Hello input -> Hello 12 World output-> Hello World input -> Hello12 World output-> Hello World input -> Hello12World output-> HelloWorld ``` The following is the C++ code. ``` std::string Utils::toStringWit...
Edit: This reproduces more accurately what the C++ code does than the previous version. ``` s = re.sub(r"\d+", "", s) s = re.sub(r"(\s)\s*", "\1", s) ``` In particular, if the first whitespace in a run of several whitespaces is a tab, it will preserve the tab. Further Edit: To replace by a space anyway, this works: ...
What are the differences between numpy arrays and matrices? Which one should I use?
4,151,128
160
2010-11-11T03:25:09Z
4,151,251
175
2010-11-11T03:59:03Z
[ "python", "arrays", "matrix", "numpy" ]
What are the advantages and disadvantages of each? From what I've seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of them? Will the style of the program influence my choice? I am doing some machine learning using numpy, so there are inde...
Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays. The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if a and b are mat...
What are the differences between numpy arrays and matrices? Which one should I use?
4,151,128
160
2010-11-11T03:25:09Z
4,159,142
19
2010-11-11T20:49:23Z
[ "python", "arrays", "matrix", "numpy" ]
What are the advantages and disadvantages of each? From what I've seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of them? Will the style of the program influence my choice? I am doing some machine learning using numpy, so there are inde...
Just to add one case to unutbu's list. One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less. For...
What are the differences between numpy arrays and matrices? Which one should I use?
4,151,128
160
2010-11-11T03:25:09Z
15,406,440
46
2013-03-14T10:16:04Z
[ "python", "arrays", "matrix", "numpy" ]
What are the advantages and disadvantages of each? From what I've seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of them? Will the style of the program influence my choice? I am doing some machine learning using numpy, so there are inde...
[Scipy.org recommends that you use arrays:](http://www.scipy.org/NumPy_for_Matlab_Users#head-e9a492daa18afcd86e84e07cd2824a9b1b651935) > **\*'array' or 'matrix'? Which should I use? - Short answer** > > Use arrays. > > * They are the standard vector/matrix/tensor type of numpy. Many numpy function return arrays, not m...
efficient circular buffer?
4,151,320
54
2010-11-11T04:17:18Z
4,151,368
101
2010-11-11T04:29:13Z
[ "python", "circular-buffer" ]
I want to create an efficient [circular buffer](http://en.wikipedia.org/wiki/Circular_buffer) in python (with the goal of taking averages of the integer values in the buffer). Is this an efficient way to use a list to collect values? ``` def add_to_buffer( self, num ): self.mylist.pop( 0 ) self.mylist.append(...
I would use [`collections.deque`](http://docs.python.org/library/collections.html#collections.deque) with a `maxlen` arg ``` >>> import collections >>> d = collections.deque(maxlen=10) >>> d deque([], maxlen=10) >>> for i in xrange(20): ... d.append(i) ... >>> d deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], max...
PyQT4: Drag and drop files into QListWidget
4,151,637
11
2010-11-11T05:36:12Z
4,176,083
13
2010-11-14T03:35:03Z
[ "python", "drag-and-drop", "pyqt" ]
I've been coding a OCR book scanning thing (it renames pages by reading the page number), and have switched to a GUI from my basic CLI Python script. I'm using PyQT4 and looked at a ton of documents on drag and drop, but no luck. It just refuses to take those files! I was using these to articles for my UI design: 1. ...
The code you're using as an example seem to work fine and looks quite clean. According to your comment your list widget is not getting initialized; this should be the root cause of your issue. I've simplified your code a bit a tried it on my Ubuntu 10.04LTS and it worked fine. My code is listed below, see if it would f...
How to know what django version i use? is it 1.0, 1.1, or 1.2?
4,151,788
12
2010-11-11T06:06:39Z
4,151,796
8
2010-11-11T06:07:59Z
[ "python", "django" ]
this is the first time i use django. I'm really a beginner. And this is the first time i see the page "It worked! Congratulations on your first Django-powered page.". it's mean i'm now have a django+python in my xampp server. So i cam to the question ? 1. How to know what django version i use? is it 1.0, 1.1, or 1.2 ?...
``` import django django.VERSION ```
How to know what django version i use? is it 1.0, 1.1, or 1.2?
4,151,788
12
2010-11-11T06:06:39Z
4,151,811
29
2010-11-11T06:10:17Z
[ "python", "django" ]
this is the first time i use django. I'm really a beginner. And this is the first time i see the page "It worked! Congratulations on your first Django-powered page.". it's mean i'm now have a django+python in my xampp server. So i cam to the question ? 1. How to know what django version i use? is it 1.0, 1.1, or 1.2 ?...
As to your first question: ``` jcomeau@intrepid:/usr/src/unternet$ python Python 2.6.6 (r266:84292, Oct 9 2010, 11:40:09) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.get_version() '1.2.3' ```
google app engine path in linux?
4,151,919
5
2010-11-11T06:33:14Z
4,152,200
13
2010-11-11T07:29:22Z
[ "python", "linux", "google-app-engine" ]
I'm starting to learn googleapp engine and use python. Whenever i create a new project, should i always include whole bunch of configuration and python files like these, ``` abhilash@abhilash:~/python_resources/google_appengine$ ls appcfg.py bulkload_client.py demos google LICENSE README ...
A new GAE project doesn't need any of those files. Per the [Getting Started Guide](http://code.google.com/appengine/docs/python/gettingstarted/helloworld.html), all you need is `app.yaml` and `main.py`. If your goal is less command-line typing you can add the `google_appengine` dir to your PATH in your `.bashrc`, e....
How to get the n next values of a generator in a list (python)
4,152,376
11
2010-11-11T08:01:13Z
4,152,389
24
2010-11-11T08:04:08Z
[ "python", "list", "generator" ]
I have made a generator to read a file word by word and it works nicely. ``` def word_reader(file): for line in open(file): for p in line.split(): yield p reader = word_reader('txtfile') next(reader) ``` What is the easiest way of getting the n next values in a list?
``` list(itertools.islice(it, 0, n, 1)) ```
How to get the n next values of a generator in a list (python)
4,152,376
11
2010-11-11T08:01:13Z
4,152,713
7
2010-11-11T08:56:17Z
[ "python", "list", "generator" ]
I have made a generator to read a file word by word and it works nicely. ``` def word_reader(file): for line in open(file): for p in line.split(): yield p reader = word_reader('txtfile') next(reader) ``` What is the easiest way of getting the n next values in a list?
**EDIT**: This is bad idea — it crashes when `it` yields less than `n` values, and this behaviour depends on subtle issues, so people reading such code are unlikely to understand it's precise semantics. > There is also > > ``` > [next(it) for _ in range(n)] > ``` > > which might(?) be clearer to people not familiar ...
Get the name of current script with Python
4,152,963
141
2010-11-11T09:32:35Z
4,152,986
221
2010-11-11T09:35:12Z
[ "python" ]
I'm trying to get the name of the Python script that is currently running. For example, I have a script called `foo.py` and I would like to do something like this inside it: ``` print Scriptname ``` and get: `foo.py`.
Use `__file__`. If you want to omit the directory part (which might be present), you can use `import os`,`os.path.basename(__file__)`.
Get the name of current script with Python
4,152,963
141
2010-11-11T09:32:35Z
4,152,992
63
2010-11-11T09:36:00Z
[ "python" ]
I'm trying to get the name of the Python script that is currently running. For example, I have a script called `foo.py` and I would like to do something like this inside it: ``` print Scriptname ``` and get: `foo.py`.
``` import sys print sys.argv[0] ``` This will print `foo.py` for `python foo.py`, `dir/foo.py` for `python dir/foo.py`, etc. It's the first argument to `python`. (Note that after py2exe it would be `foo.exe`.)
Get the name of current script with Python
4,152,963
141
2010-11-11T09:32:35Z
13,240,524
29
2012-11-05T21:16:56Z
[ "python" ]
I'm trying to get the name of the Python script that is currently running. For example, I have a script called `foo.py` and I would like to do something like this inside it: ``` print Scriptname ``` and get: `foo.py`.
Note that `__file__` will give the file where this code resides, which can be imported and different from the main file being interpreted. To get the main file, the special [\_\_main\_\_](http://docs.python.org/3/library/__main__.html) module can be used: ``` import __main__ as main print(main.__file__) ``` Note that...
Get the name of current script with Python
4,152,963
141
2010-11-11T09:32:35Z
29,430,130
10
2015-04-03T10:09:44Z
[ "python" ]
I'm trying to get the name of the Python script that is currently running. For example, I have a script called `foo.py` and I would like to do something like this inside it: ``` print Scriptname ``` and get: `foo.py`.
The Above answers are good . But I found this method more efficient using above results. This results in actual script file name not a path. ``` import sys import os file_name = os.path.basename(sys.argv[0]) ```
Get the name of current script with Python
4,152,963
141
2010-11-11T09:32:35Z
35,514,032
7
2016-02-19T20:07:07Z
[ "python" ]
I'm trying to get the name of the Python script that is currently running. For example, I have a script called `foo.py` and I would like to do something like this inside it: ``` print Scriptname ``` and get: `foo.py`.
For completeness' sake, I thought it would be worthwhile summarizing the various possible outcomes and supplying references for the exact behaviour of each: * `__file__` is the currently executing file, as detailed in the [official documentation](https://docs.python.org/3/reference/datamodel.html#index-43): > `__fi...
Execute task every so often within a process
4,152,969
6
2010-11-11T09:33:18Z
4,153,314
15
2010-11-11T10:15:20Z
[ "python", "timer" ]
I want to execute a task every 2 hours. Python has a Timer in Threading module, but does it meet my needs? How do I generate a proper Timer myself?
If you want your code to be run every 2 hours the easiest way would be using cron or a similar scheduler depending on your operating system if you want your programm to call a function every n seconds ( 7200 in your case ) you could use a thread and event.wait. The following example starts a timer that is triggered ev...
How to use comparison and ' if not' in python?
4,153,260
21
2010-11-11T10:08:40Z
4,153,344
34
2010-11-11T10:19:07Z
[ "python" ]
In one piece of my program I doubt if i use the comparison correctly. i want to make sure that ( u0 <= u < u0+step ) before do something. ``` if not (u0 <= u) and (u < u0+step): u0 = u0+ step # change the condition until it is satisfied else: do something. # condition is satisfied ```
You can do: ``` if not (u0 <= u <= u0+step): u0 = u0+ step # change the condition until it is satisfied else: do sth. # condition is satisfied ``` Using a loop: ``` while not (u0 <= u <= u0+step): u0 = u0+ step # change the condition until it is satisfied do sth. # condition is satisfied ```
Python and Server Load
4,153,881
17
2010-11-11T11:24:18Z
4,153,900
9
2010-11-11T11:26:45Z
[ "python" ]
Is there a way, using Python, to check the server load of a Linux machine periodically and inform me of it in some way?
[`os.getloadavg()`](http://docs.python.org/library/os.html#os.getloadavg)
Python and Server Load
4,153,881
17
2010-11-11T11:24:18Z
4,153,901
31
2010-11-11T11:26:50Z
[ "python" ]
Is there a way, using Python, to check the server load of a Linux machine periodically and inform me of it in some way?
Python has a function to get the system's load average as part of the os module ``` >>> import os >>> os.getloadavg() (1.1200000000000001, 1.0600000000000001, 0.79000000000000004) ``` From there, you can do whatever checks you need, and then email you, or similar.
How can I transform blocks into a blockdiagonal matrix (NumPy)
4,154,253
10
2010-11-11T12:11:51Z
4,155,943
14
2010-11-11T15:19:03Z
[ "python", "numpy" ]
I have three same-size square matrices in NumPy. I would like to combine these to a block-diagonal matrix. Example: ``` a1 = np.array([[1,1,1],[1,1,1],[1,1,1]]) a2 = np.array([[2,2,2],[2,2,2],[2,2,2]]) a3 = np.array([[3,3,3],[3,3,3],[3,3,3]]) r = np.array([[1,1,1,0,0,0,0,0,0],[1,1,1,0,0,0,0,0,0],[1,1,1,0,0,0,0,0,0],...
scipy.linalg has a block\_diag function to do this automatically ``` >>> a1 = np.array([[1,1,1],[1,1,1],[1,1,1]]) >>> a2 = np.array([[2,2,2],[2,2,2],[2,2,2]]) >>> a3 = np.array([[3,3,3],[3,3,3],[3,3,3]]) >>> import scipy.linalg >>> scipy.linalg.block_diag(a1, a2, a3) array([[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1...