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
Source Code in Bullet Lists with reStructuredText
4,206,393
20
2010-11-17T16:05:03Z
4,206,605
22
2010-11-17T16:23:20Z
[ "python", "documentation", "restructuredtext" ]
I am trying to include source code in bullet lists with reStructuredText; like this: ``` - List item 1 :: code sample... code sample... - List item 2 :: code sample... code sample... ``` However, I get the following warning: `System Message: WARNING/2 Literal block expected; none found.` The empty lines i...
Clearly, you haven't indented enough. Think of it this way. ``` - List item 1 :: code sample... code sample... - List item 2 :: code sample... code sample... ```
How do I iterate through all possible values in a series of fixed lists?
4,207,122
2
2010-11-17T17:10:44Z
4,207,194
7
2010-11-17T17:17:12Z
[ "python" ]
(python) so I have the following values & lists: ``` name = colour size = ['256', '512', '1024', '2048', '4096', '8192', '16384', '32768'] depth = ['8', '16', '32'] scalar = ['False', 'True'] alpha = ['False', 'True'] colour = app.Color(0.5) ``` and I want to iterate over these to produce every possible combination ...
``` import itertools for iter in itertools.product(size, depth, scalar, alpha): print iter # prints 96 four-element tuples ```
Why do elements in Python for ... in ...: statements use byValue behavior?
4,207,231
3
2010-11-17T17:20:00Z
4,207,260
8
2010-11-17T17:24:26Z
[ "python", "numpy", "iteration" ]
I can't seem to find an explanation anywhere for this... Suppose I have a vector y initialized to all zeroes: ``` from numpy import * y = zeros(5) ``` It could also be a plain python array, I don't think it really matters. I noticed that the behavior of the `for x in y:` statement is that it makes a *copy* of each ...
You can replace this: ``` y = np.zeros(5) for i in range(len(y)): y[i] = 2*rand()-1 ``` with: ``` y=2*np.random.rand(5)-1 ``` --- If y is a Python sequence (tuple, list, array, etc) or Numpy array, `for x in y:` iterates through `y`, setting `x` to each element in `y`. If the elements are immutable objects l...
Parse WAV file header
4,207,326
2
2010-11-17T17:32:17Z
4,207,411
7
2010-11-17T17:41:28Z
[ "python", "wav" ]
I am writing a program to parse a WAV file header and print the information to the screen. Before writing the program i am doing some research hexdump -n 48 sound\_file\_8000hz.wav ``` 00000000 52 49 46 46 bc af 01 00 57 41 56 45 66 6d 74 20 |RIFF....WAVEfmt | 00000010 10 00 00 00 01 00 01 00 >40 1f 00 00< 40 ...
The "40 1F 00 00" bytes equate to an integer whose hexadecimal value is 00001F40 (remember that the integers are stored in a WAVE file in the little endian format). A value of 00001F40 in hexadecimal equates to a decimal value of 8000. Similarly, the "44 AC 00 00" bytes equate to an integer whose hexadecimal value is ...
What exception is thrown when key is not found in Python dictionary?
4,207,790
10
2010-11-17T18:27:24Z
4,207,803
19
2010-11-17T18:28:58Z
[ "python", "exception", "dictionary" ]
If I have: ``` map = { 'stack':'overflow' } try: map['experts-exchange'] except: <--- What is the Exception type that's thrown here? print( 'is not free' ) ``` Couldn't find it on the web. =(
``` KeyError ``` if you do it on the console without the try block will tell it to you ``` >>> a = {} >>> a['invalid'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'invalid' >>> ```
How are Google App Engine model classes stored?
4,208,103
5
2010-11-17T19:02:50Z
4,208,183
10
2010-11-17T19:13:15Z
[ "python", "google-app-engine", "gae-datastore" ]
I'm in doubt how the objects are stored. Say I have a class defined like: ``` class SomeEntity(db.Model): some_number = db.IntegerProperty(required=True) def calculate_something(self): return self.some_number * 2 ``` My guess is that the only thing stored in the data store is the name/value/type of `...
Entities are stored in the datastore in a protobuf representation (including its key - which includes your App ID and the entity's Kind). The [Life of a Datastore Write](http://code.google.com/appengine/articles/life_of_write.html) article talks more about the representation of entities and how they are written to the ...
What is the benefit of using the ConfigParser instead of a regular python.py file when writing configuration files?
4,208,323
6
2010-11-17T19:28:53Z
4,208,528
9
2010-11-17T19:52:29Z
[ "python", "configuration", "module", "configuration-files" ]
I have been using the ConfigParser module to write configuration files for some time. However, a thought recently struck me; why not just use pure Python instead? Take this example configuration file: ``` [parameters] # Host host = stackoverflow.com port = 22 ``` To read these values into my code, I do ``` import Co...
> So what do I gain from using the ConfigParser module? Compatibility with Windows .ini files. Makes some people happy. > What are the pros and cons of each approach? ConfigParser has limited syntax and some relatively simple things get very contrived. Look at `logging` for examples. Python syntax is simpler and mu...
How to raise a 410 error in Django
4,208,572
7
2010-11-17T19:57:13Z
4,208,608
16
2010-11-17T20:00:46Z
[ "python", "django", "error-handling", "httpresponse", "http-status-code-410" ]
I'd like to return 410 errors at for some of my Django pages instead of returning 404s. Basically, instead of calling `raise Http404('some error message')`, I would like to instead call `raise Http410('some error message')` shortcut. I am confused because in django.http, the function Http404 is simply: ``` class Http...
``` from django.http import HttpResponse return HttpResponse(status=410) ```
How to raise a 410 error in Django
4,208,572
7
2010-11-17T19:57:13Z
4,208,641
9
2010-11-17T20:03:55Z
[ "python", "django", "error-handling", "httpresponse", "http-status-code-410" ]
I'd like to return 410 errors at for some of my Django pages instead of returning 404s. Basically, instead of calling `raise Http404('some error message')`, I would like to instead call `raise Http410('some error message')` shortcut. I am confused because in django.http, the function Http404 is simply: ``` class Http...
Return a `HttpResponseGone`, a subclass of [`HttpResponse`](http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponse), in your view handler.
How to raise a 410 error in Django
4,208,572
7
2010-11-17T19:57:13Z
4,209,389
12
2010-11-17T21:34:14Z
[ "python", "django", "error-handling", "httpresponse", "http-status-code-410" ]
I'd like to return 410 errors at for some of my Django pages instead of returning 404s. Basically, instead of calling `raise Http404('some error message')`, I would like to instead call `raise Http410('some error message')` shortcut. I am confused because in django.http, the function Http404 is simply: ``` class Http...
Django does not include a mechanism for this because gone should be normal workflow, not an error condition, but if you want to not treat it as a return response, and as an exception, just implement a [middleware](http://docs.djangoproject.com/en/dev/topics/http/middleware/). ``` class MyGoneMiddleware(object): de...
Python function parameter: tuple/list
4,208,619
6
2010-11-17T20:01:32Z
4,208,674
7
2010-11-17T20:06:22Z
[ "python", "list", "coding-style", "tuples" ]
My function expects a list or a tuple as a parameter. It doesn't really care which it is, all it does is pass it to another function that accepts either a list or tuple: ``` def func(arg): # arg is tuple or list another_func(x) # do other stuff here ``` Now I need to modify the function slightly, to process an ad...
If `another_func` just wants a iterable you can pass `itertools.chain(x,'a')` to it.
Execute background process from django that can't be interrupted by the web server
4,208,624
3
2010-11-17T20:02:23Z
4,208,878
8
2010-11-17T20:32:51Z
[ "python", "django", "linux", "apache", "background" ]
I'm seeing all kinds of threads like this and they have accepted answers, and yet I'm still stuck on this. I have a view that should start a backup procedure, and I got it to the point where the view returns, and the process is still running in the background, however **if apache is restarted**, the backup process the...
You need to use a completely separate process for the backup. The best way to do this is to use a message queue - the view puts the backup request on the queue, and a separate listener picks it up and runs the backup, independently of Apache. [Celery](http://ask.github.com/celery/) is a distributed task manager that d...
how to use pexpect to get spontaneous output of subprocess in python
4,208,820
3
2010-11-17T20:25:47Z
4,209,299
11
2010-11-17T21:22:16Z
[ "python", "multithreading", "wxpython", "pipe", "pexpect" ]
This is related to my another post [multithreading problem with wx.TextCtrl (or underlying GTK+)](http://stackoverflow.com/questions/4183404/multithreading-problem-with-wx-textctrl-or-underlying-gtk), which after correction with calling GUI interactions from primary thread, I find it again comes to the pipe block buffe...
Have you tried something like: ``` child = pexpect.spawn(launchcmd) while True: try: child.expect('\n') print(child.before) except pexpect.EOF: break ```
matplotlib share x axis but don't show x axis tick labels for both, just one
4,209,467
52
2010-11-17T21:45:32Z
4,209,548
72
2010-11-17T21:55:47Z
[ "python", "matplotlib" ]
I'm using python + matplotlib and I'm having two plots share an axis. If you try to set `graph1.set_xticklabels([])` while sharing an axis, it has no effect because it is shared. Is there a way to share the axis AND be able to hide the x axis of one plot?
This is a common gotcha when using shared axes. Fortunately, there's a simple fix: use [`plt.setp(ax.get_xticklabels(), visible=False)`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.setp) to make the labels invisible on just one axis. This is equivalent to `[label.set_visible(False) for lab...
matplotlib share x axis but don't show x axis tick labels for both, just one
4,209,467
52
2010-11-17T21:45:32Z
12,751,192
20
2012-10-05T17:27:34Z
[ "python", "matplotlib" ]
I'm using python + matplotlib and I'm having two plots share an axis. If you try to set `graph1.set_xticklabels([])` while sharing an axis, it has no effect because it is shared. Is there a way to share the axis AND be able to hide the x axis of one plot?
Per a thread on [matplotlib-users](http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg25311.html), you could use ``` import matplotlib.pyplot as plt for ax in plt.gcf().axes: try: ax.label_outer() except: pass ```
Absolute vs. explicit relative import of Python module
4,209,641
35
2010-11-17T22:07:09Z
4,209,771
16
2010-11-17T22:22:48Z
[ "python", "package", "python-import" ]
I'm wondering about the preferred way to import packages in a Python application. I have a package structure like this: ``` project.app1.models project.app1.views project.app2.models ``` `project.app1.views` imports `project.app1.models` and `project.app2.models`. There are two ways to do this that come to mind. Wit...
Absolute imports. From PEP 8: > Relative imports for intra-package imports are highly > discouraged. > Always use the absolute package path for all imports. > Even now that PEP 328 [7] is fully implemented in Python 2.5, > its style of explicit relative imports is actively discouraged; > absolute imports are more port...
Absolute vs. explicit relative import of Python module
4,209,641
35
2010-11-17T22:07:09Z
4,209,804
17
2010-11-17T22:25:57Z
[ "python", "package", "python-import" ]
I'm wondering about the preferred way to import packages in a Python application. I have a package structure like this: ``` project.app1.models project.app1.views project.app2.models ``` `project.app1.views` imports `project.app1.models` and `project.app2.models`. There are two ways to do this that come to mind. Wit...
Relative imports not only leave you free to rename your package later without changing dozens of internal imports, but I have also had success with them in solving certain problems involving things like circular imports or namespace packages, because they do not send Python "back to the top" to start the search for the...
Absolute vs. explicit relative import of Python module
4,209,641
35
2010-11-17T22:07:09Z
16,748,366
65
2013-05-25T09:54:02Z
[ "python", "package", "python-import" ]
I'm wondering about the preferred way to import packages in a Python application. I have a package structure like this: ``` project.app1.models project.app1.views project.app2.models ``` `project.app1.views` imports `project.app1.models` and `project.app2.models`. There are two ways to do this that come to mind. Wit...
Python relative imports are no longer strongly discouraged, but using absolute\_import is strongly suggested in that case. Please see [this discussion](http://bugs.python.org/issue10031) citing Guido himself: > "Isn't this mostly historical? Until the new relative-import syntax > was implemented there were various pr...
Eliminate this unneeded copy in list.extend
4,210,481
2
2010-11-18T00:05:34Z
4,210,609
9
2010-11-18T00:38:29Z
[ "python", "optimization" ]
Given two normal python lists, `newlist` and `oldlist`, with an integer `index` < `len(oldlist)`, I'd like to perform the following operation: ``` newlist.extend(oldlist[index:]) ``` but without creating the intermediate list `oldlist[index:]`, or equivalently, ``` newlist.extend(oldlist[i] for i in xrange(index, le...
Don't guess, measure ``` create = """ oldlist = range(5000) newlist = range(5000, 10000) index = 500 """ tests = [ "newlist.extend(oldlist[index:])", "newlist.extend(oldlist[i] for i in xrange(index, len(oldlist)))", "newlist.extend(islice(oldlist, index, None))", """\ while index < len(oldlist): ne...
How do I use xml namespaces with find/findall in lxml?
4,210,730
14
2010-11-18T01:07:30Z
4,210,882
10
2010-11-18T01:39:20Z
[ "python", "xml", "lxml", "xml-namespaces", "elementtree" ]
I'm trying to parse content in an OpenOffice ODS spreadsheet. The ods format is essentially just a zipfile with a number of documents. The content of the spreadsheet is stored in 'content.xml'. ``` import zipfile from lxml import etree zf = zipfile.ZipFile('spreadsheet.ods') root = etree.parse(zf.open('content.xml'))...
If `root.nsmap` contains the `table` namespace prefix then you could: ``` root.xpath('.//table:table', namespaces=root.nsmap) ``` `findall(path)` accepts `{namespace}name` syntax instead of `namespace:name`. Therefore `path` should be preprocessed using namespace dictionary to the `{namespace}name` form before passin...
Python: variable-length tuples
4,210,981
4
2010-11-18T02:02:59Z
4,211,359
10
2010-11-18T03:14:13Z
[ "python", "performance", "list", "python-3.x", "tuples" ]
[Python 3.1] I'm following up on the design concept that tuples should be of known length (see [this comment](http://stackoverflow.com/questions/4208619/python-function-parameter-tuple-list/4208673#comment4554133_4208673)), and unknown length tuples should be replaced with lists in most circumstances. My question is u...
In my mind, the only interesting distinction between tuples and lists is that lists are mutable and tuples are not. The other distinctions that people mention seem completely artificial to me: tuples are like structs and lists are like arrays (this is where the "tuples should be a known length" comes from). But how is ...
Remove all the elements that occur in one list from another
4,211,209
99
2010-11-18T02:45:49Z
4,211,228
129
2010-11-18T02:48:31Z
[ "python", "list" ]
Let's say I have two lists, `l1` and `l2`. I want to perform `l1 - l2`, which returns all elements of `l1` not in `l2`. I can think of a naive loop approach to doing this, but that is going to be really inefficient. What is a pythonic and efficient way of doing this? As an example, if I have `l1 = [1,2,6,8] and l2 = ...
Python has a language feature called [List Comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) that is perfectly suited to making this sort of thing extremely easy. The following statement does exactly what you want and stores the result in `l3`: ``` l3 = [x for x in l1 if x not in...
Remove all the elements that occur in one list from another
4,211,209
99
2010-11-18T02:45:49Z
4,211,239
37
2010-11-18T02:50:51Z
[ "python", "list" ]
Let's say I have two lists, `l1` and `l2`. I want to perform `l1 - l2`, which returns all elements of `l1` not in `l2`. I can think of a naive loop approach to doing this, but that is going to be really inefficient. What is a pythonic and efficient way of doing this? As an example, if I have `l1 = [1,2,6,8] and l2 = ...
One way is to use sets: ``` >>> set([1,2,6,8]) - set([2,3,5,8]) set([1, 6]) ```
Remove all the elements that occur in one list from another
4,211,209
99
2010-11-18T02:45:49Z
4,211,265
10
2010-11-18T02:56:24Z
[ "python", "list" ]
Let's say I have two lists, `l1` and `l2`. I want to perform `l1 - l2`, which returns all elements of `l1` not in `l2`. I can think of a naive loop approach to doing this, but that is going to be really inefficient. What is a pythonic and efficient way of doing this? As an example, if I have `l1 = [1,2,6,8] and l2 = ...
Use the Python set type. That would be the most Pythonic. :) Also, since it's native, it should be the most optimized method too. See: <http://docs.python.org/library/stdtypes.html#set> <http://docs.python.org/library/sets.htm> (for older python) ``` # Using Python 2.7 set literal format. # Otherwise, use: l1 = se...
Remove all the elements that occur in one list from another
4,211,209
99
2010-11-18T02:45:49Z
4,211,325
17
2010-11-18T03:07:25Z
[ "python", "list" ]
Let's say I have two lists, `l1` and `l2`. I want to perform `l1 - l2`, which returns all elements of `l1` not in `l2`. I can think of a naive loop approach to doing this, but that is going to be really inefficient. What is a pythonic and efficient way of doing this? As an example, if I have `l1 = [1,2,6,8] and l2 = ...
Expanding on Donut's answer and the other answers here, you can get even better results by using a generator comprehension instead of a list comprehension, and by using a `set` data structure (since the `in` operator is O(n) on a list but O(1) on a set). So here's a function that would work for you: ``` def filter_li...
How to make this Twisted Python Proxy faster?
4,211,454
4
2010-11-18T03:34:29Z
4,211,963
11
2010-11-18T05:30:01Z
[ "python", "http", "proxy", "twisted" ]
The code below is an HTTP proxy for content filtering. It uses GET to send the URL of the current site to the server, where it processes it and responds. It runs **VERY**, **VERY**, **VERY** slow. Any ideas on how to make it faster? **Here is the code:** ``` from twisted.internet import reactor from twisted.web impor...
The main cause of slowness in this proxy is probably these three lines: ``` req = urllib.urlopen("http://weblock.zbrowntechnology.info/ProgFiles/stats.php?%s" % params, proxies=proxies) resp = req.read() req.close() ``` A normal Twisted-based application is single threaded. You have to go out of your way ...
When and how to use Tornado? When is it useless?
4,212,877
55
2010-11-18T08:29:04Z
4,213,777
29
2010-11-18T10:27:07Z
[ "python", "asynchronous", "nonblocking", "tornado" ]
Ok, Tornado is non-blocking and quite fast and it can handle a lot of standing requests easily. But I guess it's not a silver bullet and if we just blindly run Django-based or any other site with Tornado it won't give any performance boost. I couldn't find comprehensive explanation of this, so I'm asking it here: * ...
> There is a server and a webframework. When should we use framework and when can we replace it with other one? This distinction is a bit blurry. Only if you are serving static pages, you would use one of the fast server like lighthttpd. Other wise, most servers provides a varying complexity of framework to develop we...
Detect if python script is run from console or by crontab
4,213,091
11
2010-11-18T09:01:51Z
4,213,118
27
2010-11-18T09:05:42Z
[ "python", "bash", "environment-variables", "crontab" ]
Imagine a script is running in these 2 sets of "conditions": 1. live action, set up in `sudo crontab` 2. debug, when I run it from console `./my-script.py` What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. `--debug`) for the script. Is there a convention abou...
Since `sys.stdin` will be a [TTY](http://en.wikipedia.org/wiki/TTY) in debug mode, you can use the [os.isatty()](http://docs.python.org/library/os.html#os.isatty) function: ``` import sys, os if os.isatty(sys.stdin.fileno()): # Debug mode. pass else: # Cron mode. pass ```
Python and ctypes: how to correctly pass "pointer-to-pointer" into DLL?
4,213,095
12
2010-11-18T09:02:25Z
4,218,409
13
2010-11-18T18:51:22Z
[ "python", "ctypes" ]
I have a DLL that allocates memory and returns it. Function in DLL is like this: ``` void Foo( unsigned char** ppMem, int* pSize ) { * pSize = 4; * ppMem = malloc( * pSize ); for( int i = 0; i < * pSize; i ++ ) (* ppMem)[ i ] = i; } ``` Also, i have a python code that access this function from my DLL: ``` from...
Post actual code. The C/C++ code doesn't compile as either C or C++. The Python code has syntax errors (] ending function call Foo). The code below works. The main issue after fixing syntax and compiler errors was declaring the function `__stdcall` so `windll` could be used in the Python code. The other option is to us...
Sending data using POST in Python to PHP
4,214,231
11
2010-11-18T11:27:11Z
5,986,282
28
2011-05-13T01:15:51Z
[ "php", "python", "urllib2" ]
PHP code: ``` <?php $data=$_POST['data']; echo $data; ?> ``` When I do that, the HTML page that Python prints notifies me that PHP did not receive any value in `$data` I.e: > Error in $name; undefined index However, when I send the data as GET (`http://localhost/mine.php?data=data`) and change the PHP method from P...
Look at this python: ``` import urllib2, urllib mydata=[('one','1'),('two','2')] #The first is the var name the second is the value mydata=urllib.urlencode(mydata) path='http://localhost/new.php' #the url you want to POST to req=urllib2.Request(path, mydata) req.add_header("Content-type", "application/x-www-form...
IPython on Windows - No highlighting or Auto-complete
4,214,354
14
2010-11-18T11:41:44Z
4,214,398
21
2010-11-18T11:48:14Z
[ "python", "windows", "django", "ipython", "django-shell" ]
this has been an issue for a long time for me, but as I mainly develop using Linux I never really cared much about this problem till now. **iPython on Windows lacks various features.** **I really miss color ~~highlighting~~ and auto-completion.** --- **Edit:** fixed highlighting by installing **pyreadline** > pip ...
You need to install [PyReadline](http://pypi.python.org/pypi/pyreadline), documentation is [here](http://packages.python.org/pyreadline/introduction.html).
kill process with python
4,214,773
8
2010-11-18T12:35:19Z
4,215,561
15
2010-11-18T14:02:38Z
[ "python", "linux", "process", "kill" ]
I need to make a script that gets from the user the following: 1) Process name (on linux). 2) The log file name that this process write to it. It needs to kill the process and verify that the process is down. Change the log file name to a new file name with the time and date. And then run the process again, verify t...
You can retrieve the process id (PID) given it name using `pgrep` command like this: ``` import subprocess import signal import os from datetime import datetime as dt process_name = sys.argv[1] log_file_name = sys.argv[2] proc = subprocess.Popen(["pgrep", process_name], stdout=subprocess.PIPE) # Kill process. fo...
An example using python bindings for SVM library, LIBSVM
4,214,868
22
2010-11-18T12:44:24Z
4,215,056
11
2010-11-18T13:07:26Z
[ "python", "machine-learning", "svm", "libsvm" ]
I am in dire need of a classification task example using LibSVM in python. I don't know how the Input should look like and which function is responsible for training and which one for testing Thanks
LIBSVM reads the data from a tuple containing two lists. The first list contains the classes and the second list contains the input data. create simple dataset with two possible classes you also need to specify which kernel you want to use by creating svm\_parameter. ``` >> from libsvm import * >> prob = svm_problem([...
An example using python bindings for SVM library, LIBSVM
4,214,868
22
2010-11-18T12:44:24Z
4,215,169
20
2010-11-18T13:20:32Z
[ "python", "machine-learning", "svm", "libsvm" ]
I am in dire need of a classification task example using LibSVM in python. I don't know how the Input should look like and which function is responsible for training and which one for testing Thanks
This example demonstrates a one-class ***SVM classifier***; it's about as simple as possible while still showing the complete LIBSVM workflow. ***Step 1***: Import NumPy & LIBSVM ``` import numpy as NP from svm import * ``` ***Step 2:*** Generate synthetic data: for this example, 500 points within a given boun...
An example using python bindings for SVM library, LIBSVM
4,214,868
22
2010-11-18T12:44:24Z
6,732,799
21
2011-07-18T12:23:19Z
[ "python", "machine-learning", "svm", "libsvm" ]
I am in dire need of a classification task example using LibSVM in python. I don't know how the Input should look like and which function is responsible for training and which one for testing Thanks
The code examples listed here don't work with LibSVM 3.1, so I've more or less ported [the example by mossplix](http://stackoverflow.com/questions/4214868/an-example-using-libsvm-in-python/4215056#4215056): ``` from svmutil import * svm_model.predict = lambda self, x: svm_predict([0], [x], self)[0][0] prob = svm_prob...
Python: take max N elements from some list
4,215,472
22
2010-11-18T13:54:56Z
4,215,776
30
2010-11-18T14:26:41Z
[ "python", "max" ]
Is there some function which would return me the N highest elements from some list? I.e. if `max(l)` returns the single highest element, sth. like `max(l, count=10)` would return me a list of the 10 highest numbers (or less if `l` is smaller). Or what would be an efficient easy way to get these? (Except the obvious c...
[`heapq.nlargest`](http://docs.python.org/library/heapq.html#heapq.nlargest): ``` >>> import heapq, random >>> heapq.nlargest(3, (random.gauss(0, 1) for _ in xrange(100))) [1.9730767232998481, 1.9326532289091407, 1.7762926716966254] ```
How to bind engine when I want, when using declarative_base in SQLAlchemy?
4,215,920
4
2010-11-18T14:38:30Z
21,945,945
7
2014-02-21T21:53:54Z
[ "python", "database", "orm", "sqlalchemy" ]
Here's my code: ``` from sqlalchemy import create_engine, Column, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker database_url = 'mysql://some_path' engine = create_engine(database_url) Base = declarative_base(engine) class Users(Base): __tablename__ = 'Use...
At least with SQLAlchemy 0.9 you can defer the binding by using DeferredReflection. See the example in the [Using Reflection with Declarative section of the manual](http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/declarative.html#using-reflection-with-declarative). There, you can find the following example (simpl...
Splitting a string into a list in python
4,216,489
2
2010-11-18T15:31:23Z
4,216,514
11
2010-11-18T15:33:55Z
[ "python", "string", "split" ]
I have a long string of characters which I want to split into a list of the individual characters. I want to include the whitespaces as members of the list too. How do I do this?
you can do: ``` list('foo') ``` spaces will be treated as list members (though not grouped together, but you didn't specify you needed that) ``` >>> list('foo') ['f', 'o', 'o'] >>> list('f oo') ['f', ' ', 'o', 'o'] ```
MemoryStream analog in Python
4,216,491
5
2010-11-18T15:31:55Z
4,216,530
10
2010-11-18T15:34:49Z
[ "c#", "python", "memorystream" ]
Does some analog of C# `MemoryStream` exist in Python (that could allow me to write binary data from some source direct into memory)? And how would I go about using it?
StringIO is one possibility: <http://docs.python.org/library/stringio.html> > This module implements a file-like class, `StringIO`, that reads and writes a string buffer (also known as *memory files*). See the description of file objects for operations (section *File Objects*). (For standard strings, see `str` and `un...
Call to operating system to open url?
4,216,985
36
2010-11-18T16:16:01Z
4,217,032
53
2010-11-18T16:19:50Z
[ "python", "url", "operating-system", "system-calls" ]
What can I use to call the OS to open a URL in whatever browser the user has as default? Not worried about cross-OS compatibility; if it works in linux thats enough for me!
Here is how to open the user's default browser with a given url: ``` import webbrowser webbrowser.open(url[, new=0[, autoraise=True]]) ``` Here is the documentation about this functionality. It's part of Python's stdlibs: <http://docs.python.org/library/webbrowser.html> I have tested this successfully on Linux, Ub...
Call to operating system to open url?
4,216,985
36
2010-11-18T16:16:01Z
4,217,323
21
2010-11-18T16:43:42Z
[ "python", "url", "operating-system", "system-calls" ]
What can I use to call the OS to open a URL in whatever browser the user has as default? Not worried about cross-OS compatibility; if it works in linux thats enough for me!
Personally I really *wouldn't* use the `webbrowser` module. It's a complicated mess of sniffing for particular browsers, which will won't find the user's default browser if they have more than one installed, and won't find a browser if it doesn't know the name of it (eg Chrome). Better on Windows is simply to use the...
Why fmod(1.0,0.1) == .1?
4,218,961
4
2010-11-18T19:57:17Z
4,219,076
21
2010-11-18T20:09:48Z
[ "python", "math", "floating-point" ]
I experienced this phenomenon in Python first, but it turned out that it is the common answer, for example MS Excel gives this. Wolfram Alpha gives an interesting schizoid answer, where it states that the rational approximation of zero is 1/5. ( [1.0 mod 0.1](http://www.wolframalpha.com/input/?i=1.0+mod+.1) ) On the o...
Because `0.1` isn't 0.1; that value isn't representable in double precision, so it gets rounded to the nearest double-precision number, which is exactly: ``` 0.1000000000000000055511151231257827021181583404541015625 ``` When you call `fmod`, you get the remainder of division by the value listed above, which is exactl...
How to assert output with nosetest/unittest in python?
4,219,717
48
2010-11-18T21:22:51Z
4,220,278
42
2010-11-18T22:28:52Z
[ "python", "unit-testing", "nosetests", "python-nose" ]
I'm writing tests for a function like next one: ``` def foo(): print 'hello world!' ``` So when I want to test this function the code will be like this: ``` import sys from foomodule import foo def test_foo(): foo() output = sys.stdout.getline().strip() # because stdout is an StringIO instance assert...
If you really want to do this, you can reassign sys.stdout for the duration of the test. ``` def test_foo(): import sys from foomodule import foo from StringIO import StringIO saved_stdout = sys.stdout try: out = StringIO() sys.stdout = out foo() output = out.getval...
How to assert output with nosetest/unittest in python?
4,219,717
48
2010-11-18T21:22:51Z
7,654,776
8
2011-10-04T22:33:04Z
[ "python", "unit-testing", "nosetests", "python-nose" ]
I'm writing tests for a function like next one: ``` def foo(): print 'hello world!' ``` So when I want to test this function the code will be like this: ``` import sys from foomodule import foo def test_foo(): foo() output = sys.stdout.getline().strip() # because stdout is an StringIO instance assert...
I'm only just learning Python and found myself struggling with a similar problem to the one above with unit tests for methods with output. My passing unit test for foo module above has ended up looking like this: ``` import sys import unittest from foo import foo from StringIO import StringIO class FooTest (unittest....
How to assert output with nosetest/unittest in python?
4,219,717
48
2010-11-18T21:22:51Z
12,683,001
28
2012-10-02T00:29:47Z
[ "python", "unit-testing", "nosetests", "python-nose" ]
I'm writing tests for a function like next one: ``` def foo(): print 'hello world!' ``` So when I want to test this function the code will be like this: ``` import sys from foomodule import foo def test_foo(): foo() output = sys.stdout.getline().strip() # because stdout is an StringIO instance assert...
Since version 2.7, you do not need anymore to reassign `sys.stdout`, this is provided through [`buffer` flag](http://docs.python.org/library/unittest.html#unittest.TestResult.buffer). Moreover, it is the default behavior of nosetest. Here is a sample failing in non buffered context: ``` import sys import unittest de...
How to assert output with nosetest/unittest in python?
4,219,717
48
2010-11-18T21:22:51Z
17,981,937
37
2013-07-31T22:16:00Z
[ "python", "unit-testing", "nosetests", "python-nose" ]
I'm writing tests for a function like next one: ``` def foo(): print 'hello world!' ``` So when I want to test this function the code will be like this: ``` import sys from foomodule import foo def test_foo(): foo() output = sys.stdout.getline().strip() # because stdout is an StringIO instance assert...
I use this [context manager](https://docs.python.org/2/library/contextlib.html#contextlib.contextmanager) to capture output. It ultimately uses the same technique as some of the other answers by temporarily replacing `sys.stdout`. I prefer the context manager because it wraps all the bookkeeping into a single function,...
Get Tkinter Window Size
4,220,295
13
2010-11-18T22:31:14Z
4,221,002
20
2010-11-19T00:13:55Z
[ "python", "tkinter" ]
How do I get the width and height of a Tkinter window?
You use the `winfo_width` method of the widget to get the actual width. You can use `winfo_reqwidth` to get the size that the widget is requesting, which may be different. Note that if you call this before the window appears on the screen, you won't get the answer you expect. Tkinter needs to have actually drawn the w...
Writing a small yet flexible HTTP client
4,220,601
2
2010-11-18T23:10:57Z
4,220,771
9
2010-11-18T23:33:54Z
[ "python", "ruby", "perl", "http" ]
I'm looking to find out how people would go about writing a quick (small) yet flexible HTTP client. By quick I mean not much code, (I'll leave it up to you to decide what that means), and preferably using built-in language functions as opposed to downloaded or custom libraries, such that a basic knowledge of socket pro...
Perl has [LWP](http://search.cpan.org/perldoc/LWP). I suggest you use it.
Implementing webbased real time video chat using HTML5 websockets
4,220,672
40
2010-11-18T23:19:56Z
4,220,882
27
2010-11-18T23:49:00Z
[ "python", "video", "html5", "audio", "websocket" ]
Does anyone know how to implement voice/video over IP in a webapplication using HTML5 websockets? It would be nice if I could implement this with PHP or Python since I (unfortunately) don't know any other programming language at the moment. A good tutorial will do, as well as an already-build-solution which I have to...
If you want to go with HTML5 only, you will need a browser implementing the **HTML Media Capture** draft (available [here](http://www.w3.org/TR/capture-api/)) in order to access the raw data from the microphone. Once you have this data in hand, you need to send it over the network. Websockets would be the HTML5 option...
Implementing webbased real time video chat using HTML5 websockets
4,220,672
40
2010-11-18T23:19:56Z
4,236,695
7
2010-11-21T06:16:01Z
[ "python", "video", "html5", "audio", "websocket" ]
Does anyone know how to implement voice/video over IP in a webapplication using HTML5 websockets? It would be nice if I could implement this with PHP or Python since I (unfortunately) don't know any other programming language at the moment. A good tutorial will do, as well as an already-build-solution which I have to...
Seems like Ericsson created the first HTML5 Video Conference App. ### The technique they used: * Implemented the device element and the Stream API (device element GUI is currently written in JavaScript/CSS) * Added MediaStreamManager to map Stream URLs to the corresponding pipeline in the media backend * Added MediaS...
How to ensure that a python dict keys are lowercase?
4,223,654
7
2010-11-19T09:31:03Z
4,223,871
14
2010-11-19T09:57:26Z
[ "python", "json", "simplejson", "django-piston" ]
I have a dict that I want to convert in JSON using simplejson. How can I ensure that all the keys of my dict are lowercase ? ``` { "DISTANCE": 17.059918745802999, "name": "Foo Bar", "Restaurant": { "name": "Foo Bar", "full_address": { "country": "...
``` >>> d = {"your": "DATA", "FROM": "above"} >>> dict((k.lower(), v) for k, v in d.iteritems()) {'from': 'above', 'your': 'DATA'} >>> def lower_keys(x): ... if isinstance(x, list): ... return [lower_keys(v) for v in x] ... elif isinstance(x, dict): ... return dict((k.lower(), lower_keys(v)) for k, v in x.i...
how to change the case of first letter of a string?
4,223,923
22
2010-11-19T10:03:09Z
4,223,942
27
2010-11-19T10:05:52Z
[ "python", "string", "uppercase" ]
``` s = ['my', 'name'] ``` I want to change the 1st letter of each element in to Upper Case. ``` s = ['My', 'Name'] ```
You can use the [capitalize()](https://docs.python.org/2/library/stdtypes.html#str.capitalize) method: ``` s = ['my', 'name'] s = [item.capitalize() for item in s] print s # print(s) in Python 3 ``` This will print: ``` ['My', 'Name'] ```
how to change the case of first letter of a string?
4,223,923
22
2010-11-19T10:03:09Z
4,223,944
13
2010-11-19T10:06:07Z
[ "python", "string", "uppercase" ]
``` s = ['my', 'name'] ``` I want to change the 1st letter of each element in to Upper Case. ``` s = ['My', 'Name'] ```
You can use `'my'.title()` which will return `'My'`. To get over the complete list, simply map over it like this: ``` >>> map(lambda x: x.title(), s) ['My', 'Name'] ``` Actually, `.title()` makes all words start with uppercase. If you want to strictly limit it the first letter, use `capitalize()` instead. (This make...
how to change the case of first letter of a string?
4,223,923
22
2010-11-19T10:03:09Z
13,525,843
38
2012-11-23T09:07:47Z
[ "python", "string", "uppercase" ]
``` s = ['my', 'name'] ``` I want to change the 1st letter of each element in to Upper Case. ``` s = ['My', 'Name'] ```
Both .capitalize() and .title(), changes the other letters in the string to lower case. Here is a simple function that only changes the first letter to upper case, and leaves the rest unchanged. ``` def upcase_first_letter(s): return s[0].upper() + s[1:] ```
"htop" style gui with python, how?
4,224,933
5
2010-11-19T12:26:19Z
4,224,975
8
2010-11-19T12:30:17Z
[ "python", "user-interface", "text" ]
I am intersted in building some text based GUIs, things that look like the terminal, but has functions like selecting rows and performing actions. You know, things like htop and atop, ex: ![atop](http://lh5.ggpht.com/_fF0LO28FGYY/Sc6CBjZICQI/AAAAAAAAAhE/9GcnTxk9J7w/s800/atop.png) ![htop](http://lh6.ggpht.com/_fF0LO2...
You need [Uwrid](http://excess.org/urwid/) - a console user interface library for Python. Documentation available on the website. There is also [Curses](http://docs.python.org/library/curses.html), which is in the Python standard library.
Python mechanize login to website
4,225,721
5
2010-11-19T14:04:31Z
4,226,506
8
2010-11-19T15:34:48Z
[ "python", "webforms", "mechanize" ]
I'm trying to log into a website using Python and Mechanize, however, I'm running into trouble when trying to get the POST data to behave as I want. Essentially I want to replicate this using mechanize and Python: ``` wget --quiet --save-cookies cookiejar --keep-session-cookies --post-data "action=login&login_nick=US...
Mechanize seems to urlencode the strings anyway, so there's no point in fighting it. This is the final solution (obviously not syntactically valid, but hopefully you get the idea). ``` import mechanize self.browser = mechanize.Browser() self.browser.open(self.url) self.browser.select_form(name="login") self.browser[...
Why can I update a list slice but not a string slice in python?
4,225,743
5
2010-11-19T14:07:37Z
4,225,757
9
2010-11-19T14:09:25Z
[ "python", "string", "slice" ]
Just curious more than anything why python will allow me to update a slice of a list but not a string? ``` >>> s = "abc" >>> s[1:2] 'b' >>> s[1:3] 'bc' >>> s[1:3] = "aa" >>> l = [1,2,3] >>> l[1:3] [2, 3] >>> l[1:3] = [9,0] >>> l [1, 9, 0] ``` Is there a good reason for this? (I am sure there is.)
Because in python, strings are [immutable](http://en.wikipedia.org/wiki/Immutable_object).
html to .doc converter in Python?
4,226,095
9
2010-11-19T14:48:07Z
4,227,062
8
2010-11-19T16:26:35Z
[ "python", "ms-word", "pisa" ]
I am using pisa, which is an HTML to PDF conversion library for Python. Does there exist the same thing for a Word document: an HTML to .doc conversion library for Python?
You could use win32com from the [pywin32](http://pypi.python.org/pypi/pywin32) python extensions for windows, to let MS Word convert it for you. A simple example: ``` import win32com.client word = win32com.client.Dispatch('Word.Application') doc = word.Documents.Add('example.html') doc.SaveAs('example.doc', FileForm...
Resizing and stretching a NumPy array
4,226,386
13
2010-11-19T15:20:34Z
4,226,464
9
2010-11-19T15:28:53Z
[ "python", "arrays", "resize", "numpy", "stretch" ]
I am working in Python and I have a [NumPy](http://en.wikipedia.org/wiki/NumPy) array like this: ``` [1,5,9] [2,7,3] [8,4,6] ``` How do I stretch it to something like the following? ``` [1,1,5,5,9,9] [1,1,5,5,9,9] [2,2,7,7,3,3] [2,2,7,7,3,3] [8,8,4,4,6,6] [8,8,4,4,6,6] ``` These are just some example arrays, I will...
``` >>> a = numpy.array([[1,5,9],[2,7,3],[8,4,6]]) >>> numpy.kron(a, [[1,1],[1,1]]) array([[1, 1, 5, 5, 9, 9], [1, 1, 5, 5, 9, 9], [2, 2, 7, 7, 3, 3], [2, 2, 7, 7, 3, 3], [8, 8, 4, 4, 6, 6], [8, 8, 4, 4, 6, 6]]) ```
Resizing and stretching a NumPy array
4,226,386
13
2010-11-19T15:20:34Z
4,227,280
17
2010-11-19T16:46:37Z
[ "python", "arrays", "resize", "numpy", "stretch" ]
I am working in Python and I have a [NumPy](http://en.wikipedia.org/wiki/NumPy) array like this: ``` [1,5,9] [2,7,3] [8,4,6] ``` How do I stretch it to something like the following? ``` [1,1,5,5,9,9] [1,1,5,5,9,9] [2,2,7,7,3,3] [2,2,7,7,3,3] [8,8,4,4,6,6] [8,8,4,4,6,6] ``` These are just some example arrays, I will...
@KennyTM's answer is very slick, and really works for your case but as an alternative that might offer a bit more flexibility for expanding arrays try `np.repeat`: ``` >>> a = np.array([[1, 5, 9], [2, 7, 3], [8, 4, 6]]) >>> np.repeat(a,2, axis=1) array([[1, 1, 5, 5, 9, 9], [2, 2, 7,...
Editing Excel sheets with Python
4,226,754
7
2010-11-19T15:59:22Z
4,226,895
9
2010-11-19T16:10:11Z
[ "python", "excel", "editing" ]
I need to edit an excel workbook using python. Is there a way of doing this without reading in the workbook, editing what I want and the writing it back? ie is there a way I can do this on the fly as I only need to edit a couple of values per sheet. I have looked at pyexcelerator, xlrd and xlwt, but they only seem to ...
First off, what version of Excel? Excel2007+ use an XML file format, while Excel2003- used a proprietary binary format... so the tools to read and write these work in totally different ways. If you're after the more recent xlsx files, then take a look at Eric' Gazoni's [openpyxl](http://ericgazoni.wordpress.com/2010/0...
Python "IOError: [Errno 22] Invalid argument" when using cPickle to write large array to network drive
4,226,941
5
2010-11-19T16:15:28Z
4,228,291
12
2010-11-19T18:44:24Z
[ "python", "ioerror", "nas", "pickle" ]
EDIT: At the suggestion of J. F. Sebastian, I can get the same error much more simply: ``` Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview ...
I believe the problem is related to: <http://support.microsoft.com/default.aspx?scid=kb;en-us;899149> ...so, just try: open(r'z:\test.bin','w+b').write('a'\*67080064) \*Note the argument: 'w+b'
Python module for multiple variable global optimization
4,227,538
12
2010-11-19T17:11:21Z
4,227,717
9
2010-11-19T17:31:41Z
[ "python", "numpy", "scientific-computing" ]
I have been looking for a python module that implements the [common techniques](http://www.mat.univie.ac.at/~neum/glopt/software_g.html) of global optimization (finding the global minimum of a function in N dimensions) without success. If you heard about a simulated annealing or genetic algorithm implementation in pyt...
Scipy's [optimize](http://docs.scipy.org/doc/scipy/reference/optimize.html) module has an [anneal](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.anneal.html) function that might fit your needs. Also, you should check out the [PyEvolve](http://pyevolve.sourceforge.net/) module for doing a gen...
How can I send python multiprocessing Process output to a Tkinter gui
4,227,808
7
2010-11-19T17:42:10Z
4,298,569
8
2010-11-28T19:25:30Z
[ "python", "user-interface", "tkinter", "stdout", "multiprocessing" ]
I'm trying to get output from a python multiprocessing Process displayed in a Tkinter gui. I can send output from Processes via a gui to a command shell, for example by running the fllowing tiny script at a shell prompt: ``` from multiprocessing import Process import sys def myfunc(text): print text ...
You could redirect stdout/stderr to a StringIO in myfunc(), then send whatever gets written into that StringIO back to the parent (as suggested by unutbu). See my answer to [this question](http://stackoverflow.com/questions/4241234/having-a-console-in-a-single-threaded-python-script/4247395#4247395) for one way of doin...
PIL thumbnail is rotating my image?
4,228,530
25
2010-11-19T19:14:27Z
6,218,425
39
2011-06-02T18:05:44Z
[ "python", "python-imaging-library" ]
I'm attempting to take large (huge) images (from a digital camera), and convert them into something that I can display on the web. This seems straightforward, and probably should be. However, when I attempt to use PIL to create thumbnail versions, if my source image is taller than it is wide, the resulting image is rot...
I agree with almost everything as answered by "unutbu" and Ignacio Vazquez-Abrams, however... EXIF Orientation flag can have a value between 1 and 8 depending on how the camera was held. Portrait photo can be taken with top of the camera on the left, or right edge, landscape photo could be taken upside down. Here is...
PIL thumbnail is rotating my image?
4,228,530
25
2010-11-19T19:14:27Z
11,543,365
26
2012-07-18T14:12:08Z
[ "python", "python-imaging-library" ]
I'm attempting to take large (huge) images (from a digital camera), and convert them into something that I can display on the web. This seems straightforward, and probably should be. However, when I attempt to use PIL to create thumbnail versions, if my source image is taller than it is wide, the resulting image is rot...
xilvar's answer is very nice, but had two minor shortcomings that I wanted to fix in a rejected edit, so I'll post it as an answer. For one, xilvar's solution fails if the file isn't a JPEG or if there is no exif data present. And for the other, it always rotated 180 degrees instead of the appropriate amount. ``` imp...
PIL thumbnail is rotating my image?
4,228,530
25
2010-11-19T19:14:27Z
20,982,363
19
2014-01-07T21:33:38Z
[ "python", "python-imaging-library" ]
I'm attempting to take large (huge) images (from a digital camera), and convert them into something that I can display on the web. This seems straightforward, and probably should be. However, when I attempt to use PIL to create thumbnail versions, if my source image is taller than it is wide, the resulting image is rot...
Here's a version that works for all 8 orientations: ``` def flip_horizontal(im): return im.transpose(Image.FLIP_LEFT_RIGHT) def flip_vertical(im): return im.transpose(Image.FLIP_TOP_BOTTOM) def rotate_180(im): return im.transpose(Image.ROTATE_180) def rotate_90(im): return im.transpose(Image.ROTATE_90) def rotate_270(...
PIL thumbnail is rotating my image?
4,228,530
25
2010-11-19T19:14:27Z
30,462,851
9
2015-05-26T15:30:14Z
[ "python", "python-imaging-library" ]
I'm attempting to take large (huge) images (from a digital camera), and convert them into something that I can display on the web. This seems straightforward, and probably should be. However, when I attempt to use PIL to create thumbnail versions, if my source image is taller than it is wide, the resulting image is rot...
Feeling compelled to share my version, which is functionally identical to ones suggested in other answers, yet is, in my opinion, cleaner: ``` def image_transpose_exif(im): exif_orientation_tag = 0x0112 # contains an integer, 1 through 8 exif_transpose_sequences = [ # corresponding to the following []...
Python: Test if an argument is an integer
4,228,757
3
2010-11-19T19:43:43Z
4,228,776
7
2010-11-19T19:46:42Z
[ "python", "validation", "parameters" ]
I want to write a python script that takes 3 parameters. The first parameter is a string, the second is an integer, and the third is also an integer. I want to put conditional checks at the start to ensure that the proper number of arguments are provided, and they are the right type before proceeding. I know we can u...
If you're running Python 2.7, try importing [argparse](http://www.python.org/dev/peps/pep-0389/). Python 3.2 will also use it, and it is the new preferred way to parse arguments. This sample code from the Python [documentation page](http://docs.python.org/dev/library/argparse.html) takes in a list of ints and finds ei...
Python: Test if an argument is an integer
4,228,757
3
2010-11-19T19:43:43Z
4,228,789
9
2010-11-19T19:47:54Z
[ "python", "validation", "parameters" ]
I want to write a python script that takes 3 parameters. The first parameter is a string, the second is an integer, and the third is also an integer. I want to put conditional checks at the start to ensure that the proper number of arguments are provided, and they are the right type before proceeding. I know we can u...
[str.isdigit()](http://docs.python.org/library/stdtypes.html#str.isdigit) can be used to test if a string is comprised solely of numbers.
Python: Test if an argument is an integer
4,228,757
3
2010-11-19T19:43:43Z
4,229,685
9
2010-11-19T21:47:41Z
[ "python", "validation", "parameters" ]
I want to write a python script that takes 3 parameters. The first parameter is a string, the second is an integer, and the third is also an integer. I want to put conditional checks at the start to ensure that the proper number of arguments are provided, and they are the right type before proceeding. I know we can u...
More generally, you can use `isinstance` to see if something is an instance of a class. Obviously, in the case of script arguments, everything is a string, but if you are receiving arguments to a function/method and want to check them, you can use: ``` def foo(bar): if not isinstance(bar, int): bar = int(...
Creating a 2d matrix in python
4,230,000
12
2010-11-19T22:37:26Z
4,230,008
21
2010-11-19T22:38:29Z
[ "python", "list" ]
I create a 6x5 2d array, initially with just None in each cell. I then read a file and replace the Nones with data as I read them. I create the empty array first because the data is in an undefined order in the file I'm reading. My first attempt I did this: ``` x = [[None]*5]*6 ``` which resulted in some weird errors...
Using nested comprehension lists : ``` x = [[None for _ in range(5)] for _ in range(6)] ```
Creating a 2d matrix in python
4,230,000
12
2010-11-19T22:37:26Z
4,230,088
17
2010-11-19T22:49:57Z
[ "python", "list" ]
I create a 6x5 2d array, initially with just None in each cell. I then read a file and replace the Nones with data as I read them. I create the empty array first because the data is in an undefined order in the file I'm reading. My first attempt I did this: ``` x = [[None]*5]*6 ``` which resulted in some weird errors...
What's going on here is that the line ``` x = [[None]*5]*6 ``` expands out to ``` x = [[None, None, None, None, None, None]]*6 ``` At this point you have a list with 6 different references to the singleton `None`. You also have a list with a reference to the inner list as it's first and only entry. When you multipl...
python generators duplicates
4,230,063
4
2010-11-19T22:47:48Z
4,230,131
9
2010-11-19T22:55:33Z
[ "python" ]
How do I either avoid adding duplicate entries into a generator or remove them once there are already there? If I should be using something else, please advice.
If the values are hashable, the simplest, dumbest way to remove duplicates is to use a `set`: ``` values = mygenerator() unique_values = set(values) ``` But watch out: sets don't remember what order the values were originally in. So this scrambles the sequence. The function below might be better than `set` for your ...
Is there a better way to do this python code?
4,230,689
6
2010-11-20T01:10:08Z
4,230,733
9
2010-11-20T01:21:22Z
[ "python" ]
Looking at this snippet of python code I wrote: ``` return map(lambda x: x[1], filter(lambda x: x[0] == 0b0000, my_func(i) ) ) ``` (Hoping it's self-explanatory) I'm wondering if python has a better way to do it? I learned python several months ago, wrote a ...
I think you want a list comprehension: ``` [x[1] for x in my_func(i) if x[0] == 0] ``` List comprehensions are an extremely common Python idiom.
how to execute a python script file with an argument from inside another python script file
4,230,725
12
2010-11-20T01:19:50Z
4,230,752
29
2010-11-20T01:27:47Z
[ "python" ]
my problem is that I want to execute a python file with an argument from inside another python file to get the returned values.... I don't know if I've explained it well... example: from the shell I execute this: ``` getCameras.py "path_to_the_scene" ``` and this return me a list of cameras.... so how c...
The best answer is **don't**. Write your getCameras.py as ``` import stuff1 import stuff2 import sys def main(arg1, arg2): # do whatever and return 0 for success and an # integer x, 1 <= x <= 256 for failure if __name__=='__main__': sys.exit(main(sys.argv[1], sys.argv[2])) ``` From your other script, ...
how to execute a python script file with an argument from inside another python script file
4,230,725
12
2010-11-20T01:19:50Z
4,231,444
8
2010-11-20T05:56:37Z
[ "python" ]
my problem is that I want to execute a python file with an argument from inside another python file to get the returned values.... I don't know if I've explained it well... example: from the shell I execute this: ``` getCameras.py "path_to_the_scene" ``` and this return me a list of cameras.... so how c...
First off, I agree with others that you should edit your code to separate the logic from the command line argument handling. But in cases where you're using other libraries and don't want to mess around editing them, it's still useful to know how to do equivalent command line stuff from within Python. The solution i...
why am I getting IOError: (9, 'Bad file descriptor') error while making print statements?
4,230,855
15
2010-11-20T02:16:24Z
4,230,866
21
2010-11-20T02:19:08Z
[ "python", "windows", "service" ]
I am running a python2.5 script on a windows 2003 server as a service. I am getting this error for simple print statments: ``` IOError: (9, 'Bad file descriptor') ``` I deleted all the print statements because they were only used for development purposes, but I am unsure why a print statement would cause me any greif...
You can't print because `sys.stdout` is not available when not running as a console session. Instead of using `print` statements you can consider using the `logging` module so you can set the loglevel and write all critical things to the system event log. --- It should be noted that you can still get it to work (or ...
Get IP address in Google App Engine + Python
4,231,077
23
2010-11-20T03:32:56Z
4,231,085
26
2010-11-20T03:34:14Z
[ "python", "google-app-engine" ]
I'm looking for the equivalent of `<?php $_SERVER['REMOTE_ADDR'] ?>` in Google App Engine and Python. Thanks!
Try with: ``` os.environ["REMOTE_ADDR"] ``` or with the [Request Class variable](http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_remote_addr): ``` class MyRequestHandler(webapp.RequestHandler): def get(self): ip = self.request.remote_addr ```
Get IP address in Google App Engine + Python
4,231,077
23
2010-11-20T03:32:56Z
4,231,134
24
2010-11-20T03:52:45Z
[ "python", "google-app-engine" ]
I'm looking for the equivalent of `<?php $_SERVER['REMOTE_ADDR'] ?>` in Google App Engine and Python. Thanks!
I slapped a quick and dirty example together based on the tutorial. It's been tested on my local appengine sdk. You should be able to adapt it to your needs: ``` from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db class Log(db.Model): ...
Python - NumPy - tuples as elements of an array
4,231,190
4
2010-11-20T04:18:42Z
4,231,852
7
2010-11-20T08:25:02Z
[ "python", "arrays", "numpy", "linear-algebra" ]
I'm a CS major in university working on a programming project for my Calc III course involving singular-value decomposition. The idea is basically to convert an image of m x n dimensions into an m x n matrix wherein each element is a tuple representing the color channels (r, g, b) of the pixel at point (m, n). I'm usin...
Instead of setting the array element type to 'O' (object) you should set it to a tuple. See [the SciPy manual](http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html) for some examples. In your case, easiest is to use something like ``` a = zeros((ph,pw), dtype=(float,3)) ``` Assuming your RGB values a...
Redirect user in Python + Google App Engine
4,231,254
6
2010-11-20T04:39:09Z
4,231,265
13
2010-11-20T04:44:02Z
[ "python", "google-app-engine", "redirect" ]
I'm trying to do a simple redirection after logging the user. I thought I could use the print "Location:..." method but that doesn't seem to do the trick. ``` class MainPage(webapp.RequestHandler): def get(self): ip = self.request.remote_addr log = Log() log.ip_address = ip log.put...
[`RequestHandler`](http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html) has a [`redirect()`](http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html#RequestHandler_redirect) method that you can use. It takes two parameters, the first one being the url to redirec...
Zip and apply a list of functions over a list of values in Python
4,231,345
13
2010-11-20T05:15:10Z
4,231,350
18
2010-11-20T05:18:32Z
[ "python" ]
Is there idiomatic and/or elegant Python for zipping **and applying** a list of functions over a list of values? For example, suppose you have a list of functions: ``` functions = [int, unicode, float, lambda x: '~' + x + '~'] ``` and a list of values: ``` values = ['33', '\xc3\xa4', '3.14', 'flange'] ``` Is there...
``` [x(y) for x, y in zip(functions, values)] ```
Zip and apply a list of functions over a list of values in Python
4,231,345
13
2010-11-20T05:15:10Z
4,231,439
14
2010-11-20T05:54:15Z
[ "python" ]
Is there idiomatic and/or elegant Python for zipping **and applying** a list of functions over a list of values? For example, suppose you have a list of functions: ``` functions = [int, unicode, float, lambda x: '~' + x + '~'] ``` and a list of values: ``` values = ['33', '\xc3\xa4', '3.14', 'flange'] ``` Is there...
These solutions seem overly complicated: `map` already zips its arguments: ``` map(lambda x,y:x(y), functions, values) ``` Or, if you prefer the iterator version: ``` from itertools import imap imap(lambda x,y:x(y), functions, values) ```
pyparsing isn't nesting list ... why?
4,231,349
4
2010-11-20T05:18:22Z
4,231,558
8
2010-11-20T06:51:34Z
[ "python", "pyparsing" ]
For some reason, pyparsing isn't nesting the list for my string: ``` rank = oneOf("2 3 4 5 6 7 8 9 T J Q K A") suit = oneOf("h c d s") card = rank + Optional(suit) suit_filter = oneOf("z o") hand = card + card + Optional(suit_filter) greater = Literal("+") through = Literal("-") series = hand + Optional(greater | th...
Pyparsing isn't grouping these tokens because you didn't tell it to. Pyparsing's default behavior is to simply string together all matched tokens into a single list. To get grouping of your tokens, wrap the expressions in your parser that are to be grouped in a pyparsing `Group` expression. In your case, change `series...
how to insert None values as null into postgresql db using Python
4,231,491
5
2010-11-20T06:21:50Z
4,231,583
16
2010-11-20T06:59:29Z
[ "python", "postgresql" ]
I would like to know if there is a good practice for entering null key values to a postgresql database when a variable is None in Python. I am trying to run this query: ``` mycursor.execute('insert into products (user_id, city_id, product_id, quantity, price) values (%i, %i, %i, %i, %f)' %(user_id, city_id, product_i...
To insert null values to the database you have two options: 1. omit that field from your INSERT statement, or 2. use `None` Also: To guard against SQL-injection you should not use normal string interpolation for your queries. You should pass two (2) arguments to `execute()`, e.g.: ``` mycursor.execute("""INSERT INT...
StringType and NoneType in python3.x
4,232,111
16
2010-11-20T09:48:25Z
4,232,402
14
2010-11-20T11:11:12Z
[ "python", "python-3.x" ]
I have a codebase which uses StringType and NoneType(types module) in the python2.x codebase. On porting to Python3, tests failed as the types module in Python3.x does not have the above mentioned two types. I solved the problem by replacing them with "str" and "None" respectively. I was wondering if there is another ...
Checking None is usually done by calling `obj is None`, while checking for string usually is `isinstance(obj, str)`. In Python 2.x to detect both string and unicode, you could use `isinstance(obj, basestring)`. If you use `2to3`, it's enough, but if you need to have single piece of code working in both Py2 and Py3, yo...
Python metaprogramming: automatically generate member functions
4,232,371
6
2010-11-20T10:59:12Z
4,232,401
7
2010-11-20T11:10:55Z
[ "python", "metaprogramming" ]
How do I write a function that adds a method to a class? I have: ``` class A: def method(self): def add_member(name): self.new_method = def name...? add_member("f1") add_member("f2") ``` In order to answer what I'm trying to do. I'm trying to factor out some pyqt slots. I want...
Here's an real example from your newly posted code: ``` import types def attach_on_sample_slider(obj, base): def on_sample_slider(self, value): self.samples = base**value self.sample_label.setText('%d' % self.samples) # This next line creates a method from the function # The first arg is ...
Signing and verifying data using pycrypto (RSA)
4,232,389
15
2010-11-20T11:07:35Z
4,232,889
15
2010-11-20T13:14:09Z
[ "python", "pycrypto" ]
I am trying to familiarize myself with the pycrypto module, but the lack of clear documentation makes things difficult. To start with, I would like to understand signing and verifying data. Could someone please provide an example for how this would be written?
This is a fleshed-out version of the [example in the documentation:](http://www.dlitz.net/software/pycrypto/doc/#crypto-publickey-public-key-algorithms) ``` import Crypto.Hash.MD5 as MD5 import Crypto.PublicKey.RSA as RSA import Crypto.PublicKey.DSA as DSA import Crypto.PublicKey.ElGamal as ElGamal import Crypto.Util....
Python: BaseHTTPRequestHandler post variables
4,233,218
25
2010-11-20T14:36:48Z
4,233,452
41
2010-11-20T15:25:11Z
[ "python", "http", "post" ]
given the simplest HTTP server, how do I get post variables in a BaseHTTPRequestHandler? ``` from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_POST(self): # post variables?! server = HTTPServer(('', 4444), Handler) server.serve_forever() # test w...
``` def do_POST(self): ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': postvars = cgi.parse_multipart(self.rfile, pdict) elif ctype == 'application/x-www-form-urlencoded': length = int(self.headers.getheader('content-length')) ...
Python: BaseHTTPRequestHandler post variables
4,233,218
25
2010-11-20T14:36:48Z
13,330,449
15
2012-11-11T10:50:30Z
[ "python", "http", "post" ]
given the simplest HTTP server, how do I get post variables in a BaseHTTPRequestHandler? ``` from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_POST(self): # post variables?! server = HTTPServer(('', 4444), Handler) server.serve_forever() # test w...
I tried to edit the post and got rejected, so there's my version of this code that should work on Python 2.7 and 3.2: ``` from sys import version as python_version from cgi import parse_header, parse_multipart if python_version.startswith('3'): from urllib.parse import parse_qs from http.server import BaseHTT...
Sort a list by multiple attributes?
4,233,476
134
2010-11-20T15:30:53Z
4,233,482
241
2010-11-20T15:32:01Z
[ "python", "sorting" ]
I have a list of lists: ``` [[12, 'tall', 'blue', 1], [2, 'short', 'red', 9], [4, 'tall', 'blue', 13]] ``` If I wanted to sort by one element, say the tall/short element, I could do it via `s = sorted(s, key = itemgetter(1))`. If I wanted to sort by *both* tall/short and colour, I could do the sort twice, once for e...
A key can be a function that returns a tuple: ``` s = sorted(s, key = lambda x: (x[1], x[2])) ``` Or you can achieve the same using `itemgetter`: ``` import operator s = sorted(s, key = operator.itemgetter(1, 2)) ``` And notice that here you can use `sort` instead of using `sorted` and then reassigning: ``` s.sort...
Sort a list by multiple attributes?
4,233,476
134
2010-11-20T15:30:53Z
36,783,084
7
2016-04-22T01:20:24Z
[ "python", "sorting" ]
I have a list of lists: ``` [[12, 'tall', 'blue', 1], [2, 'short', 'red', 9], [4, 'tall', 'blue', 13]] ``` If I wanted to sort by one element, say the tall/short element, I could do it via `s = sorted(s, key = itemgetter(1))`. If I wanted to sort by *both* tall/short and colour, I could do the sort twice, once for e...
I'm not sure if this is the most pythonic method ... I had a list of tuples that needed sorting 1st by descending integer values and 2nd alphabetically. This required reversing the integer sort but not the alphabetical sort. Here was my solution: (on the fly in an exam btw, I was not even aware you could 'nest' sorted ...
Permutations of a list of lists
4,233,742
8
2010-11-20T16:35:00Z
4,233,765
8
2010-11-20T16:39:05Z
[ "python" ]
I have a list like this: ``` l = [['a', 'b', 'c'], ['a', 'b'], ['g', 'h', 'r', 'w']] ``` I want to pick an element from each list and combine them to be a string. For example: 'aag', 'aah', 'aar', 'aaw', 'abg', 'abh' .... However, the length of the list l and the length of each inner list are all unknown before the...
Take a [previous solution](http://stackoverflow.com/questions/2535924/simple-way-to-create-possible-case/2535934#2535934) and use `itertools.product(*l)` instead.
RESTful APIs for Django projects/apps
4,233,754
9
2010-11-20T16:37:48Z
4,234,390
7
2010-11-20T18:55:38Z
[ "python", "django", "api", "rest", "django-piston" ]
What do you prefer when you want to "RESTify" your Django project in Django? I came to the conclusion that there are really three options to do that: * django-piston <http://bitbucket.org/jespern/django-piston/wiki/Home> * django-rest-interface <http://code.google.com/p/django-rest-interface/> * django-restful-resour...
I'm most familiar with django-piston, so I would naturally steer you in that direction. A quick glance at the other two, though, indicates that django-rest-interface does nothing more than expose models as resources, and that django-restful-resources is some guy's one-off attempt at the same. Piston, if I recall corr...
SQLAlchemy declarative one-to-many not defined error
4,234,493
4
2010-11-20T19:19:36Z
4,235,691
10
2010-11-20T23:58:55Z
[ "python", "database", "sqlalchemy" ]
I'm trying to figure how to define a one-to-many relationship using SQLAlchemy's declarative ORM, and trying to get [the example](http://www.sqlalchemy.org/docs/orm/relationships.html) to work, but I'm getting an error that my sub-class can't be found (naturally, because it's declared later...) > InvalidRequestError: ...
Here's how I do it: ``` from sqlalchemy import create_engine from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship engine = create_engine('sqlite://', echo=True) Base = declarative_base(bind=engine) Session = se...
Launch an IPython shell on exception
4,234,612
26
2010-11-20T19:42:32Z
4,505,828
14
2010-12-22T03:06:11Z
[ "python", "debugging", "ipython" ]
Is there a way to launch an IPython shell or prompt when my program runs a line that raises an exception? I'm mostly interested in the context, variables, in the scope (and subscopes) where the exception was raised. Something like Visual Studio's debugging, when an exception is thrown but not caught by anyone, Visual ...
Doing: ``` ipython --pdb -c "%run exceptionTest.py" ``` kicks off the script after IPython initialises and you get dropped into the normal IPython+pdb environment.
Launch an IPython shell on exception
4,234,612
26
2010-11-20T19:42:32Z
10,201,686
7
2012-04-18T01:46:08Z
[ "python", "debugging", "ipython" ]
Is there a way to launch an IPython shell or prompt when my program runs a line that raises an exception? I'm mostly interested in the context, variables, in the scope (and subscopes) where the exception was raised. Something like Visual Studio's debugging, when an exception is thrown but not caught by anyone, Visual ...
[ipdb](http://pypi.python.org/pypi/ipdb) integrates IPython features into pdb. I use the following code to throw my apps into the IPython debugger after an unhanded exception. ``` import sys, ipdb, traceback def info(type, value, tb): traceback.print_exception(type, value, tb) print ipdb.pm() sys.excepth...
Launch an IPython shell on exception
4,234,612
26
2010-11-20T19:42:32Z
14,881,323
17
2013-02-14T18:11:51Z
[ "python", "debugging", "ipython" ]
Is there a way to launch an IPython shell or prompt when my program runs a line that raises an exception? I'm mostly interested in the context, variables, in the scope (and subscopes) where the exception was raised. Something like Visual Studio's debugging, when an exception is thrown but not caught by anyone, Visual ...
Update for [IPython v0.13](http://ipython.org/ipython-doc/rel-0.13.1/interactive/reference.html#automatic-invocation-of-pdb-on-exceptions): ``` import sys from IPython.core import ultratb sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1) ```
How to avoid infinite recursion with super()?
4,235,078
20
2010-11-20T21:22:34Z
4,235,084
38
2010-11-20T21:25:41Z
[ "python", "oop", "multiple-inheritance", "super" ]
I have code like this: ``` class A(object): def __init__(self): self.a = 1 class B(A): def __init__(self): self.b = 2 super(self.__class__, self).__init__() class C(B): def __init__(self): self.c = 3 super(self.__class__, self).__init__() ``` Instantiating B wor...
When instantiating C calls `B.__init__`, `self.__class__` will still be C, so the super() call brings it back to B. When calling super(), use the class names directly. So in B, call `super(B, self)`, rather than `super(self.__class__, self)` (and for good measure, use `super(C, self)` in C). From Python 3, you can jus...