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 |
|---|---|---|---|---|---|---|---|---|---|
Problems POST-ing with pyCurl | 4,154,306 | 3 | 2010-11-11T12:18:01Z | 4,155,460 | 8 | 2010-11-11T14:35:57Z | [
"python",
"webservice-client",
"pycurl"
] | i'm trying to POST a file to a webservice using CURL (that's what I need to use so I can't take twisted or something else). The problem is that when using pyCurl the webservice doesn't receive the file i'm sending, as in the case commented at the bottom of the file. What am I doing wrong in my pyCurl script? Any ideeas... | PyCurl seems to be an orphaned project. It hasn't been updated in two years. I just call command line curl as a subprocess.
```
import subprocess
def curl(*args):
curl_path = '/usr/bin/curl'
curl_list = [curl_path]
for arg in args:
# loop just in case we want to filter args in future.
curl... |
sorted() using Generator Expressions Rather Than Lists | 4,154,571 | 30 | 2010-11-11T12:54:47Z | 4,154,588 | 9 | 2010-11-11T12:56:15Z | [
"python",
"optimization"
] | After seeing the discussion here: [Python - generate the time difference](http://stackoverflow.com/questions/4154116/python-generate-the-time-difference/4154298#4154298) I got curious. I also initially thought that a generator is faster than a list, but when it comes to sorted() I don't know. Is there any benefit to s... | There's no way to sort a sequence without knowing all the elements of the sequence, so any generator passed to `sorted()` is exhausted. |
sorted() using Generator Expressions Rather Than Lists | 4,154,571 | 30 | 2010-11-11T12:54:47Z | 4,154,734 | 28 | 2010-11-11T13:12:46Z | [
"python",
"optimization"
] | After seeing the discussion here: [Python - generate the time difference](http://stackoverflow.com/questions/4154116/python-generate-the-time-difference/4154298#4154298) I got curious. I also initially thought that a generator is faster than a list, but when it comes to sorted() I don't know. Is there any benefit to s... | The first thing `sorted()` does is to convert the data to a list. Basically the first line (after argument validation) of the implementation is
```
newlist = PySequence_List(seq);
```
See also [the full source code version 2.7](http://svn.python.org/view/python/tags/r27/Python/bltinmodule.c?view=markup) and [version ... |
sorted() using Generator Expressions Rather Than Lists | 4,154,571 | 30 | 2010-11-11T12:54:47Z | 4,155,652 | 10 | 2010-11-11T14:52:27Z | [
"python",
"optimization"
] | After seeing the discussion here: [Python - generate the time difference](http://stackoverflow.com/questions/4154116/python-generate-the-time-difference/4154298#4154298) I got curious. I also initially thought that a generator is faster than a list, but when it comes to sorted() I don't know. Is there any benefit to s... | There's a huge benefit. Because sorted doesn't affect the passed in sequence, it has to make a copy of it. If it's making a list from the generator expression, then only one list gets made. If a list comprehension is passed in, then first, that gets built and then `sorted` makes a copy of it to sort.
This is reflected... |
sorted() using Generator Expressions Rather Than Lists | 4,154,571 | 30 | 2010-11-11T12:54:47Z | 4,155,903 | 13 | 2010-11-11T15:15:47Z | [
"python",
"optimization"
] | After seeing the discussion here: [Python - generate the time difference](http://stackoverflow.com/questions/4154116/python-generate-the-time-difference/4154298#4154298) I got curious. I also initially thought that a generator is faster than a list, but when it comes to sorted() I don't know. Is there any benefit to s... | The easiest way to see which is faster is to use [`timeit`](http://docs.python.org/library/timeit.html) and it tells me that it's faster to pass a list rather than a generator:
```
>>> import random
>>> randomlist = range(1000)
>>> random.shuffle(randomlist)
>>> import timeit
>>> timeit.timeit("sorted(x for x in rando... |
Find substring in string but only if whole words? | 4,154,961 | 7 | 2010-11-11T13:37:59Z | 4,155,064 | 14 | 2010-11-11T13:50:57Z | [
"python",
"search",
"string",
"substring"
] | What is an elegant way to look for a string within another string in Python, but only if the substring is within whole words, not part of a word?
Perhaps an example will demonstrate what I mean:
```
string1 = "ADDLESHAW GODDARD"
string2 = "ADDLESHAW GODDARD LLP"
assert string_found(string1, string2) # this is True
s... | You can use [regular expressions](http://docs.python.org/library/re.html) and the word boundary special character `\b` (highlight by me):
> Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so **the end of a word is indicated... |
How to map numbers in range <0;99> to range <-1.0;1.0>? | 4,154,969 | 7 | 2010-11-11T13:38:27Z | 4,154,988 | 18 | 2010-11-11T13:40:43Z | [
"python"
] | So I have a function which always returns a number from range <0;99> (i.e. 0, 1, ... 99 - integers).
What would be the best way to correctly map those numbers to range <-1.0;1.0>?
0 would be -1.0 of course and 99 would be 1.0. How to calculate the numbers between? | Use a linear mapping:
```
y = ((x / 99.0) * 2) - 1
```
How it works:
* Divide by 99: This normalizes the range from [0, 99] to [0, 1].
* Multiply by 2: This increases the range to [0, 2].
* Subtract 1: This is a translation which gives [-1, 1].
You can of course combine the steps ((x / 99.0) \* 2) into a single div... |
How to map numbers in range <0;99> to range <-1.0;1.0>? | 4,154,969 | 7 | 2010-11-11T13:38:27Z | 4,155,197 | 11 | 2010-11-11T14:09:25Z | [
"python"
] | So I have a function which always returns a number from range <0;99> (i.e. 0, 1, ... 99 - integers).
What would be the best way to correctly map those numbers to range <-1.0;1.0>?
0 would be -1.0 of course and 99 would be 1.0. How to calculate the numbers between? | Don't do scaling manually; it takes far too much squinting at the math to figure out what's really intended. Use a helper function.
```
def scale(val, src, dst):
"""
Scale the given value from the scale of src to the scale of dst.
"""
return ((val - src[0]) / (src[1]-src[0])) * (dst[1]-dst[0]) + dst[0]... |
How to display a message box on PyQT4? | 4,155,052 | 11 | 2010-11-11T13:48:05Z | 4,155,232 | 18 | 2010-11-11T14:12:59Z | [
"python",
"pyqt"
] | I'd like a MessageBox to display when I click a button on my simple PyQT application. How can I declare two textboxes and have a MessageBox display with the text from both textboxes?
Here's my code far:
```
import sys
from PyQt4 import QtGui, QtCore
class myWindow(QtGui.QWidget):
def __init__(self, parent=None):... | Since such simple code is a common request, I decided to hack something basic together, here you go:
```
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class AppForm(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.create_main_frame()
def cr... |
Python: CSV write by column rather than row | 4,155,106 | 17 | 2010-11-11T13:58:05Z | 4,155,145 | 17 | 2010-11-11T14:04:18Z | [
"python",
"csv"
] | I have a python script that generates a bunch of data in a while loop. I need to write this data to a CSV file, so it writes by column rather than row.
For example in loop 1 of my script I generate:
```
(1, 2, 3, 4)
```
I need this to reflect in my csv script like so:
```
Result_1 1
Result_2 2
Result_3 3
R... | The reason `csv` doesn't support that is because variable-length lines are not really supported on most filesystems. What you should do instead is collect all the data in lists, then call `zip()` on them to transpose them after.
```
>>> l = [('Result_1', 'Result_2', 'Result_3', 'Result_4'), (1, 2, 3, 4), (5, 6, 7, 8)]... |
How to create a python 2.x package - simple case | 4,155,914 | 19 | 2010-11-11T15:16:38Z | 4,157,080 | 32 | 2010-11-11T17:07:32Z | [
"python",
"packaging",
"python-2.x"
] | Please show the simple and up to date standard way to create a python package for python 2.x
I'd prefer to use pip for installing the package later.
The package should contain a single class:
```
class hello:
def greet(self):
print "hello"
```
One should be able to do the following later:
```
pip install my_... | # Start simple
Simplest one-file package:
```
MyProject/
setup.py
my_package.py
```
Simplest setup.py:
```
from setuptools import setup
setup(name='MyProject',
version='0.1',
author='Your Name',
author_email='your.name@example.com',
license='MIT',
description='Example package t... |
How to pickle a scapy packet? | 4,156,328 | 12 | 2010-11-11T15:57:20Z | 4,312,192 | 7 | 2010-11-30T09:29:03Z | [
"python",
"pickle",
"scapy"
] | I need to pickle a `scapy` packet. Most of the time this works, but sometimes the pickler complains about a function object. As a rule of thumb: ARP packets pickle fine. Some UDP packets are problematic. | My solution (as inspired by the scapy mailing list) is as follows:
```
class PicklablePacket:
"""A container for scapy packets that can be pickled (in contrast
to scapy packets themselves)."""
def __init__(self, pkt):
self.contents = bytes(pkt)
self.time = pkt.time
def __call__(self):
... |
Python Puzzle code review(spoiler) | 4,156,699 | 4 | 2010-11-11T16:30:47Z | 4,157,109 | 7 | 2010-11-11T17:10:47Z | [
"python",
"algorithm"
] | I have been working on the problems presented in [Python Challenge](http://www.pythonchallenge.com/ry). One of the problems asks to sift through a mess of characters and pick out the rarest character/s.
My methodology was to read the characters from a text file, store the characters/occurrence as a key/value pair in a... | # Refactoring: A Walkthrough
I want to walk you through the process of refactoring. Learning to program is not just about knowing the end result, which is what you usually get when you ask a question on Stack Overflow. It's about how to get to that answer yourself. When people post short, dense answers to a question l... |
Why does Python raise TypeError rather than SyntaxError? | 4,157,278 | 36 | 2010-11-11T17:26:50Z | 4,157,321 | 58 | 2010-11-11T17:30:42Z | [
"python"
] | A question purely for curiosity's sake. This is obviously invalid syntax:
```
foo = {}
foo['bar': 'baz']
```
It's obvious what happened, the developer moved a line out of the dictionary definition but didn't change it from the literal dictionary declaration to the assignment syntax (and has been suitably mocked as a ... | Using the colon in an indexing operation [generates a `slice` object](http://stackoverflow.com/questions/2936863/python-implementing-slicing-in-getitem/2936876#2936876), which is not hashable. |
Why does Python raise TypeError rather than SyntaxError? | 4,157,278 | 36 | 2010-11-11T17:26:50Z | 4,158,114 | 19 | 2010-11-11T18:51:21Z | [
"python"
] | A question purely for curiosity's sake. This is obviously invalid syntax:
```
foo = {}
foo['bar': 'baz']
```
It's obvious what happened, the developer moved a line out of the dictionary definition but didn't change it from the literal dictionary declaration to the assignment syntax (and has been suitably mocked as a ... | I just want to add some detail to [Ignacio answer](http://stackoverflow.com/questions/4157278/why-does-python-raise-typeerror-rather-than-syntaxerror/4157321#4157321) (which is great) and that take me some time to understand and for people like me that didn't get it (i may be the only one that didn't get it because i d... |
tuple vs list objects in python | 4,158,361 | 5 | 2010-11-11T19:19:03Z | 4,158,376 | 10 | 2010-11-11T19:20:26Z | [
"python"
] | Can someone explain me this?
```
>>> [] is []
False
>>> () is ()
True
>>> (1,) is (1,)
False
```
I understand that I should use "==" instead of "is"to compare the values, I am just wondering why it is this way? | `is` is based on object identity. I.E., are the left and right the same object?
In all these cases, the objects would ordinarily be different (since you have six separate literals). However, the empty tuples are the same object due to implementation-dependent interning. As you noted, you should never rely on this beha... |
more than 9 subplots in matplotlib | 4,158,367 | 18 | 2010-11-11T19:19:27Z | 4,158,455 | 29 | 2010-11-11T19:29:59Z | [
"python",
"charts",
"matplotlib"
] | Is it possible to get more than 9 subplots in matplotlib?
I am on the subplots command `pylab.subplot(449);` how can I get a `4410` to work?
Thank you very much. | It was easier than I expected, I just did: `pylab.subplot(4,4,10)` and it worked. |
Can I somehow "compile" a python script to work on PC without Python installed? | 4,158,369 | 17 | 2010-11-11T19:19:43Z | 4,158,389 | 10 | 2010-11-11T19:21:24Z | [
"python",
"compilation"
] | So I have a Python script:
```
myscript.py
```
I am executing it like this:
```
python D:\myscript.py
```
However, I must have Python installed and included in the `PATH` environment variable for that to work.
Is it somehow possible to "bundle" Python executable with a Python script so other people will be able to... | You want something like [py2exe](http://www.py2exe.org/). |
Can I somehow "compile" a python script to work on PC without Python installed? | 4,158,369 | 17 | 2010-11-11T19:19:43Z | 4,158,399 | 9 | 2010-11-11T19:22:28Z | [
"python",
"compilation"
] | So I have a Python script:
```
myscript.py
```
I am executing it like this:
```
python D:\myscript.py
```
However, I must have Python installed and included in the `PATH` environment variable for that to work.
Is it somehow possible to "bundle" Python executable with a Python script so other people will be able to... | There are multiple solutions like [py2exe](http://www.py2exe.org/), [cx-freeze](http://cx-freeze.sourceforge.net/) or (only for Mac OS X) [py2app](http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html). |
Can I somehow "compile" a python script to work on PC without Python installed? | 4,158,369 | 17 | 2010-11-11T19:19:43Z | 4,158,642 | 13 | 2010-11-11T19:49:02Z | [
"python",
"compilation"
] | So I have a Python script:
```
myscript.py
```
I am executing it like this:
```
python D:\myscript.py
```
However, I must have Python installed and included in the `PATH` environment variable for that to work.
Is it somehow possible to "bundle" Python executable with a Python script so other people will be able to... | Here is one way to do it (for Windows, using `py2exe`).
First, install the [`py2exe`](http://www.py2exe.org/) on your Windows box.
Then create a python script named `compile.py`, like this:
```
import sys
from distutils.core import setup
import py2exe
entry_point = sys.argv[1]
sys.argv.pop()
sys.argv.append('py2exe... |
Can I somehow "compile" a python script to work on PC without Python installed? | 4,158,369 | 17 | 2010-11-11T19:19:43Z | 4,160,462 | 7 | 2010-11-12T00:01:41Z | [
"python",
"compilation"
] | So I have a Python script:
```
myscript.py
```
I am executing it like this:
```
python D:\myscript.py
```
However, I must have Python installed and included in the `PATH` environment variable for that to work.
Is it somehow possible to "bundle" Python executable with a Python script so other people will be able to... | [PyInstaller](http://www.pyinstaller.org/) has worked well for me, generating reasonably small packages due to its use of upx. Its dependency detection was better than py2exe at the time as well. It seems not to have a lot of recent development and probably doesn't work with 3.x, however.
The source in the repository ... |
Numpy: Concatenating multidimensional and unidimensional arrays | 4,158,388 | 11 | 2010-11-11T19:21:16Z | 4,158,985 | 20 | 2010-11-11T20:32:20Z | [
"python",
"arrays",
"numpy",
"concatenation"
] | I have a 2x2 numpy array :
```
x = array(([[1,2],[4,5]]))
```
which I must merge (or stack, if you wish) with a one-dimensional array :
```
y = array(([3,6]))
```
by adding it to the end of the rows, thus making a 2x3 numpy array that would output like so :
array([[1, 2, 3],
[4, 5, 6]])
now the proposed method fo... | unutbu's answer works in general, but in this case there is also np.column\_stack
```
>>> x
array([[1, 2],
[4, 5]])
>>> y
array([3, 6])
>>> np.column_stack((x,y))
array([[1, 2, 3],
[4, 5, 6]])
``` |
Python: kill or terminate subprocess when timeout | 4,158,502 | 15 | 2010-11-11T19:35:23Z | 6,001,858 | 27 | 2011-05-14T12:34:21Z | [
"python",
"timeout",
"subprocess",
"kill",
"signals"
] | I would like to repeatedly execute a subprocess as fast as possible. However, sometimes the process will take too long, so I want to kill it.
I use signal.signal(...) like below:
```
ppid=pipeexe.pid
signal.signal(signal.SIGALRM, stop_handler)
signal.alarm(1)
.....
def stop_handler(signal, frame):
print 'Stop tes... | You could do something like this:
```
import subprocess as sub
import threading
class RunCmd(threading.Thread):
def __init__(self, cmd, timeout):
threading.Thread.__init__(self)
self.cmd = cmd
self.timeout = timeout
def run(self):
self.p = sub.Popen(self.cmd)
self.p.wa... |
Make the readline method of Python recognize both end-of-line variations? | 4,158,645 | 10 | 2010-11-11T19:49:18Z | 4,158,708 | 17 | 2010-11-11T19:57:57Z | [
"python"
] | I am writing a Python file that needs to read in several files of different types. I am reading the files in line by line with the traditional `for line in f` after using `f = open("file.txt", "r")`.
This doesn't seem to be working for all files. My guess is some files end with different encodings (such as \r\n versus... | Use the universal newline support -- see <http://docs.python.org/library/functions.html#open>
> In addition to the standard fopen()
> values mode may be 'U' or 'rU'. Python
> is usually built with universal
> newline support; supplying 'U' opens
> the file as a text file, but lines may
> be terminated by any of the fo... |
Python - Speed up an A Star Pathfinding Algorithm | 4,159,331 | 28 | 2010-11-11T21:14:12Z | 4,159,367 | 32 | 2010-11-11T21:19:46Z | [
"python",
"algorithm",
"performance",
"a-star"
] | I've coded my first slightly-complex algorithm, an implementation of the [A Star Pathfinding](http://en.wikipedia.org/wiki/A%2a_search_algorithm) algorithm. I followed some [Python.org advice](http://www.python.org/doc/essays/graphs.html) on implementing graphs so a dictionary contains all the nodes each node is linked... | An easy optimization is to use sets instead of lists for the open and closed sets.
```
openSet = set()
closedSet = set()
```
This will make all of the `in` and `not in` tests O(1) instead of O(*n*). |
Python - Speed up an A Star Pathfinding Algorithm | 4,159,331 | 28 | 2010-11-11T21:14:12Z | 4,160,577 | 9 | 2010-11-12T00:23:51Z | [
"python",
"algorithm",
"performance",
"a-star"
] | I've coded my first slightly-complex algorithm, an implementation of the [A Star Pathfinding](http://en.wikipedia.org/wiki/A%2a_search_algorithm) algorithm. I followed some [Python.org advice](http://www.python.org/doc/essays/graphs.html) on implementing graphs so a dictionary contains all the nodes each node is linked... | I would use the sets as have been said, but I would also use a heap to find the minimum element (the one that will be the next `current`). This would require keeping both an openSet and an openHeap, but the memory shouldn't really be a problem. Also, sets insert in O(1) and heaps in O(log N) so they will be fast. The o... |
Python timing - There must be a better way! | 4,160,006 | 3 | 2010-11-11T22:43:06Z | 4,160,029 | 13 | 2010-11-11T22:45:20Z | [
"python",
"performance",
"testing",
"timing"
] | I hope someone can help me out with this.
I'd like to measure sorting algorithms. Here's how I currently do it:
```
M = 1000 # number of executions
N = [1000, 2000, 4000, 16000] # size of the list
L = [100, 1000, 2000,16000] # max element of the list
# timing:
print 'Number of executions: %i' % (M)
print '-'*80
print... | [timeit](http://docs.python.org/library/timeit.html). Best way to time in Python, period. Refactor your algorithms into functions and use `timeit` to test the execution time. |
How do you show a picture in python? | 4,160,082 | 3 | 2010-11-11T22:54:50Z | 4,160,103 | 10 | 2010-11-11T22:57:40Z | [
"python",
"image"
] | I am wondering, is it possible to display images in python? | The easiest way is to use [PIL](http://www.pythonware.com/library/pil/handbook/index.htm) and the [Image.show](http://www.pythonware.com/library/pil/handbook/image.htm) method. This brings up an external viewer program on the image. |
Detect tap with pyaudio from live mic | 4,160,175 | 26 | 2010-11-11T23:09:59Z | 4,160,733 | 74 | 2010-11-12T00:58:12Z | [
"python",
"microphone",
"pyaudio"
] | How would I use pyaudio to detect a sudden tapping noise from a live microphone? | One way I've done it:
* read a block of samples at a time,
say 0.05 seconds worth
* compute the
RMS amplitude of the block (square
root of the average of the squares of
the individual samples)
* if the block's RMS amplitude is greater than a threshold, it's a "noisy block" else it's a "quiet block"
* a sudden ... |
Detect tap with pyaudio from live mic | 4,160,175 | 26 | 2010-11-11T23:09:59Z | 10,669,054 | 10 | 2012-05-19T21:43:00Z | [
"python",
"microphone",
"pyaudio"
] | How would I use pyaudio to detect a sudden tapping noise from a live microphone? | a simplified version of the above code...
```
import pyaudio
import struct
import math
INITIAL_TAP_THRESHOLD = 0.010
FORMAT = pyaudio.paInt16
SHORT_NORMALIZE = (1.0/32768.0)
CHANNELS = 2
RATE = 44100
INPUT_BLOCK_TIME = 0.05
INPUT_FRAMES_PER_BLOCK = int(RATE*INPUT_BLOCK_TIME)
OVERSENSITIVE = 15.0/INPUT_BLOCK_TIME ... |
Creating Dependency Graphs in Python | 4,160,746 | 20 | 2010-11-12T01:00:44Z | 4,160,800 | 19 | 2010-11-12T01:12:57Z | [
"python",
"dependency-management",
"call-flow"
] | I have inherited a huge codebase that I need to make some small changes into. I was wondering if there are utilities that would parse python code and give dependencies between functions, as in if I make changes to a function I want to be sure that I dont break other functions, so if I could see in a graph like diagram ... | * Usually "dependency" is defined for module / package import.
* What you are looking for is a visualizing call flow.
+ <http://pycallgraph.slowchop.com/>
* You can still not guarantee that you will not break functionality :)
* My experience and solution:
Many a times, I found the call flow data overwhelming and ... |
Pattern for a background Twisted server that fills an incoming message queue and empties an outgoing message queue? | 4,161,403 | 3 | 2010-11-12T03:34:03Z | 4,161,580 | 8 | 2010-11-12T04:21:04Z | [
"python",
"background",
"client",
"twisted",
"nonblocking"
] | I'd like to do something like this:
```
twistedServer.start() # This would be a nonblocking call
while True:
while twistedServer.haveMessage():
message = twistedServer.getMessage()
response = handleMessage(message)
twistedServer.sendResponse(response)
doSomeOtherLogic()
```
The key thing I wa... | > The key thing I want to do is run the server in a background thread.
You don't explain why this is key, though. Generally, things like "use threads" are implementation details. Perhaps threads are appropriate, perhaps not, but the actual goal is agnostic on the point. What is your goal? To handle multiple clients co... |
Bootstrapping a web server in Scala | 4,161,460 | 9 | 2010-11-12T03:47:34Z | 4,161,571 | 10 | 2010-11-12T04:19:11Z | [
"python",
"scala"
] | The following is possible using Python:
```
$ apt-get install python
$ easy_install Flask
$ cat > hello.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
$ python hello.py
```
4 commands and 7 lines of code to get a web s... | You might find [Unfiltered](http://unfiltered.databinder.net) worth a look. |
Bootstrapping a web server in Scala | 4,161,460 | 9 | 2010-11-12T03:47:34Z | 4,163,921 | 10 | 2010-11-12T10:57:57Z | [
"python",
"scala"
] | The following is possible using Python:
```
$ apt-get install python
$ easy_install Flask
$ cat > hello.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
$ python hello.py
```
4 commands and 7 lines of code to get a web s... | I know [Max](http://stackoverflow.com/users/152619/max-a) alread [mentioned](http://stackoverflow.com/questions/4161460/bootstrapping-a-web-server-in-scala/4161547#4161547) it, but I couldn't resist pointing out [Scalatra's](https://github.com/scalatra/scalatra) 6 lines hello world:
```
import org.scalatra._
class Sc... |
Bootstrapping a web server in Scala | 4,161,460 | 9 | 2010-11-12T03:47:34Z | 6,432,180 | 10 | 2011-06-21T21:24:31Z | [
"python",
"scala"
] | The following is possible using Python:
```
$ apt-get install python
$ easy_install Flask
$ cat > hello.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
$ python hello.py
```
4 commands and 7 lines of code to get a web s... | This uses the HttpServer class that is built-in in JDK6. Feel free to suggest improvements, I'm new to Scala.
```
package org.test.simplehttpserver
import java.net.InetSocketAddress
import com.sun.net.httpserver.{HttpExchange, HttpHandler, HttpServer}
import collection.mutable.HashMap
abstract class SimpleHttpServer... |
Making C++ pause | 4,161,556 | 2 | 2010-11-12T04:15:22Z | 4,161,596 | 14 | 2010-11-12T04:25:00Z | [
"c++",
"python",
"time",
"sleep"
] | Is there a C++ equivalent to Python's **time.sleep()**? | Use [boost::this\_thread::sleep](http://www.boost.org/doc/libs/1_44_0/doc/html/thread/thread_management.html#thread.thread_management.this_thread.sleep)
```
// sleep for 5 seconds
boost::this_thread::sleep(boost::posix_time::seconds(5));
``` |
Forward declaration of class in Python | 4,162,456 | 28 | 2010-11-12T07:25:36Z | 4,162,505 | 11 | 2010-11-12T07:33:14Z | [
"python"
] | I have some classes looking like this:
```
class Base:
subs = [Sub3,Sub1]
# Note that this is NOT a list of all subclasses!
# Order is also important
class Sub1(Base): pass
class Sub2(Base): pass
class Sub3(Base): pass
...
```
Now, this fails because Sub1 and Sub3 are not defined when Base.subs is. But obvious... | Write a decorator that adds it to the registry in `Base`.
```
class Base(object):
subs = []
@classmethod
def addsub(cls, scls):
cls.subs.append(scls)
...
@Base.addsub
class Sub1(Base):
pass
class Sub2(Base):
pass
@Base.addsub
class Sub3(Base):
pass
``` |
Forward declaration of class in Python | 4,162,456 | 28 | 2010-11-12T07:25:36Z | 4,163,042 | 8 | 2010-11-12T09:09:17Z | [
"python"
] | I have some classes looking like this:
```
class Base:
subs = [Sub3,Sub1]
# Note that this is NOT a list of all subclasses!
# Order is also important
class Sub1(Base): pass
class Sub2(Base): pass
class Sub3(Base): pass
...
```
Now, this fails because Sub1 and Sub3 are not defined when Base.subs is. But obvious... | This is a hybrid version of @Ignacio Vazquez-Abrams and @aaronasterling's answers which preserves the order of the subclasses in the list. Initially the subclass names are manually placed in the `subs` list in the desired order. Then as each subclass is defined, a class decorator causes the corresponding string to be r... |
Python : terminology 'class' VS 'type' | 4,162,578 | 23 | 2010-11-12T07:46:38Z | 4,162,755 | 10 | 2010-11-12T08:21:38Z | [
"python",
"class",
"types",
"terminology"
] | Just a simple question : when should I use the term 'class', and when should I use the term 'type' in Python ?
* is 'class' only for user-defined types, and 'type' for built-in types ?
* or now that [everything is a type](http://www.python.org/download/releases/2.2/descrintro/) ... should I use always 'type' even for ... | It is more or less historical: [they used to be different](http://www.python.org/download/releases/2.2/descrintro/) a long time ago, which has no practical implications anymore.
**Edit:** I use "`class`" when referring to concrete implementations and "`type`" in a more informal way, when speaking about high level data... |
Python and character normalization | 4,162,603 | 16 | 2010-11-12T07:52:02Z | 4,162,694 | 35 | 2010-11-12T08:10:23Z | [
"python",
"django",
"utf-8",
"diacritics",
"transliteration"
] | Hello
I retrieve text based utf8 data from a foreign source which contains special chars such as `u"ıöüç"` while I want to normalize them to English such as `"ıöüç"` -> `"iouc"` . What would be the best way to achieve this ? | I recommend using [Unidecode module](http://pypi.python.org/pypi/Unidecode/):
```
>>> from unidecode import unidecode
>>> unidecode(u'ıöüç')
'iouc'
```
Note how you feed it a unicode string and it outputs a byte string. The output is guaranteed to be ASCII. |
Django request get parameters | 4,162,625 | 34 | 2010-11-12T07:55:11Z | 4,162,731 | 40 | 2010-11-12T08:16:25Z | [
"python",
"django",
"django-models",
"django-views"
] | In a Django request I have the following
```
POST:<QueryDict: {u'section': [u'39'], u'MAINS': [u'137']}>
```
How to get the values of `section` and `MAINS`?
```
if request.method == 'GET':
qd = request.GET
elif request.method == 'POST':
qd = request.POST
section_id = qd.__getitem__('section'... | You can use `[]` to extract values from a `QueryDict` object like you would any ordinary dictionary.
```
# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]
# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]
# HTTP POST and HTTP GET variables (D... |
Django request get parameters | 4,162,625 | 34 | 2010-11-12T07:55:11Z | 4,162,775 | 113 | 2010-11-12T08:26:05Z | [
"python",
"django",
"django-models",
"django-views"
] | In a Django request I have the following
```
POST:<QueryDict: {u'section': [u'39'], u'MAINS': [u'137']}>
```
How to get the values of `section` and `MAINS`?
```
if request.method == 'GET':
qd = request.GET
elif request.method == 'POST':
qd = request.POST
section_id = qd.__getitem__('section'... | You may also use:
```
request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137]
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]
```
Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an excepti... |
python: single vs double quotes in JSON | 4,162,642 | 46 | 2010-11-12T08:00:37Z | 4,162,651 | 86 | 2010-11-12T08:02:34Z | [
"python",
"json"
] | My code:
```
import simplejson as json
s = "{'username':'dfdsfdsf'}" #1
#s = '{"username":"dfdsfdsf"}' #2
j = json.loads(s)
```
`#1` definition is wrong
`#2` definition is right
I was heard that in python that single double quote can be interchangable, can anyone explain this for me? | [JSON syntax](http://www.json.org/) is not Python syntax. JSON requires double quotes for its strings. |
python: single vs double quotes in JSON | 4,162,642 | 46 | 2010-11-12T08:00:37Z | 8,710,579 | 13 | 2012-01-03T10:07:00Z | [
"python",
"json"
] | My code:
```
import simplejson as json
s = "{'username':'dfdsfdsf'}" #1
#s = '{"username":"dfdsfdsf"}' #2
j = json.loads(s)
```
`#1` definition is wrong
`#2` definition is right
I was heard that in python that single double quote can be interchangable, can anyone explain this for me? | You can dump JSON with double quote by:
```
from json import dumps
#mixing single and double quotes
data = {'jsonKey': 'jsonValue',"title": "hello world"}
jsonString = json.dumps(data)
#get string with all double quotes
``` |
python: single vs double quotes in JSON | 4,162,642 | 46 | 2010-11-12T08:00:37Z | 21,154,138 | 30 | 2014-01-16T05:40:05Z | [
"python",
"json"
] | My code:
```
import simplejson as json
s = "{'username':'dfdsfdsf'}" #1
#s = '{"username":"dfdsfdsf"}' #2
j = json.loads(s)
```
`#1` definition is wrong
`#2` definition is right
I was heard that in python that single double quote can be interchangable, can anyone explain this for me? | you can use `ast.literal_eval()`
```
>>> import ast
>>> s = "{'username':'dfdsfdsf'}"
>>> ast.literal_eval(s)
{'username': 'dfdsfdsf'}
``` |
How to read two inputs separated by space in a single line? | 4,162,815 | 3 | 2010-11-12T08:32:42Z | 4,162,830 | 12 | 2010-11-12T08:35:35Z | [
"python"
] | I want to read two input values. First value should be an integer and the second value should be a float.
I saw [python: read two variables in a single line](http://stackoverflow.com/questions/1588058/python-read-two-variables-in-a-single-line), but it applies only if both the values are of same type. Do I have any ot... | Like this:
```
In [20]: a,b = raw_input().split()
12 12.2
In [21]: a = int(a)
Out[21]: 12
In [22]: b = float(b)
Out[22]: 12.2
```
You can't do this in a one-liner (or at least not without some super duper extra hackz0r skills -- or semicolons), but python is not made for one-liners. |
Create an object using Python's C API | 4,163,018 | 22 | 2010-11-12T09:06:28Z | 4,163,055 | 24 | 2010-11-12T09:10:44Z | [
"python",
"c",
"python-c-api",
"python-extensions",
"python-embedding"
] | Say I have my object layout defined as:
```
typedef struct {
PyObject_HEAD
// Other stuff...
} pyfoo;
```
...and my type definition:
```
static PyTypeObject pyfoo_T = {
PyObject_HEAD_INIT(NULL)
// ...
pyfoo_new,
};
```
How do I create a new instance of `pyfoo` somewhere within my C extension? | Call [PyObject\_New()](http://docs.python.org/c-api/allocation.html#PyObject_New), followed by [PyObject\_Init()](http://docs.python.org/c-api/allocation.html#PyObject_Init).
**EDIT:** The best way is to [call](http://docs.python.org/c-api/object.html#PyObject_Call) the class object, just like in Python itself:
```
/... |
Python vs PHP speed | 4,163,070 | 9 | 2010-11-12T09:14:34Z | 4,163,192 | 11 | 2010-11-12T09:29:39Z | [
"php",
"python"
] | I want to solve a problem from [Project Euler](http://en.wikipedia.org/wiki/Project_Euler) (BTW, problem 25), and I found a solution in Python:
```
fibonacci = 1
old1 = 0
old2 = 1
limit = 1000
i = 1
while len(str(fibonacci)) < limit:
fibonacci = old1 + old2
old1 = old2
old2 = fibonacci
i = i + 1
pri... | Definitely, the PHP is going into an infinite loop. There's no way it could be taking that long if there wasn't something wrong...
I don't think counting the digits of these numbers with `strlen` is going to work in PHP. PHP is dealing with the numbers in scientific notation, in lower precision than Python.
I added d... |
QTreeView with drag and drop support in PyQt | 4,163,740 | 11 | 2010-11-12T10:36:23Z | 4,170,541 | 14 | 2010-11-13T02:02:48Z | [
"python",
"drag-and-drop",
"pyqt",
"qtreeview"
] | In PyQt 4 I would like to create a QTreeView with possibility to reorganize its structure with drag and drop manipulation.
I have implemented my own model(QAbstractItemModel) for QTreeView so my QTreeView properly displays the data.
Now I would like to add drag and drop support for tree's nodes to be able to move a no... | You can enable drag and drop support for tree view items by setting *QtGui.QAbstractItemView.InternalMove* into the [dragDropMode](http://doc.trolltech.com/4.7/qabstractitemview.html#dragDropMode-prop) property of the treeview control. Also take a look at the documentation here [Using drag & drop with item views](http:... |
HTML presentation slides with Python syntax highlighting | 4,163,894 | 12 | 2010-11-12T10:54:13Z | 4,164,032 | 12 | 2010-11-12T11:13:56Z | [
"python",
"html",
"syntax-highlighting",
"presentation"
] | I'd like to create slides for my presentation. My presentation will contain these: slide title, bullet points, code snippets (in a monospace font), some code lines highlighted as bold, Python code snippets (with syntax highlighting).
I need an application or tool which can generate such slides in HTML (or HTML5), so w... | Try one of the following:
1. Restructured text with S5
<http://meyerweb.com/eric/tools/s5/>
<http://docutils.sourceforge.net/docs/user/slide-shows.html>
If you install [docutils](http://docutils.sourceforge.net/) (snapshot is preferred), you will get rst2s5.py in the tools folder.
2. Bruce, The Presentatio... |
python: is it possible to attach a console into a running process | 4,163,964 | 49 | 2010-11-12T11:04:00Z | 4,164,088 | 27 | 2010-11-12T11:22:44Z | [
"python"
] | I just want to see the state of the process, is it possible to attach a console into the process, so I can invoke functions inside the process and see some of the global variables.
It's better the process is running without being affected(of course performance can down a little bit) | If you have access to the program's source-code, you can add this functionality relatively easily.
See [Recipe 576515](http://code.activestate.com/recipes/576515/): `Debugging a running python process by interrupting and providing an interactive prompt (Python)`
To quote:
> This provides code to allow any python
> p... |
python: is it possible to attach a console into a running process | 4,163,964 | 49 | 2010-11-12T11:04:00Z | 4,164,424 | 7 | 2010-11-12T12:07:37Z | [
"python"
] | I just want to see the state of the process, is it possible to attach a console into the process, so I can invoke functions inside the process and see some of the global variables.
It's better the process is running without being affected(of course performance can down a little bit) | Why not simply using the [pdb](http://docs.python.org/library/pdb.html) module? It allows you to stop a script, inspect elements values, and execute the code line by line. And since it is built upon the Python interpreter, it also provides the features provided by the classic interpreter. To use it, just put these 2 li... |
python: is it possible to attach a console into a running process | 4,163,964 | 49 | 2010-11-12T11:04:00Z | 4,693,529 | 41 | 2011-01-14T16:45:23Z | [
"python"
] | I just want to see the state of the process, is it possible to attach a console into the process, so I can invoke functions inside the process and see some of the global variables.
It's better the process is running without being affected(of course performance can down a little bit) | This will interrupt your process (unless you start it in a thread), but you can use the `code` module to start a Python console:
```
import code
code.interact()
```
This will block until the user exits the interactive console by executing `exit()`.
The `code` module is available in at least Python v2.6, probably oth... |
python: is it possible to attach a console into a running process | 4,163,964 | 49 | 2010-11-12T11:04:00Z | 35,113,682 | 7 | 2016-01-31T12:09:30Z | [
"python"
] | I just want to see the state of the process, is it possible to attach a console into the process, so I can invoke functions inside the process and see some of the global variables.
It's better the process is running without being affected(of course performance can down a little bit) | Use [pyrasite-shell](http://pyrasite.readthedocs.org/en/latest/Shell.html). I can't believe it works so well, but it does. "**Give it a pid, get a shell**".
```
$ sudo pip install pyrasite
$ echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope # If YAMA activated, see below.
$ pyrasite-shell 16262
Pyrasite Shell 2.0
C... |
Most appropriate data structure (Python) | 4,164,303 | 9 | 2010-11-12T11:52:13Z | 4,164,401 | 7 | 2010-11-12T12:04:19Z | [
"python",
"arrays",
"data-structures",
"dictionary"
] | I'm new to Python and have what is probably a very basic question about the 'best' way to store data in my code. Any advice much appreciated!
I have a long .csv file in the following format:
```
Scenario,Year,Month,Value
1,1961,1,0.5
1,1961,2,0.7
1,1961,3,0.2
etc.
```
My scenario values run from 1 to 100, year goes ... | I'd use a dict of tuples. Simple, fast, and a hash-table look-up to retrieve a single value:
```
import csv
reader = csv.reader(open('data.csv', 'rb'))
header = reader.next()
data = {}
for row in reader:
key = tuple([int(v) for v in row[:-1]])
val = row[-1]
data[key] = float(val)
# Retrieve a value
prin... |
Tuning mod_wsgi in daemon mode | 4,165,213 | 17 | 2010-11-12T13:43:59Z | 4,170,445 | 11 | 2010-11-13T01:34:28Z | [
"python",
"apache",
"mod-wsgi",
"wsgi"
] | I'm running wsgi application on apache mod\_wsgi in daemon mode.
I have these lines in the configuration
```
WSGIDaemonProcess app processes=2 threads=3 display-name=%{GROUP}
WSGIProcessGroup app
```
How do I find the optimal combination/tuning of processes and threads?
**EDIT**:
This link [given in answer bellow] ... | You might get more information on ServerFault as well. For example: <http://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes>
This is another good resource for the topic: <http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading#The_mod_wsgi_Daemon_Processes>
which briefly descr... |
How to efficiently manage frequent schema changes using sqlalchemy? | 4,165,452 | 32 | 2010-11-12T14:08:55Z | 4,165,496 | 12 | 2010-11-12T14:14:32Z | [
"python",
"sqlalchemy",
"pylons",
"data-migration",
"migrate"
] | I'm programming a web application using sqlalchemy. Everything was smooth during the first phase of development when the site was not in production. I could easily change the database schema by simply deleting the old sqlite database and creating a new one from scratch.
Now the site is in production and I need to pres... | What we do.
1. Use "major version"."minor version" identification of your applications. Major version is the schema version number. The major number is no some random "enough new functionality" kind of thing. It's a formal declaration of compatibility with database schema.
Release 2.3 and 2.4 both use schema versi... |
How to efficiently manage frequent schema changes using sqlalchemy? | 4,165,452 | 32 | 2010-11-12T14:08:55Z | 4,165,611 | 12 | 2010-11-12T14:28:09Z | [
"python",
"sqlalchemy",
"pylons",
"data-migration",
"migrate"
] | I'm programming a web application using sqlalchemy. Everything was smooth during the first phase of development when the site was not in production. I could easily change the database schema by simply deleting the old sqlite database and creating a new one from scratch.
Now the site is in production and I need to pres... | Use [sqlalchemy-migrate](http://code.google.com/p/sqlalchemy-migrate/).
It is designed to support an agile approach to database design, and make it easier to keep development and production databases in sync, as schema changes are required. It makes schema versioning easy.
Think of it as a version control for your da... |
How to efficiently manage frequent schema changes using sqlalchemy? | 4,165,452 | 32 | 2010-11-12T14:08:55Z | 13,467,138 | 25 | 2012-11-20T05:32:09Z | [
"python",
"sqlalchemy",
"pylons",
"data-migration",
"migrate"
] | I'm programming a web application using sqlalchemy. Everything was smooth during the first phase of development when the site was not in production. I could easily change the database schema by simply deleting the old sqlite database and creating a new one from scratch.
Now the site is in production and I need to pres... | [Alembic](https://pypi.python.org/pypi/alembic) is a new database migrations tool, written by the author of SQLAlchemy. I've found it much easier to use than sqlalchemy-migrate. It also works seamlessly with Flask-SQLAlchemy.
Auto generate the schema migration script from your SQLAlchemy models:
```
alembic revision ... |
Is this a bug? Variables are identical references to the same string in this example (Python) | 4,165,688 | 8 | 2010-11-12T14:36:55Z | 4,165,753 | 10 | 2010-11-12T14:44:18Z | [
"python",
"string",
"reference"
] | This is for Python 2.6.
I could not figure out why a and b are identical:
```
>>> a = "some_string"
>>> b = "some_string"
>>> a is b
True
```
But if there is a space in the string, they are not:
```
>>> a = "some string"
>>> b = "some string"
>>> a is b
False
```
If this is normal behavior, could someone please ex... | Python may or may not automatically intern strings, which determines whether future instances of the string will share a reference.
If it decides to intern a string, then both will refer to the same string instance. If it doesn't, it'll create two separate strings that happen to have the same contents.
In general, yo... |
Can Java and Python coexist in the same app? | 4,165,824 | 4 | 2010-11-12T14:53:30Z | 4,166,178 | 9 | 2010-11-12T15:31:54Z | [
"java",
"python",
"google-app-engine",
"integration",
"gae-datastore"
] | I need to have a Java instance fetching data directly from the Python's instance datastore. I don't know if that's possible at all. Is the datastore transparent/unique, or each instance (if they can indeed coexist) has its separate datastore?
Suming it up: how can a Java app fetch data from the datastore of a Python ap... | Different versions of an app share a datastore, and AFAIK you can still have a Java version of your app, and Python version, at the same time. It used to be a necessary hack to use features that were implemented in Python but not (yet) in Java, and quite possibly still is.
Of course only one of those versions can be t... |
Beginner question: returning a boolean value from a function in Python | 4,165,933 | 6 | 2010-11-12T15:04:38Z | 4,165,978 | 21 | 2010-11-12T15:09:13Z | [
"python",
"function",
"boolean"
] | I'm trying to get this rock paper scissors game to either return a Boolean value, as in set `player_wins` to True or False, depending on if the player wins, or to refactor this code entirely so that it doesn't use a while loop.
I'm coming from the sysadmin side of the world, so please be gentle if this is written in th... | Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:
```
def rps():
# Code to determine if player wins
if player_wins:
return True
return False
```
Then, just assign a value to the variable outside this functio... |
Python CSV error: line contains NULL byte | 4,166,070 | 63 | 2010-11-12T15:18:55Z | 4,169,762 | 79 | 2010-11-12T22:49:03Z | [
"python",
"csv"
] | I'm working with some CSV files, with the following code:
```
reader = csv.reader(open(filepath, "rU"))
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
```
And one file is throwing this error:
```
file ... | As @S.Lott says, you should be opening your files in 'rb' mode, not 'rU' mode. However that may NOT be causing your current problem. As far as I know, using 'rU' mode would mess you up if there are embedded `\r` in the data, but not cause any other dramas. I also note that you have several files (all opened with 'rU' ?... |
Python CSV error: line contains NULL byte | 4,166,070 | 63 | 2010-11-12T15:18:55Z | 4,338,944 | 11 | 2010-12-02T19:25:51Z | [
"python",
"csv"
] | I'm working with some CSV files, with the following code:
```
reader = csv.reader(open(filepath, "rU"))
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
```
And one file is throwing this error:
```
file ... | I bumped into this problem as well. Using the Python `csv` module, I was trying to read an XLS file created in MS Excel and running into the `NULL byte` error you were getting. I looked around and found the [xlrd](http://pypi.python.org/pypi/xlrd) Python module for reading and formatting data from MS Excel spreadsheet ... |
Python CSV error: line contains NULL byte | 4,166,070 | 63 | 2010-11-12T15:18:55Z | 10,300,007 | 8 | 2012-04-24T14:27:14Z | [
"python",
"csv"
] | I'm working with some CSV files, with the following code:
```
reader = csv.reader(open(filepath, "rU"))
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
```
And one file is throwing this error:
```
file ... | Converting the encoding of the source file from UTF-16 to UTF-8 solve my problem.
[How to convert a file to utf-8 in Python?](http://stackoverflow.com/questions/191359/how-to-convert-a-file-to-utf-8-in-python)
```
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName... |
Python CSV error: line contains NULL byte | 4,166,070 | 63 | 2010-11-12T15:18:55Z | 21,895,911 | 10 | 2014-02-20T00:52:49Z | [
"python",
"csv"
] | I'm working with some CSV files, with the following code:
```
reader = csv.reader(open(filepath, "rU"))
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
```
And one file is throwing this error:
```
file ... | Reading it as UTF-16 was also my problem.
Here's my code that ended up working:
```
f=codecs.open(location,"rb","utf-16")
csvread=csv.reader(f,delimiter='\t')
csvread.next()
for row in csvread:
print row
```
Where location is the directory of your csv file. |
python zipfile module doesn't seem to be compressing my files | 4,166,447 | 34 | 2010-11-12T15:56:53Z | 4,166,505 | 73 | 2010-11-12T16:01:37Z | [
"python",
"compression",
"zipfile"
] | I made a little helper function:
```
import zipfile
def main(archive_list=[],zfilename='default.zip'):
print zfilename
zout = zipfile.ZipFile(zfilename, "w")
for fname in archive_list:
print "writing: ", fname
zout.write(fname)
zout.close()
if __name__ == '__main__':
main()
```
T... | This is because `ZipFile` requires you to specify the compression method. If you don't specify it, it assumes the compression method to be `zipfile.ZIP_STORED`, which only stores the files without compressing them. You need to specify the method to be `zipfile.ZIP_DEFLATED`. You will need to have the `zlib` module inst... |
How can I optimally concat a list of chars to a string? | 4,166,641 | 2 | 2010-11-12T16:14:47Z | 4,166,656 | 10 | 2010-11-12T16:16:19Z | [
"python",
"string"
] | The data:
```
list = ['a','b','x','d','s']
```
I want to create a string str = "abxds". How can I do that?
Right now I am doing something like:
```
str = ""
for i in list:
str = str + i
print(str)
```
I know strings are immutable in Python and this will create 7 string object. And this goes out of my memory wh... | ```
>>> theListOfChars = ['a', 'b', 'x', 'd', 's']
>>> ''.join(theListOfChars)
'abxds'
```
BTW, *don't use `list` or `str` as variable names* as they are names of built-in functions already.
(Also, there is no `char` in Python. A "character" is just a string of length 1. So the `''.join` method works for list of stri... |
Python .join or string concatenation | 4,166,665 | 17 | 2010-11-12T16:17:03Z | 4,166,702 | 23 | 2010-11-12T16:20:18Z | [
"python",
"string-concatenation"
] | I realise that if you have an iterable you should always use `.join(iterable)` instead of `for x in y: str += x`. But if there's only a fixed number of variables that aren't already in an iterable, is using `.join()` still the recommended way?
For example I have
```
user = 'username'
host = 'host'
```
should I do
`... | If you're creating a string like that, you normally want to use string formatting:
```
>>> user = 'username'
>>> host = 'host'
>>> '%s@%s' % (user, host)
'username@host'
```
Python 2.6 added another form, which doesn't rely on operator overloading and has some extra features:
```
>>> '{0}@{1}'.format(user, host)
'us... |
Python .join or string concatenation | 4,166,665 | 17 | 2010-11-12T16:17:03Z | 4,234,224 | 9 | 2010-11-20T18:15:55Z | [
"python",
"string-concatenation"
] | I realise that if you have an iterable you should always use `.join(iterable)` instead of `for x in y: str += x`. But if there's only a fixed number of variables that aren't already in an iterable, is using `.join()` still the recommended way?
For example I have
```
user = 'username'
host = 'host'
```
should I do
`... | I take the question to mean: "Is it ok to do this:"
```
ret = user + '@' + host
```
..and the answer is yes. That is perfectly fine.
You should, of course, be aware of the cool formatting stuff you can do in Python, and you should be aware that for long lists, "join" is the way to go, but for a simple situation like... |
A cleaner/shorter way to solve this problem? | 4,167,009 | 3 | 2010-11-12T16:48:21Z | 4,167,100 | 9 | 2010-11-12T16:57:23Z | [
"python"
] | This exercise is taken from [Google's Python Class](http://code.google.com/intl/de-DE/edu/languages/google-python-class/index.html):
> D. Given a list of numbers, return a list where
> all adjacent == elements have been reduced to a single element,
> so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
> mo... | There is function in [itertools](http://docs.python.org/library/itertools.html#itertools.groupby) that works here:
```
import itertools
[key for key,seq in itertools.groupby([1,1,1,2,2,3,4,4])]
```
You can also write a generator:
```
def remove_adjacent(items):
# iterate the items
it = iter(items)
# get ... |
even numbers python list | 4,167,217 | 3 | 2010-11-12T17:10:43Z | 4,167,239 | 7 | 2010-11-12T17:13:28Z | [
"python",
"list"
] | How do I create a list and only extract or search out the even numbers in that list?
Create a function even\_only(l) that takes a list of integers as its only argument. The
function will return a new list containing all (and only) the elements of l which are evenly divisible by 2. The original list l shall remain unch... | Simplest way would be to do what you posted in a comment -- iterate through the input list to find digits evenly divisible by 2, and add them to the return list if so.
The [`list.append(x)`](http://docs.python.org/tutorial/datastructures.html) function will help you add an item to a list.
Also as mentioned, look at u... |
even numbers python list | 4,167,217 | 3 | 2010-11-12T17:10:43Z | 4,167,267 | 9 | 2010-11-12T17:15:32Z | [
"python",
"list"
] | How do I create a list and only extract or search out the even numbers in that list?
Create a function even\_only(l) that takes a list of integers as its only argument. The
function will return a new list containing all (and only) the elements of l which are evenly divisible by 2. The original list l shall remain unch... | "By hand":
```
def even_only(lst):
evens = []
for number in lst:
if is_even(number):
evens.append(number)
return evens
```
Pythonic:
```
def even_only(iter):
return [x for x in iter if is_even(x)]
```
Since it's homework, you can fill in the `is_even` function. |
Remove duplicates in list of object with Python | 4,169,252 | 8 | 2010-11-12T21:36:39Z | 4,173,307 | 18 | 2010-11-13T15:41:37Z | [
"python",
"mysql",
"sqlobject"
] | I've got a list of objects and I've got a db table full of records. My list of objects has a title attribute and I want to remove any objects with duplicate titles from the list (leaving the original).
Then I want to check if my list of objects has any duplicates of any records in the database and if so, remove those ... | The `set(list_of_objects)` will only remove the duplicates if you know what a duplicate is, that is, you'll need to define a uniqueness of an object.
In order to do that, you'll need to make the object hashable. You need to define both `__hash__` and `__eq__` method, here is how:
<http://docs.python.org/glossary.html... |
Optimizing python for loops | 4,169,828 | 4 | 2010-11-12T23:04:10Z | 4,170,007 | 7 | 2010-11-12T23:43:46Z | [
"python"
] | Here are two programs that naively calculate the number of prime numbers <= n.
One is in Python and the other is in Java.
```
public class prime{
public static void main(String args[]){
int n = Integer.parseInt(args[0]);
int nps = 0;
boolean isp;
for(int i = 1; i <= n; i++){
... | As has been pointed out, straight Python really isn't made for this sort of thing. That the prime checking algorithm is naive is also not the point. However, with two simple things I was able to greatly reduce the time in Python while using the original algorithm.
First, put everything inside of a function, call it `m... |
how to convert a datetime string back to datetime object? | 4,170,655 | 6 | 2010-11-13T02:37:14Z | 4,170,691 | 13 | 2010-11-13T02:48:27Z | [
"python",
"datetime"
] | I am storing the datetime string in the database, now I meet a problem that when I fetch the string from database I need to convert it back to datatime object...
Any easy way to do that?
The string of datetime looks like:
```
2010-11-13 10:33:54.227806
``` | You want datetime.strptime(date\_string, format).
```
from datetime import datetime
datetime.strptime("2010-11-13 10:33:54.227806", "%Y-%m-%d %H:%M:%S.%f")
```
For details on the format string, see <http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior> |
for loop in Python | 4,170,656 | 21 | 2010-11-13T02:37:22Z | 4,170,661 | 43 | 2010-11-13T02:38:57Z | [
"python"
] | In C/C++, I can have the following loop `for(int k = 1; k <= c ; k +=2)`
How do do the same thing in Python?
I can do this `for k in range(1,c):` in Python, which would be identical to `for(int k = 1; k <= c ; k++)` in C/C++. | Try using this:
```
for k in range(1,c+1,2):
``` |
for loop in Python | 4,170,656 | 21 | 2010-11-13T02:37:22Z | 4,171,389 | 16 | 2010-11-13T06:58:29Z | [
"python"
] | In C/C++, I can have the following loop `for(int k = 1; k <= c ; k +=2)`
How do do the same thing in Python?
I can do this `for k in range(1,c):` in Python, which would be identical to `for(int k = 1; k <= c ; k++)` in C/C++. | You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.
```
mylist = [1,2,3]
for item in mylist:
print item
mydict = {1:'one', 2:'two', 3:'three... |
Create random list of integers in Python | 4,172,131 | 52 | 2010-11-13T10:52:21Z | 4,172,186 | 47 | 2010-11-13T11:05:06Z | [
"python",
"list",
"random",
"performance"
] | I'd like to create random list of integers for testing purposes. The distribution of the numbers is not important. The only thing that is count is **time**. I know generating random numbers is a time-consuming task, but there must be a better way.
Here's my current solution:
```
import random
import timeit
# random ... | Not entirely clear what you want, but I would use [numpy.random.randint](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html):
```
import numpy.random as nprnd
t1 = timeit.Timer('[random.randint(0,1000) for r in xrange(10000)]','import random') # v1
### change v2 so that it picks numbers in ... |
Create random list of integers in Python | 4,172,131 | 52 | 2010-11-13T10:52:21Z | 4,172,224 | 26 | 2010-11-13T11:14:09Z | [
"python",
"list",
"random",
"performance"
] | I'd like to create random list of integers for testing purposes. The distribution of the numbers is not important. The only thing that is count is **time**. I know generating random numbers is a time-consuming task, but there must be a better way.
Here's my current solution:
```
import random
import timeit
# random ... | All the random methods end up calling `random.random()` so the best way is to call it directly
```
[int(1000*random.random()) for i in xrange(10000)]
```
eg.
`random.randint` calls `random.randrange`
`random.randrange` has a bunch of overhead to check the range before returning `istart + istep*int(self.random() * ... |
Is it possible to break a long line to multiple lines in Python | 4,172,448 | 183 | 2010-11-13T12:17:04Z | 4,172,465 | 235 | 2010-11-13T12:20:00Z | [
"python"
] | Just like C, you can break a long line into multiple short lines. But in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), if I do this, there will be an indent error... Is it possible? | From [PEP 8 - Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/):
> The preferred way of wrapping long lines is by using Python's implied line
> continuation inside parentheses, brackets and braces. If necessary, you
> can add an extra pair of parentheses around an expression, but sometimes
> using... |
Is it possible to break a long line to multiple lines in Python | 4,172,448 | 183 | 2010-11-13T12:17:04Z | 4,172,466 | 9 | 2010-11-13T12:20:12Z | [
"python"
] | Just like C, you can break a long line into multiple short lines. But in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), if I do this, there will be an indent error... Is it possible? | It works in Python too:
```
>>> 1+\
2+\
3
6
>>> (1+
2+
3)
6
``` |
Is it possible to break a long line to multiple lines in Python | 4,172,448 | 183 | 2010-11-13T12:17:04Z | 4,172,487 | 109 | 2010-11-13T12:26:46Z | [
"python"
] | Just like C, you can break a long line into multiple short lines. But in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), if I do this, there will be an indent error... Is it possible? | There is more than one way to do it.
1). A long statement:
```
>>> def print_something():
print 'This is a really long line,', \
'but we can make it across multiple lines.'
```
2). Using parenthesis:
```
>>> def print_something():
print ('Wow, this also works?',
'I nev... |
python: what does u'{' represent? | 4,172,652 | 3 | 2010-11-13T13:10:11Z | 4,172,656 | 7 | 2010-11-13T13:11:05Z | [
"python"
] | When I print out a value it has a `u` in front of it, I think it is some type notation, what is it? Where I can find a list of such notations? | It meant [*UNICODE string literal*](http://docs.python.org/howto/unicode.html#unicode-literals-in-python-source-code) before [Python 3](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit).
Documentation about all these literal adornments can be found [there](http://docs.pyt... |
My implementation of merging two sorted lists in linear time - what could be improved? | 4,173,225 | 2 | 2010-11-13T15:23:47Z | 4,173,352 | 8 | 2010-11-13T15:54:11Z | [
"python",
"algorithm"
] | Fromg Google's Python Class:
```
E. Given two lists sorted in increasing order, create and return a merged
list of all the elements in sorted order. You may modify the passed in lists.
Ideally, the solution should work in "linear" time, making a single
pass of both lists.
```
Here's my solution:
```
def linear_merge... | Here's a generator approach. You've probably noticed that a whole lot of these "generate lists" can be done well as generator functions. They're very useful: they don't require you to generate the whole list before using data from it, to keep the whole list in memory, and you can use them to directly generate many data... |
String exact match | 4,173,787 | 9 | 2010-11-13T17:32:18Z | 4,173,810 | 25 | 2010-11-13T17:36:09Z | [
"python",
"string"
] | I have a string in which the word "LOCAL" occurs many times. I used the `find()` function to search for this word but it returns another word "Locally" as well. How can I match the word "local" exactly? | For this kind of thing, regexps are very useful :
```
import re
print(re.findall('\\blocal\\b', "Hello, locally local test local."))
// ['local', 'local']
```
\b means word boundary, basically. Can be space, punctuation, etc.
Edit for comment :
```
print(re.sub('\\blocal\\b', '*****', "Hello, LOCAL locally local t... |
String exact match | 4,173,787 | 9 | 2010-11-13T17:32:18Z | 10,466,291 | 7 | 2012-05-05T21:54:34Z | [
"python",
"string"
] | I have a string in which the word "LOCAL" occurs many times. I used the `find()` function to search for this word but it returns another word "Locally" as well. How can I match the word "local" exactly? | Below you can use simple function.
```
def find_word(text, search):
result = re.findall('\\b'+search+'\\b', text, flags=re.IGNORECASE)
if len(result)>0:
return True
else:
return False
```
Using:
```
text = "Hello, LOCAL locally local test local."
search = "local"
if find_word(text, search):
p... |
Anything faster than SELECT DISTINCT item FROM DB? | 4,174,480 | 2 | 2010-11-13T20:17:16Z | 4,174,487 | 9 | 2010-11-13T20:19:12Z | [
"python",
"sql",
"sqlite",
"optimization"
] | Is there any alternative to
```
SELECT DISTINCT item FROM DB
```
I have already tried:
```
SELECT item FROM DB group by item
```
the table isn't so large (30,000 rows) but this command takes almost 6 seconds to complete.
On the other hand, other queries perform very fast (0.2 seconds).
What might be going on? Sugg... | make sure there is an index on the distinct column |
Adding padding to a tkinter widget only on one side | 4,174,575 | 21 | 2010-11-13T20:37:11Z | 4,178,084 | 57 | 2010-11-14T15:15:57Z | [
"python",
"tkinter",
"padding"
] | How can I add padding to a tkinter window, without tkinter centering the widget?
I tried:
```
self.canvas_l = Label(self.master, text="choose a color:", font="helvetica 12")
self.canvas_l.grid(row=9, column=1, sticky=S, ipady=30)
```
and
```
self.canvas_l = Label(self.master, text="choose a color:", font="helveti... | The padding options `padx` and `pady` can take a **2-tuple** that represent the left/right and top/bottom padding.
Here's an example:
```
import tkinter as tk
class MyApp():
def __init__(self):
self.root = tk.Tk()
l1 = tk.Label(text="Hello")
l2 = tk.Label(text="World")
l1.grid(row... |
Is there any way to get a better terminal in emacs? | 4,174,633 | 2 | 2010-11-13T20:51:32Z | 4,174,657 | 10 | 2010-11-13T20:56:59Z | [
"python",
"emacs"
] | I'm using emacs for python, and I'd like to have a nice useable shell in emacs to run an interpreter alongside my editing.
Is there any better emacs shell package out there? The default shell is awful. | You say "terminal" in the title and "shell" in the question, yet you refer to an interpreter. It's all rather confusing.
If you want a better Python interpreter than the standard (although I'd suggest you explore the features of python-mode first); check out [ipython.el](http://ipython.scipy.org/dist/ipython.el) which... |
How to sort a list of lists by a specific index of the inner list? | 4,174,941 | 90 | 2010-11-13T21:54:41Z | 4,174,955 | 133 | 2010-11-13T21:59:49Z | [
"python",
"sorting"
] | I have a list of lists. For example,
```
[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]
```
If I wanted to sort the outer list by the string field of the inner lists, how would you do that in python? | This is a job for [itemgetter](http://docs.python.org/library/operator.html#operator.itemgetter)
```
>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
```
It is also possible to use a lambda function here, h... |
How to sort a list of lists by a specific index of the inner list? | 4,174,941 | 90 | 2010-11-13T21:54:41Z | 4,174,956 | 74 | 2010-11-13T22:00:08Z | [
"python",
"sorting"
] | I have a list of lists. For example,
```
[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]
```
If I wanted to sort the outer list by the string field of the inner lists, how would you do that in python? | in place
```
>>> l = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> l.sort(key=lambda x: x[2])
```
not in place using sorted:
```
>>> sorted(l, key=lambda x: x[2])
``` |
How to sort a list of lists by a specific index of the inner list? | 4,174,941 | 90 | 2010-11-13T21:54:41Z | 15,544,861 | 38 | 2013-03-21T10:25:13Z | [
"python",
"sorting"
] | I have a list of lists. For example,
```
[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]
```
If I wanted to sort the outer list by the string field of the inner lists, how would you do that in python? | Itemgetter lets you to sort by multiple criteria / columns:
```
sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))
``` |
Mixing Python and PHP? | 4,175,419 | 2 | 2010-11-14T00:04:16Z | 4,175,473 | 7 | 2010-11-14T00:20:07Z | [
"php",
"python",
"apache"
] | I have some Python scripts that I run on my desktop now for cutting up files. I want to put them on the web and write a simple front-end in PHP where a user uploads a file and it is passed as an argument to a python script on the web server and it is written out in chunks and the user can re-download the chunks.
I kno... | 1. For http requests, you need to set your web server to hand over certain request to PHP and others to Python. From within PHP's scripts, if you need to call some Python executable scripts, use one of PHP's shell functions. e.g. exec()
2. Yes it is possible. The djangobook is a nice tutorial that covers this in one of... |
How does Amazon's SQS notify one of my "worker" servers whenever there is something in the queue? | 4,175,428 | 11 | 2010-11-14T00:06:42Z | 4,176,255 | 10 | 2010-11-14T04:59:21Z | [
"python",
"callback",
"amazon-web-services",
"queue",
"amazon-sqs"
] | I'm following this tutorial: <http://boto.s3.amazonaws.com/sqs_tut.html>
When there's something in the queue, how do I assign one of my 20 workers to process it?
I'm using Python. | Unfortunately, SQS lacks some of the semantics we've often come to expect in queues. There's no notification or any sort of blocking "get" call.
Amazon's related SNS/Simple Notification Service may be useful to you in this effort. When you've added work to the queue, you can send out a notification to subscribed worke... |
How does Amazon's SQS notify one of my "worker" servers whenever there is something in the queue? | 4,175,428 | 11 | 2010-11-14T00:06:42Z | 15,216,183 | 8 | 2013-03-05T05:01:41Z | [
"python",
"callback",
"amazon-web-services",
"queue",
"amazon-sqs"
] | I'm following this tutorial: <http://boto.s3.amazonaws.com/sqs_tut.html>
When there's something in the queue, how do I assign one of my 20 workers to process it?
I'm using Python. | This is (now) possible with Long polling on a SQS queue.
<http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/Query_QueryReceiveMessage.html>
Long poll support (integer from 1 to 20) - the duration (in seconds) that the ReceiveMessage action call will wait until a message is in the queue to include i... |
Relative imports in Python | 4,175,534 | 24 | 2010-11-14T00:43:09Z | 4,175,606 | 17 | 2010-11-14T01:05:10Z | [
"python",
"import",
"relative"
] | Hey all -- I am pulling my hair out with relative imports in Python. I've read the documentation 30 times and numerous posts here on SO and other forums -- still doesn't seem to work.
My directory structure currently looks like this
```
src/
__init__.py
main.py
components/
__init__.py
expa... | Nevermind, I solved it:
```
src/
main.py
mod/
__init__.py
components/
__init__.py
expander.py
language_id.py
utilities/
__init__.py
functions.py
```
main.py then refers to the subpackages as:
```
from mod.components.expander ... |
python: Is this a wrong way to remove an element from a dict? | 4,175,686 | 4 | 2010-11-14T01:32:16Z | 4,175,698 | 11 | 2010-11-14T01:34:37Z | [
"python"
] | I use this way to remove an emelment from a dict:
```
d["ele"] = data
...
d["ele"] = None
```
I think by this I can remove the reference on the original element so that the removed data can be freed, no memory leak.
Is it the right way to do this? | You remove an element from a dictionary using `del`:
```
>>> d={}
>>> d['asdf']=3
>>> d['ele']=90
>>> d
{'asdf': 3, 'ele': 90}
>>> d['ele']=None
>>> d
{'asdf': 3, 'ele': None}
>>> del d['ele']
>>> d
{'asdf': 3}
>>>
``` |
Sorting a Django QuerySet by a property (not a field) of the Model | 4,175,749 | 4 | 2010-11-14T01:46:52Z | 4,175,785 | 9 | 2010-11-14T01:55:11Z | [
"python",
"django-models",
"django-templates"
] | ## Some code and my goal
My (simplified) model:
```
class Stop(models.Model):
EXPRESS_STOP = 0
LOCAL_STOP = 1
STOP_TYPES = (
(EXPRESS_STOP, 'Express stop'),
(LOCAL_STOP, 'Local stop'),
)
name = models.CharField(max_length=32)
type = models.PositiveSmallIntegerField(choices=... | Use [`QuerySet.extra()`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.QuerySet.extra) along with `CASE ... END` to define a new field, and sort on that.
```
Stops.objects.extra(select={'cost': 'CASE WHEN price=0 THEN 0 '
'WHEN type=:EXPRESS_STOP THEN price/2 WHEN type=:LOCAL_STOP THEN ... |
What is the best way to control Twisted's reactor so that it is nonblocking? | 4,176,405 | 5 | 2010-11-14T06:10:12Z | 4,176,590 | 11 | 2010-11-14T07:25:18Z | [
"python",
"twisted",
"nonblocking"
] | Instead of running reactor.run(), I'd like to call something else (I dunno, like reactor.runOnce() or something) occasionally while maintaining my own main loop. Is there a best-practice for this with twisted? | Yes. The best practice is that this is a bad idea, and that you never really need to do it. It doesn't work with all reactors, and you certainly can't have two different libraries which want to do this.
Why do you need to maintain your own main loop? Chances are, it's something like "I want to work with PyGame" or "I ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.