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
Programming a Self Learning Music Maker
1,344,884
6
2009-08-28T03:28:03Z
1,346,272
9
2009-08-28T10:50:37Z
[ "python", "perl", "music", "waveform" ]
I want to learn how to program a music application that will analyze songs. How would I get started in this and is there a library for analyzing soundwaves? I know C, C++, Java, Python, some assembly, and some Perl. **Related question:** [Algorithm for music imitation](http://stackoverflow.com/questions/1178479/algo...
Composition and analysis of music by computer is a huge field. There are two basic areas in this type of work, which overlap somewhat. * [**Algorithmic composition**](http://en.wikipedia.org/wiki/Algorithmic%5Fcomposition) is concerned with the *generation* of music. This can be based on statistical approaches such as...
Simple recursive descent in PyParsing
1,345,039
17
2009-08-28T04:38:13Z
1,345,155
9
2009-08-28T05:19:59Z
[ "python", "pyparsing", "recursive-descent" ]
I've tried taking [this code](http://stackoverflow.com/questions/634432/need-help-on-making-the-recursive-parser-using-pyparsing/634725#634725) and converting it to something for a project I'm working on for programming language processing, but I'm running into an issue with a simplified version: ``` op = oneOf( '+ - ...
Is this more or less what you want...? ``` from pyparsing import Literal,Word,ZeroOrMore,Forward,nums,oneOf def Syntax(): op = oneOf( '+ - / *') lpar = Literal( '(' ) rpar = Literal( ')' ) num = Word(nums) expr = Forward() atom = num | ( lpar + expr + rpar ) expr << atom + ZeroOrMore( o...
Simple recursive descent in PyParsing
1,345,039
17
2009-08-28T04:38:13Z
1,350,314
21
2009-08-29T03:02:04Z
[ "python", "pyparsing", "recursive-descent" ]
I've tried taking [this code](http://stackoverflow.com/questions/634432/need-help-on-making-the-recursive-parser-using-pyparsing/634725#634725) and converting it to something for a project I'm working on for programming language processing, but I'm running into an issue with a simplified version: ``` op = oneOf( '+ - ...
Wow, I guess pyparsing is really on the map! Thanks Alex and John for stepping in on this question. You are both on the mark with your responses. But let me add a comment or two: 1. If we suppress the opening and closing parenthesis symbols, and group the parenthesized expression using Group, pyparsing will a structur...
How to set timeout detection on a RabbitMQ server?
1,345,239
16
2009-08-28T05:55:14Z
1,385,416
11
2009-09-06T11:14:32Z
[ "python", "message-queue", "rabbitmq", "amqp" ]
I am trying out [RabbitMQ](http://www.rabbitmq.com/) with [this](http://barryp.org/software/py-amqplib/) python binding. One thing I noticed is that if I kill a consumer uncleanly (emulating a crashed program), the server will think that this consumer is still there for a long time. The result of this is that every ot...
I don't see `amqp_consumer.py` or `amqp_producer.py` in the tarball, so reproducing the fault is tricky. RabbitMQ terminates connections, releasing their unacknowledged messages for redelivery to other clients, whenever it is told by the operating system that a socket has closed. Your symptoms are very strange, in tha...
Determine if an executable (or library) is 32 -or 64-bits (on Windows)
1,345,632
5
2009-08-28T08:05:38Z
1,345,697
17
2009-08-28T08:27:12Z
[ "python", "windows", "dll", "64bit", "executable" ]
I am trying to find out if a given executable (or library) is compiled for 32-bits or 64-bits from Python. I am running Vista 64-bits and would like to determine if a certain application in a directory is compiled for 32-bits or 64-bits. Is there a simple way to do this using only the standard Python libraries (curren...
The Windows API for this is [`GetBinaryType`](http://msdn.microsoft.com/en-us/library/aa364819%28VS.85%29.aspx). You can call this from Python using [pywin32](http://sourceforge.net/projects/pywin32/files/): ``` import win32file type=GetBinaryType("myfile.exe") if type==win32file.SCS_32BIT_BINARY: print "32 bit" #...
How do I find the time difference between two datetime objects in python?
1,345,827
117
2009-08-28T09:03:15Z
1,345,847
15
2009-08-28T09:06:47Z
[ "python", "datetime" ]
How do I tell the time difference in minutes between two `datetime` objects?
Just subtract one from the other. You get a `timedelta` object with the difference. ``` >>> import datetime >>> d1 = datetime.datetime.now() >>> d2 = datetime.datetime.now() # after a 5-second or so pause >>> d2 - d1 datetime.timedelta(0, 5, 203000) ``` You can convert `dd.days`, `dd.seconds` and `dd.microseconds` to...
How do I find the time difference between two datetime objects in python?
1,345,827
117
2009-08-28T09:03:15Z
1,345,852
129
2009-08-28T09:08:13Z
[ "python", "datetime" ]
How do I tell the time difference in minutes between two `datetime` objects?
``` >>> import datetime >>> a = datetime.datetime.now() >>> b = datetime.datetime.now() >>> c = b - a datetime.timedelta(0, 8, 562000) >>> divmod(c.days * 86400 + c.seconds, 60) (0, 8) # 0 minutes, 8 seconds ```
How do I find the time difference between two datetime objects in python?
1,345,827
117
2009-08-28T09:03:15Z
12,654,426
71
2012-09-29T16:35:40Z
[ "python", "datetime" ]
How do I tell the time difference in minutes between two `datetime` objects?
New at Python 2.7 is the `timedelta` instance method `.total_seconds()`. From the Python docs, this is equivalent to `(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6`. Reference: <http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds> ``` >>> import datetime >>> time1 ...
How do I find the time difference between two datetime objects in python?
1,345,827
117
2009-08-28T09:03:15Z
22,768,924
8
2014-03-31T18:05:09Z
[ "python", "datetime" ]
How do I tell the time difference in minutes between two `datetime` objects?
Use divmod: ``` now = int(time.time()) # epoch seconds then = now - 90000 # some time in the past d = divmod(now-then,86400) # days h = divmod(d[1],3600) # hours m = divmod(h[1],60) # minutes s = m[1] # seconds print '%d days, %d hours, %d minutes, %d seconds' % (d[0],h[0],m[0],s) ```
What's the most Pythonic way of determining endianness?
1,346,034
26
2009-08-28T09:55:21Z
1,346,039
57
2009-08-28T09:56:17Z
[ "python", "endianness", "little-endian", "big-endian" ]
I'm trying to find the best way of working out whether the machine my code is running on is big-endian or little-endian. I have a solution that works (although I haven't tested it on a big-endian machine) but it seems a bit clunky: ``` import struct little_endian = (struct.pack('@h', 1) == struct.pack('<h', 1)) ``` T...
The answer is in the [sys module](http://docs.python.org/library/sys.html): ``` >>> import sys >>> sys.byteorder 'little' ``` Of course depending on your machine it may return `'big'`. Your method should certainly work too though.
How to find out whether computer is connected to internet?
1,346,575
9
2009-08-28T11:59:50Z
1,346,598
7
2009-08-28T12:06:11Z
[ "python", "internet-connection" ]
How to find out whether computer is connected to internet in python?
Try ``` import urllib file = urllib.urlopen("http://stackoverflow.com/") html = file.read() ``` and see if that works, or if it throws an exception. Even if you don't use the exact code, you should get the idea.
How to find out whether computer is connected to internet?
1,346,575
9
2009-08-28T11:59:50Z
1,346,623
16
2009-08-28T12:11:23Z
[ "python", "internet-connection" ]
How to find out whether computer is connected to internet in python?
If you have [python2.6](http://docs.python.org/library/urllib2.html#urllib2.urlopen) you can set a timeout. Otherwise the connection might block for a long time. ``` try: urllib2.urlopen("http://example.com", timeout=2) except urllib2.URLError: # There is no connection ```
Moving to Python 2.6.x
1,347,168
2
2009-08-28T13:56:09Z
1,347,191
8
2009-08-28T14:00:20Z
[ "python", "python-2.6" ]
My stuff is developed and running on Python 2.5.2 I want to move some code to 3.x, but that isn't feasible because so many of the external packages I use are not there yet. (Like numpy for instance). So, I'll do the intermediate step and go to 2.6.2. My question: If an external module runs on 2.5.2, but doesn't expl...
Most likely they will work just fine. Some things might cause DeprecationWarnings, for example sha module, but they can be ignored safely. This is my gut feeling, of course you can hit some specific thing causing problems. Anyway, a quick look over these should tell pretty fast whether your code needs work or not: * [...
Python version shipping with Mac OS X Snow Leopard?
1,347,376
10
2009-08-28T14:30:28Z
1,350,316
12
2009-08-29T03:03:07Z
[ "python", "osx", "osx-snow-leopard" ]
I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version") Thanks!
It ships with both python 2.6.1 and 2.5.4. > $ python2.5 > > Python 2.5.4 (r254:67916, Jul 7 2009, 23:51:24) > > $ python > > Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
Generate test coverage information from pyunit unittests?
1,347,727
2
2009-08-28T15:24:56Z
1,347,755
7
2009-08-28T15:30:19Z
[ "python", "unit-testing", "testing", "code-coverage", "pyunit" ]
I have some pyunit unit tests for a simple command line programme I'm writing. Is it possible for me to generate test coverage numbers? I want to see what lines aren't being covered by my tests.
I regularly use Ned Batchelder's [coverage.py](http://nedbatchelder.com/code/modules/coverage.html) tool for exactly this purpose.
"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3
1,347,791
63
2009-08-28T15:36:39Z
1,347,854
146
2009-08-28T15:46:24Z
[ "python", "unicode", "python-3.x" ]
I am using python 3.1, on a windows 7 machines. Russian is the default system language, and utf-8 is the default encoding. Looking at the answer to a [previous question](http://stackoverflow.com/questions/778096/problem-opening-a-text-document-unicode-error), I have attempting using the "codecs" module to give me a li...
The problem is with the string ``` "C:\Users\Eric\Desktop\beeline.txt" ``` Here, `\U` starts an eight-character Unicode escape, such as '\U00014321`. In your code, the escape is followed by the character 's', which is invalid. You either need to duplicate all backslashes, or prefix the string with `r` (to produce a ...
How do I create a file in python without overwriting an existing file
1,348,026
20
2009-08-28T16:14:03Z
1,348,073
36
2009-08-28T16:21:33Z
[ "python", "multithreading" ]
Currently I have a loop that tries to find an unused filename by adding suffixes to a filename string. Once it fails to find a file, it uses the name that failed to open a new file wit that name. Problem is this code is used in a website and there could be multiple attempts to do the same thing at the same time, so a r...
Use [`os.open()`](https://docs.python.org/2/library/os.html#os.open) with `os.O_CREAT` and `os.O_EXCL` to create the file. That will fail if the file already exists: ``` >>> fd = os.open("x", os.O_WRONLY | os.O_CREAT | os.O_EXCL) Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno ...
passing ctrl+z to pexpect
1,348,283
2
2009-08-28T17:01:48Z
1,348,298
7
2009-08-28T17:07:36Z
[ "python", "pexpect" ]
How do I pass a certain key combination to a spawned/child process using the pexpect module? I'm using telnet and have to pass Ctrl+Z to a remote server. Tnx
use [sendcontrol()](http://pexpect.sourceforge.net/pexpect.html#spawn-sendcontrol) for example: ``` p = pexpect.spawn(your_cmd_here) p.sendcontrol('z') ```
Different versions of msvcrt in ctypes
1,348,547
5
2009-08-28T18:05:29Z
1,348,903
10
2009-08-28T19:30:12Z
[ "python", "ctypes", "msvcrt" ]
In Windows, the `ctypes.cdll.msvcrt` object automatically exists when I import the ctypes module, and it represents the `msvcrt` Microsoft C++ runtime library [according to the docs](http://docs.python.org/library/ctypes.html#loading-dynamic-link-libraries). However, I notice that there is also a [find\_msvcrt](http:/...
It's not just that `ctypes.cdll.msvcrt` automatically exists, but `ctypes.cdll.anything` automatically exists, and is loaded on first access, loading `anything.dll`. So `ctypes.cdll.msvcrt` loads `msvcrt.dll`, which is a library that ships as part of Windows. It is not the C runtime that Python links with, so you shoul...
Matplotlib coord. sys origin to top left
1,349,230
8
2009-08-28T20:40:31Z
1,350,146
12
2009-08-29T01:27:29Z
[ "python", "matplotlib", "axes" ]
How can I flip the origin of a matplotlib plot to be in the upper-left corner - as opposed to the default lower-left? I'm using matplotlib.pylab.plot to produce the plot (though if there is another plotting routine that is more flexible, please let me know). I'm looking for the equivalent of the matlab command: axis i...
`axis ij` just makes the y-axis increase downward instead of upward, right? If so, then [`matplotlib.axes.invert_yaxis()`](http://matplotlib.sourceforge.net/api/axes%5Fapi.html#matplotlib.axes.Axes.invert%5Fyaxis) might be all you need -- but I can't test that right now. If that doesn't work, I found [a mailing post](...
Matplotlib coord. sys origin to top left
1,349,230
8
2009-08-28T20:40:31Z
1,350,154
8
2009-08-29T01:31:45Z
[ "python", "matplotlib", "axes" ]
How can I flip the origin of a matplotlib plot to be in the upper-left corner - as opposed to the default lower-left? I'm using matplotlib.pylab.plot to produce the plot (though if there is another plotting routine that is more flexible, please let me know). I'm looking for the equivalent of the matlab command: axis i...
For an image or contour plot, you can use the keyword `origin = None | 'lower' | 'upper'` and for a line plot, you can set the ylimits high to low. ``` from pylab import * A = arange(25)/25. A = A.reshape((5,5)) figure() imshow(A, interpolation='nearest', origin='lower') figure() imshow(A, interpolation='nearest') ...
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
23
2009-08-28T20:57:29Z
1,350,289
42
2009-08-29T02:47:39Z
[ "python", "string", "performance" ]
I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the **join** method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is goin...
Some of us Python committers, I believe mostly Rigo and Hettinger, went out of their way (on the way to 2.5 I believe) to optimize some special cases of the alas-far-too-common `s += something` **blight**, arguing that it was proven that beginners will never be covinced that `''.join` is the right way to go and the hor...
Python - Passing a function into another function
1,349,332
37
2009-08-28T21:01:19Z
1,349,350
72
2009-08-28T21:04:04Z
[ "python", "function", "first-class-functions" ]
I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python? Example ``` def Game(listA, listB, rules): if rules == True: do... else: do... def Rule1(v): if "variable_name1" in v...
Just pass it in like any other parameter: ``` def a(x): return "a(%s)" % (x,) def b(f,x): return f(x) print b(a,10) ```
Python - Passing a function into another function
1,349,332
37
2009-08-28T21:01:19Z
1,349,359
10
2009-08-28T21:06:28Z
[ "python", "function", "first-class-functions" ]
I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python? Example ``` def Game(listA, listB, rules): if rules == True: do... else: do... def Rule1(v): if "variable_name1" in v...
Treat function as variable in your program so you can just pass them to other functions easily: ``` def test (): print "test was invoked" def invoker(func): func() invoker(test) # prints test was invoked ```
Parse an HTTP request Authorization header with Python
1,349,367
9
2009-08-28T21:07:56Z
1,349,528
11
2009-08-28T21:40:19Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
I need to take a header like this: ``` Authorization: Digest qop="chap", realm="[email protected]", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" ``` And parse it into this using Python: ``` {'protocol':'Digest', 'qop':'chap', 're...
A little regex: ``` import re reg=re.compile('(\w+)[:=] ?"?(\w+)"?') >>>dict(reg.findall(headers)) {'username': 'Foobear', 'realm': 'testrealm', 'qop': 'chap', 'cnonce': '5ccc069c403ebaf9f0171e9517f40e41', 'response': '6629fae49393a05397450978507c4ef1', 'Authorization': 'Digest'} ```
Parse an HTTP request Authorization header with Python
1,349,367
9
2009-08-28T21:07:56Z
1,349,626
8
2009-08-28T22:11:31Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
I need to take a header like this: ``` Authorization: Digest qop="chap", realm="[email protected]", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" ``` And parse it into this using Python: ``` {'protocol':'Digest', 'qop':'chap', 're...
You can also use urllib2 as [CheryPy](http://www.google.com/codesearch/p?hl=en&sa=N&cd=9&ct=rc#OQvO9n2mc04/CherryPy-3.0.1/cherrypy/lib/httpauth.py&q=Authorization%20Digest%20http%20lang%3Apython) does. here is the snippet: ``` input= """ Authorization: Digest qop="chap", realm="[email protected]", username="Foo...
What does matrix**2 mean in python/numpy?
1,350,174
9
2009-08-29T01:40:52Z
1,350,199
12
2009-08-29T01:54:48Z
[ "python", "numpy" ]
I have a python ndarray temp in some code I'm reading that suffers this: ``` x = temp**2 ``` Is this the dot square (ie, equivalent to m.\*m) or the matrix square (ie m must be a square matrix)? In particular, I'd like to know whether I can get rid of the transpose in this code: ``` temp = num.transpose(whatever) nu...
It's just the square of each element. ``` from numpy import * a = arange(4).reshape((2,2)) print a**2 ``` prints ``` [[0 1] [4 9]] ```
Java equivalent of Python repr()?
1,350,397
20
2009-08-29T03:52:13Z
1,351,973
8
2009-08-29T17:49:30Z
[ "java", "python", "repr" ]
Is there a Java method that works like Python's repr? For example, assuming the function were named repr, ``` "foo\n\tbar".repr() ``` would return ``` "foo\n\tbar" ``` not ``` foo bar ``` as toString does.
In some projects, I use the following helper function to accomplish something akin to Python's *repr* for strings: ``` private static final char CONTROL_LIMIT = ' '; private static final char PRINTABLE_LIMIT = '\u007e'; private static final char[] HEX_DIGITS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', ...
Preventing Python code from importing certain modules?
1,350,466
7
2009-08-29T04:39:33Z
1,350,476
11
2009-08-29T04:44:34Z
[ "python", "module", "sandbox" ]
I'm writing an application where users can enter a python script and execute it in a sandbox. I need a way to prevent the exec'ed code from importing certain modules, so malicious code won't be as much of a problem. Is there a way to do this in Python?
Have you checked the python.org [article on SandboxedPython](http://wiki.python.org/moin/SandboxedPython), and the [linked article](http://wiki.python.org/moin/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20%28i.e.%20Sandbox%29)? Both of those pages have links to other resources. Specifically, PyPi...
Preventing Python code from importing certain modules?
1,350,466
7
2009-08-29T04:39:33Z
1,350,574
13
2009-08-29T05:35:31Z
[ "python", "module", "sandbox" ]
I'm writing an application where users can enter a python script and execute it in a sandbox. I need a way to prevent the exec'ed code from importing certain modules, so malicious code won't be as much of a problem. Is there a way to do this in Python?
If you put None in sys.modules for a module name, in won't be importable... ``` >>> import sys >>> import os >>> del os >>> sys.modules['os']=None >>> import os Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named os >>> ```
"Inner exception" (with traceback) in Python?
1,350,671
86
2009-08-29T06:35:17Z
1,350,981
97
2009-08-29T09:41:33Z
[ "python", "exception", "error-handling" ]
My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python? Eg. in C# I would do something like this: ...
It's simple; pass the traceback as the third argument to raise. ``` import sys class MyException(Exception): pass try: raise TypeError("test") except TypeError, e: raise MyException(), None, sys.exc_info()[2] ``` Always do this when catching one exception and re-raising another.
"Inner exception" (with traceback) in Python?
1,350,671
86
2009-08-29T06:35:17Z
6,246,394
105
2011-06-05T22:42:06Z
[ "python", "exception", "error-handling" ]
My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python? Eg. in C# I would do something like this: ...
In python 3 you can do the following: ``` try: raise MyExceptionToBeWrapped("I have twisted my ankle") except MyExceptionToBeWrapped as e: raise MyWrapperException("I'm not in a good shape") from e ``` This will produce something like this: ``` Traceback (most recent call last): ... MyExceptionToBeWrapped:...
"Inner exception" (with traceback) in Python?
1,350,671
86
2009-08-29T06:35:17Z
13,018,468
8
2012-10-22T19:33:05Z
[ "python", "exception", "error-handling" ]
My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python? Eg. in C# I would do something like this: ...
Python 3 has the [`raise` ... `from` clause](https://docs.python.org/3/reference/simple_stmts.html#raise) to chain exceptions. [Glenn's answer](http://stackoverflow.com/a/1350981/4794) is great for Python 2.7, but it only uses the original exception's traceback and throws away the error message and other details. Here ...
What are some of the core conceptual differences between C# and Python?
1,351,227
3
2009-08-29T11:39:35Z
1,351,670
9
2009-08-29T15:11:48Z
[ "c#", "asp.net", "python", "django", "programming-languages" ]
I'm new to Python, coming from a C# background and I'm trying to get up to speed. I understand that Python is dynamically typed, whereas C# is strongly-typed. -> see comments. What conceptual obstacles should I watch out for when attempting to learn Python? Are there concepts for which no analog exists in Python? How i...
" I understand that Python is dynamically typed, whereas C# is strongly-typed. " This is weirdly wrong. 1. Python is strongly typed. A list or integer or dictionary is always of the given type. The object's type cannot be changed. 2. Python variables are not strongly typed. Indeed, Python variables are just labels on...
How to make custom buttons in wx?
1,351,448
4
2009-08-29T13:31:52Z
1,361,336
7
2009-09-01T08:55:55Z
[ "python", "button", "wxpython" ]
I'd like to make a custom button in wxPython. Where should I start, how should I do it?
Here is a skeleton which you can use to draw totally custom button, its up to your imagination how it looks or behaves ``` class MyButton(wx.PyControl): def __init__(self, parent, id, bmp, text, **kwargs): wx.PyControl.__init__(self,parent, id, **kwargs) self.Bind(wx.EVT_LEFT_DOWN, self._onMouseD...
Why is Python's enumerate so slow?
1,352,497
3
2009-08-29T21:57:28Z
1,352,521
14
2009-08-29T22:09:07Z
[ "python" ]
Why is "enumerate" slower than "xrange + lst[i]"? ``` >>> from timeit import Timer >>> lst = [1,2,3,0,1,2]*1000 >>> setup = 'from __main__ import lst' >>> s1 = """ for i in range(len(lst)): elem = lst[i] """ >>> s2 = """ for i in xrange(len(lst)): elem = lst[i] """ >>> s3 = """ for i, v in enumerate(lst): ...
If you measure properly you'll see there's essentially no difference (enumerate is microscopically faster than xrange in this example, but well within noise): ``` $ python -mtimeit -s'lst=[1,2,3,0,1,2]*1000' 'for i in xrange(len(lst)): elem=lst[i]' 1000 loops, best of 3: 480 usec per loop $ python -mtimeit -s'lst=[1,2...
Why does ActivePython exist?
1,352,528
63
2009-08-29T22:12:56Z
1,352,533
28
2009-08-29T22:17:13Z
[ "python", "activestate", "activepython", "rationale" ]
What's ActivePython actually about? From [what I've read](http://www.activestate.com/activepython/features/) it's just standard Python with openssl and pyWin32 (on Win). No big deal I guess, I could install them in matter of minutes, and most people don't need them anyway. All other mentioned libraries (zlib, bzip2, s...
The main feature is that you can buy a paid support contract for it. Why does Red Hat Enterprise Linux exist when you can compile everything yourself? 8-) For many businesses, the combination of proven Open Source software *and* a support contract from people who build, package and test that software, is an excellent...
Why does ActivePython exist?
1,352,528
63
2009-08-29T22:12:56Z
1,352,539
42
2009-08-29T22:20:10Z
[ "python", "activestate", "activepython", "rationale" ]
What's ActivePython actually about? From [what I've read](http://www.activestate.com/activepython/features/) it's just standard Python with openssl and pyWin32 (on Win). No big deal I guess, I could install them in matter of minutes, and most people don't need them anyway. All other mentioned libraries (zlib, bzip2, s...
It's a packaging, or "distribution", of Python, with some extras -- not (anywhere) quite as "Sumo" as Enthought's HUGE distro of "Python plus everything", but still in a similar vein (and it first appeared much earlier). I don't think you're missing anything in particular, except perhaps the fact that David Ascher (Py...
Why does ActivePython exist?
1,352,528
63
2009-08-29T22:12:56Z
1,352,541
31
2009-08-29T22:21:36Z
[ "python", "activestate", "activepython", "rationale" ]
What's ActivePython actually about? From [what I've read](http://www.activestate.com/activepython/features/) it's just standard Python with openssl and pyWin32 (on Win). No big deal I guess, I could install them in matter of minutes, and most people don't need them anyway. All other mentioned libraries (zlib, bzip2, s...
ActiveState has a long tradition contributing Windows support to Python, Tcl, and Perl: by hiring key developers (like Mark Hammond, for some time), by fixing bugs specific to Windows, and having employees contribute fixes back, and by being sponsors of the Python Software Foundation. While it is true that the distrib...
Why does ActivePython exist?
1,352,528
63
2009-08-29T22:12:56Z
1,354,126
8
2009-08-30T15:40:47Z
[ "python", "activestate", "activepython", "rationale" ]
What's ActivePython actually about? From [what I've read](http://www.activestate.com/activepython/features/) it's just standard Python with openssl and pyWin32 (on Win). No big deal I guess, I could install them in matter of minutes, and most people don't need them anyway. All other mentioned libraries (zlib, bzip2, s...
I've been using ActivePerl for years and when I made the switch to Python, I very naturally downloaded ActivePython. Never had any problems with the Active\* distributions - they're robust, come with a few useful libraries that the vanilla core Python doesn't have. They also come bundled with a .CHM Python documentatio...
Optional get parameters in django?
1,352,834
22
2009-08-30T01:43:34Z
1,352,841
34
2009-08-30T01:48:34Z
[ "python", "regex", "django" ]
Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag. Here's what I have currently: **Pattern** ``` (r'^so/(?P<required>\d+)/?(?P<optional>(.*))/?$', 'myapp.so') ``` **View** ``` def so(request, req...
I generally make two patterns with a [named url](http://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns): ``` url(r'^so/(?P<required>\d+)/$', 'myapp.so', name='something'), url(r'^so/(?P<required>\d+)/(?P<optional>.*)/$', 'myapp.so', name='something_else'), ```
Optional get parameters in django?
1,352,834
22
2009-08-30T01:43:34Z
8,981,132
16
2012-01-24T01:46:59Z
[ "python", "regex", "django" ]
Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag. Here's what I have currently: **Pattern** ``` (r'^so/(?P<required>\d+)/?(?P<optional>(.*))/?$', 'myapp.so') ``` **View** ``` def so(request, req...
Django urls are polymorphic: ``` url(r'^so/(?P<required>\d+)/$', 'myapp.so', name='sample_view'), url(r'^so/(?P<required>\d+)/(?P<optional>.*)/$', 'myapp.so', name='sample_view'), ``` its obious that you have to make your views like this: ``` def sample_view(request, required, optional = None): ``` so you can call ...
Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
1,352,922
57
2009-08-30T02:30:30Z
1,352,938
60
2009-08-30T02:36:51Z
[ "python", "bash" ]
Anyone know this? I've never been able to find an answer.
If you're prone to installing python in various and interesting places on your PATH (as in `$PATH` in typical Unix shells, `%PATH` on typical Windows ones), using `/usr/bin/env` will accomodate your whim (well, in Unix-like environments at least) while going directly to `/usr/bin/python` won't. But losing control of wh...
Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
1,352,922
57
2009-08-30T02:30:30Z
1,352,939
23
2009-08-30T02:36:53Z
[ "python", "bash" ]
Anyone know this? I've never been able to find an answer.
From [wikipedia](http://en.wikipedia.org/wiki/Shebang_%28Unix%29) > Shebangs specify absolute paths to system executables; this can cause > problems on systems which have non-standard file system layouts > > Often, the program /usr/bin/env can be used to circumvent this > limitation
Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
1,352,922
57
2009-08-30T02:30:30Z
1,352,941
9
2009-08-30T02:37:13Z
[ "python", "bash" ]
Anyone know this? I've never been able to find an answer.
it finds the python executable in your environment and uses that. it's more portable because python may not always be in /usr/bin/python. env is always located in /usr/bin.
Multiprocessing debug techniques
1,352,980
15
2009-08-30T03:06:04Z
1,353,037
28
2009-08-30T03:58:08Z
[ "python", "debugging", "deadlock", "multiprocessing" ]
I'm having trouble debugging a multi-process application (specifically using a process pool in python's multiprocessing module). I have an apparent deadlock and I do not know what is causing it. The stack trace is not sufficient to describe the issue, as it only displays code in the multiprocessing module. Are there a...
Yah, debugging deadlocks is fun. You can set the logging level to be higher -- see [the Python documentation](http://docs.python.org/library/multiprocessing.html) for a description of it, but really quickly: ``` import multiprocessing, logging logger = multiprocessing.log_to_stderr() logger.setLevel(multiprocessing.SU...
Python+Django social network open source projects
1,353,097
6
2009-08-30T04:37:35Z
1,353,112
10
2009-08-30T04:44:12Z
[ "python", "django", "project", "social-networking" ]
I'm looking for some open source, free to change and use project written on Pyton+Django with following features: * Blog (for site, not for users) * Users Registration * User Profiles * Adding friends, watching what friends added * Award system for active users (carma, rating) * Content rating * Comments * Probably di...
Django has [authentication](http://docs.djangoproject.com/en/dev/topics/auth/) and [commenting](http://docs.djangoproject.com/en/dev/ref/contrib/comments/) built in, but most of the rest is covered by [Pinax](http://pinaxproject.com/).
Issues with scoped_session in sqlalchemy - how does it work?
1,353,131
6
2009-08-30T04:57:08Z
1,353,193
7
2009-08-30T06:02:18Z
[ "python", "sqlalchemy", "python-elixir" ]
I'm not really sure how scoped\_session works, other than it seems to be a wrapper that hides several real sessions, keeping them separate for different requests. Does it do this with thread locals? Anyway the trouble is as follows: ``` S = elixir.session # = scoped_session(...) f = Foo(bar=1) S.add(f) # ERROR, f is ...
Scoped session creates a proxy object that keeps a registry of (by default) per thread session objects created on demand from the passed session factory. When you access a session method such as `ScopedSession.add` it finds the session corresponding to the current thread and returns the `add` method bound to that sessi...
Should I optimise my python code like C++? Does it matter?
1,353,715
5
2009-08-30T11:49:35Z
1,353,722
14
2009-08-30T11:52:06Z
[ "python", "performance" ]
I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++. Things like: * In an `if` statement with an `or` always put the c...
My answer to that would be : > We should forget about small > efficiencies, say about 97% of the > time: premature optimization is the > root of all evil. *(Quoting Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268)* If your application is doin...
Should I optimise my python code like C++? Does it matter?
1,353,715
5
2009-08-30T11:49:35Z
1,353,732
13
2009-08-30T11:57:23Z
[ "python", "performance" ]
I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++. Things like: * In an `if` statement with an `or` always put the c...
The answer is really simple : * Follow Python best practices, not C++ best practices. * Readability in Python is more important that speed. * If performance becomes an issue, measure, then start optimizing.
Should I optimise my python code like C++? Does it matter?
1,353,715
5
2009-08-30T11:49:35Z
1,353,775
10
2009-08-30T12:26:37Z
[ "python", "performance" ]
I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++. Things like: * In an `if` statement with an `or` always put the c...
This sort of premature micro-optimisation is usually a waste of time in my experience, even in C and C++. Write readable code first. If it's running too slowly, run it through a profiler, and if necessary, fix the hot-spots. Fundamentally, you need to think about return on investment. Is it worth the extra effort in r...
Storing huge hash table in a file in Python
1,354,520
4
2009-08-30T18:24:09Z
1,354,619
10
2009-08-30T18:56:01Z
[ "python", "file", "hashtable" ]
Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I know it's slow to read from a text file but there'...
For a list of primes up to `10**9`, why do you need a hash? What would the KEYS be?! Sounds like a perfect opportunity for a simple, straightforward binary file! By the [Prime Number Theorem](http://en.wikipedia.org/wiki/Prime%5Fnumber%5Ftheorem), there's about `10**9/ln(10**9)` such primes -- i.e. 50 millions or a bit...
Creating GUI with Python in Linux
1,355,918
11
2009-08-31T05:25:00Z
1,355,923
12
2009-08-31T05:27:14Z
[ "python", "linux", "user-interface", "gtk", "pygtk" ]
Quick question. I'm using Linux and I want to try making a GUI with Python. I've heard about something like Qt, GTK+ and PyGTK but I don't know what they are exactly and what the difference between them is. Is there any difference on how they work with different DEs like GNOME, KDE, XFCE etc.? Is there any IDE that a...
Your first step should be <http://wiki.python.org/moin/GuiProgramming> Some tool-kits integrate better in one environment over the other. For example PyQt, PyKDE (and the brand new [PySide](http://www.pyside.org/) will play nicer in a KDE environment, while the GTK versions (including the WX-widgets) will blend better...
How do I line up text from python into columns in my terminal?
1,356,029
7
2009-08-31T06:08:43Z
1,356,065
16
2009-08-31T06:26:10Z
[ "python" ]
I'm printing out some values from a script in my terminal window like this: ``` for i in items: print "Name: %s Price: %d" % (i.name, i.price) ``` How do I make these line up into columns?
If you know the maximum lengths of data in the two columns, then you can use format qualifiers. For example if the name is at most 20 chars long and the price will fit into 10 chars, you could do ``` print "Name: %-20s Price: %10d" % (i.name, i.price) ``` This is better than using tabs as tabs won't line up in some c...
How do I line up text from python into columns in my terminal?
1,356,029
7
2009-08-31T06:08:43Z
1,356,087
8
2009-08-31T06:34:58Z
[ "python" ]
I'm printing out some values from a script in my terminal window like this: ``` for i in items: print "Name: %s Price: %d" % (i.name, i.price) ``` How do I make these line up into columns?
As Vinay said, use string format specifiers. If you don't know the maximum lengths, you can find them by making an extra pass through the list: ``` maxn, maxp = 0, 0 for item in items: maxn = max(maxn, len(item.name)) maxp = max(maxp, len(str(item.price))) ``` then use `'*'` instead of the number and provide...
pytz utc conversion
1,357,711
20
2009-08-31T14:22:55Z
1,358,161
18
2009-08-31T16:07:40Z
[ "python", "datetime", "utc", "pytz" ]
What is the right way to convert a naive time and a `tzinfo` into an utc time? Say I have: ``` d = datetime(2009, 8, 31, 22, 30, 30) tz = timezone('US/Pacific') ``` First way, pytz inspired: ``` d_tz = tz.normalize(tz.localize(d)) utc = pytz.timezone('UTC') d_utc = d_tz.astimezone(utc) ``` Second way, from [UTCDate...
Your first method seems to be the approved one, and should be DST-aware. You could shorten it a tiny bit, since *pytz.utc = pytz.timezone('UTC')*, but you knew that already :) ``` tz = timezone('US/Pacific') def toUTC(d): return tz.normalize(tz.localize(d)).astimezone(pytz.utc) print "Test: ", datetime.datetime....
How to make several plots on a single page using matplotlib?
1,358,977
48
2009-08-31T19:17:03Z
1,358,983
10
2009-08-31T19:19:17Z
[ "python", "numpy", "matplotlib" ]
I have written code that opens 16 figures at once. Currently they all open as separate graphs. I'd like them to open all on the same page. Not the same graph. I want 16 separate graphs on a single page/window. Also for some reason the format of the numbins and defaultreallimits doesn't hold past figure 1. Do I need to ...
To answer your main question, you want to use the [subplot](http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.subplot) command. I think changing `plt.figure(i)` to `plt.subplot(4,4,i+1)` should work.
How to make several plots on a single page using matplotlib?
1,358,977
48
2009-08-31T19:17:03Z
2,060,170
109
2010-01-13T20:52:22Z
[ "python", "numpy", "matplotlib" ]
I have written code that opens 16 figures at once. Currently they all open as separate graphs. I'd like them to open all on the same page. Not the same graph. I want 16 separate graphs on a single page/window. Also for some reason the format of the numbins and defaultreallimits doesn't hold past figure 1. Do I need to ...
The answer from *las3rjock*, which somehow is the answer accepted by the OP, is incorrect--the code doesn't run, nor is it valid matplotlib syntax; that answer provides no runnable code and lacks any information or suggestion that the OP might find useful in writing their own code to solve the problem in the OP. Given...
How to make several plots on a single page using matplotlib?
1,358,977
48
2009-08-31T19:17:03Z
18,673,184
43
2013-09-07T12:14:45Z
[ "python", "numpy", "matplotlib" ]
I have written code that opens 16 figures at once. Currently they all open as separate graphs. I'd like them to open all on the same page. Not the same graph. I want 16 separate graphs on a single page/window. Also for some reason the format of the numbins and defaultreallimits doesn't hold past figure 1. Do I need to ...
Since this question is from 4 years ago new things have been implemented and among them there is a [new function `plt.subplots` which is very convenient](http://matplotlib.org/api/pyplot_api.html): ``` fig, axes = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True) ``` where `axes` is a `numpy.ndarray` of AxesS...
PyObjc and Cocoa on Snow Leopard
1,359,227
13
2009-08-31T20:19:29Z
1,359,402
7
2009-08-31T21:00:03Z
[ "python", "cocoa", "xcode", "osx-snow-leopard", "pyobjc" ]
I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and...
You mean like [Checkout](http://checkoutapp.com/)? :-) I only mention it because Checkout is gorgeous and written with PyObjC... Your concerns are valid, although probably not as much of a potential showstopper as you'd think. Using PyObjC still requires you to learn some Objective-C, and definitely requires you to un...
PyObjc and Cocoa on Snow Leopard
1,359,227
13
2009-08-31T20:19:29Z
1,359,605
19
2009-08-31T22:00:20Z
[ "python", "cocoa", "xcode", "osx-snow-leopard", "pyobjc" ]
I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and...
Allow me to echo what has already been said. I too am a student who just started a Cocoa development project, and at the beginning I thought "Well, I already know Python, I'll just use PyObjC and save myself from having to learn Objective-C, which looks beyond my grasp." I learned quickly that it can't be done. You can...
Python: Run a process and kill it if it doesn't end within one hour
1,359,383
10
2009-08-31T20:55:29Z
1,359,467
16
2009-08-31T21:17:10Z
[ "python", "process", "kill" ]
I need to do the following in Python. I want to spawn a process (subprocess module?), and: * if the process ends normally, to continue exactly from the moment it terminates; * if, otherwise, the process "gets stuck" and doesn't terminate within (say) one hour, to kill it and continue (possibly giving it another try, i...
The `subprocess` module will be your friend. Start the process to get a `Popen` object, then pass it to a function like this. Note that this only raises exception on timeout. If desired you can catch the exception and call the `kill()` method on the `Popen` process. (kill is new in Python 2.6, btw) ``` import time de...
Generating a list from complex dictionary
1,360,507
2
2009-09-01T04:17:35Z
1,360,514
8
2009-09-01T04:22:45Z
[ "python-3.x", "python" ]
I have a dictionary `dict1['a'] = [ [1,2], [3,4] ]` and need to generate a list out of it as `l1 = [2, 4]`. That is, a list out of the second element of each inner list. It can be a separate list or even the dictionary can be modified as `dict1['a'] = [2,4]`.
Given a list: ``` >>> lst = [ [1,2], [3,4] ] ``` You can extract the second element of each sublist with a simple list comprehension: ``` >>> [x[1] for x in lst] [2, 4] ``` If you want to do this for every value in a dictionary, you can iterate over the dictionary. I'm not sure exactly what you want your final data...
How to get/set local variables of a function (from outside) in Python?
1,360,721
3
2009-09-01T05:50:41Z
1,361,058
12
2009-09-01T07:34:41Z
[ "python" ]
If I have a function (in Python 2.5.2) like: ``` def sample_func(): a = 78 b = range(5) #c = a + b[2] - x ``` My questions are: 1. How to get the local variables (a,b) of the function from outside **without** using *locals()* inside the function? (kind of reflection) 2. Is it possible to set a local vari...
No. A function that isn't being run doesn't have locals; it's just a function. Asking how to modify a function's locals when it's not running is like asking how to modify a program's heap when it's not running. You can modify constants, though, if you really want to. ``` def func(): a = 10 print a co = func....
Why does namespace after method call changes?
1,361,393
2
2009-09-01T09:07:54Z
1,361,409
7
2009-09-01T09:11:58Z
[ "python", "namespaces" ]
I'm creating a class, but having some trouble with the namespacing in python. You can see the code below, and it mostly works ok, but after the call to `guiFrame._stateMachine()` the time module is somehow not defined anymore. If I re-import the time module in `_stateMachine()` it works. But why is the time module no...
Why do you assign to `time`? You can't use it as local variable, it will overshadow the module! If you look closely it complains that you use `time` before you assign to it -- since to use it as a local variable in `_stateMachine`. ``` time = 4 ```
How to encode UTF8 filename for HTTP headers? (Python, Django)
1,361,604
38
2009-09-01T10:00:31Z
1,361,646
35
2009-09-01T10:11:28Z
[ "python", "django", "http", "http-headers", "escaping" ]
I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII. ``` response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), ) ``` I don't want to use static files serving for same issue with non...
This is a FAQ. There is no interoperable way to do this. Some browsers implement proprietary extensions (IE, Chrome), other implement RFC 2231 (Firefox, Opera). See test cases at <http://greenbytes.de/tech/tc2231/>. Update: as of November 2012, all current desktop browsers support the encoding defined in RFC 6266 an...
How to encode UTF8 filename for HTTP headers? (Python, Django)
1,361,604
38
2009-09-01T10:00:31Z
1,365,186
30
2009-09-01T23:41:27Z
[ "python", "django", "http", "http-headers", "escaping" ]
I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII. ``` response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), ) ``` I don't want to use static files serving for same issue with non...
Don't send a filename in Content-Disposition. There is no way to make non-ASCII header parameters work cross-browser(\*). Instead, send just “Content-Disposition: attachment”, and leave the filename as a URL-encoded UTF-8 string in the trailing (PATH\_INFO) part of your URL, for the browser to pick up and use by d...
How to encode UTF8 filename for HTTP headers? (Python, Django)
1,361,604
38
2009-09-01T10:00:31Z
8,996,249
22
2012-01-25T00:13:54Z
[ "python", "django", "http", "http-headers", "escaping" ]
I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII. ``` response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), ) ``` I don't want to use static files serving for same issue with non...
Note that in 2011, [RFC 6266](http://tools.ietf.org/html/rfc6266#appendix-D) (especially Appendix D) weighed in on this issue and has specific recommendations to follow. Namely, you can issue a `filename` with only ASCII characters, followed by `filename*` with a RFC 5987-formatted filename for those agents that under...
Cubic root of the negative number on python
1,361,740
11
2009-09-01T10:40:10Z
1,361,750
9
2009-09-01T10:42:37Z
[ "python", "math" ]
Can someone help me to find a solution on how to calculate a cubic root of the negative number using python? ``` >>> math.pow(-3, float(1)/3) nan ``` it does not work. Cubic root of the negative number is negative number. Any solutions?
You could use: ``` -math.pow(3, float(1)/3) ``` Or more generally: ``` if x > 0: return math.pow(x, float(1)/3) elif x < 0: return -math.pow(abs(x), float(1)/3) else: return 0 ```
Cubic root of the negative number on python
1,361,740
11
2009-09-01T10:40:10Z
1,361,778
10
2009-09-01T10:50:09Z
[ "python", "math" ]
Can someone help me to find a solution on how to calculate a cubic root of the negative number using python? ``` >>> math.pow(-3, float(1)/3) nan ``` it does not work. Cubic root of the negative number is negative number. Any solutions?
``` math.pow(abs(x),float(1)/3) * (1,-1)[x<0] ```
Cubic root of the negative number on python
1,361,740
11
2009-09-01T10:40:10Z
1,361,789
8
2009-09-01T10:54:58Z
[ "python", "math" ]
Can someone help me to find a solution on how to calculate a cubic root of the negative number using python? ``` >>> math.pow(-3, float(1)/3) nan ``` it does not work. Cubic root of the negative number is negative number. Any solutions?
Taking the earlier answers and making it into a one-liner: ``` import math def cubic_root(x): return math.copysign(math.pow(abs(x), 1.0/3.0), x) ```
Cubic root of the negative number on python
1,361,740
11
2009-09-01T10:40:10Z
1,362,288
17
2009-09-01T12:44:15Z
[ "python", "math" ]
Can someone help me to find a solution on how to calculate a cubic root of the negative number using python? ``` >>> math.pow(-3, float(1)/3) nan ``` it does not work. Cubic root of the negative number is negative number. Any solutions?
A simple use of [De Moivre's formula](http://en.wikipedia.org/wiki/De%5FMoivre%27s%5Fformula), is sufficient to show that the cube root of a value, regardless of sign, is a multi-valued function. That means, for any input value, there will be three solutions. Most of the solutions presented to far only return the princ...
Cubic root of the negative number on python
1,361,740
11
2009-09-01T10:40:10Z
1,362,820
8
2009-09-01T14:31:59Z
[ "python", "math" ]
Can someone help me to find a solution on how to calculate a cubic root of the negative number using python? ``` >>> math.pow(-3, float(1)/3) nan ``` it does not work. Cubic root of the negative number is negative number. Any solutions?
You can get the complete (all n roots) and more general (any sign, any power) solution using: ``` import cmath x, t = -3., 3 # x**(1/t) a = cmath.exp((1./t)*cmath.log(x)) p = cmath.exp(1j*2*cmath.pi*(1./t)) r = [a*(p**i) for i in range(t)] ``` Explanation: a is using the equation xu = exp(u\*log(x)). This solutio...
Pointers and arrays in Python ctypes
1,363,163
26
2009-09-01T15:38:20Z
1,363,344
43
2009-09-01T16:10:10Z
[ "python", "arrays", "pointers", "ctypes" ]
I have a DLL containing a C function with a prototype like this: `int c_read_block(uint32 addr, uint32 *buf, uint32 num);` I want to call it from Python using ctypes. The function expects a pointer to a chunk of memory, into which it will write the results. I don't know how to construct and pass such a chunk of memor...
You can cast with the [`cast`](http://docs.python.org/library/ctypes.html#type-conversions) function :) ``` >>> import ctypes >>> x = (ctypes.c_ulong*5)() >>> x <__main__.c_ulong_Array_5 object at 0x00C2DB20> >>> ctypes.cast(x, ctypes.POINTER(ctypes.c_ulong)) <__main__.LP_c_ulong object at 0x0119FD00> >>> ```
Efficient way to use python's lambda, map
1,363,413
3
2009-09-01T16:27:08Z
1,363,491
7
2009-09-01T16:41:17Z
[ "python", "performance", "list", "lambda", "map-function" ]
I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items. for eg: ``` original_list = [1005, 1004, 1003, 1004, 1006] ``` Storing the above list(which actually contains more than 1000k items) as ``` start = 1005 diff = [-1, -1, 1, 2] ``` The close...
For such large data structures numpy will work well. For this example, it's **over 200x faster** (see below), and a bit easier to code, basically just ``` add.accumulate(diff) ``` Comparison between numpy and direct list manipulation: ``` import numpy as nx import timeit N = 10000 diff_nx = nx.zeros(N, dtype=nx.in...
Python singleton / object instantiation
1,363,839
5
2009-09-01T18:10:16Z
1,363,857
17
2009-09-01T18:16:39Z
[ "python", "singleton" ]
I'm learning Python and i've been trying to implement a Singleton-type class as a test. The code i have is as follows: ``` _Singleton__instance = None class Singleton: def __init__(self): global __instance if __instance == None: self.name = "The one" __instance =...
Assigning to an argument or any other local variable (barename) cannot ever, possibly have ANY effect outside the function; that applies to your `self = whatever` as it would to ANY other assignment to a (barename) argument or other local variable. Rather, override `__new__`: ``` class Singleton(object): __insta...
Stopping python using ctrl+c
1,364,173
45
2009-09-01T19:17:13Z
1,364,179
23
2009-09-01T19:18:43Z
[ "python" ]
I have a python script that uses threads and makes lots of HTTP requests. I think what's happening is that while a HTTP request (using urllib2) is reading, it's blocking and not responding to `Ctrl``C` to stop the program. Is there any way around this?
If it is running in the Python shell use `Ctrl` + `Z`, otherwise locate the `python` process and kill it.
Stopping python using ctrl+c
1,364,173
45
2009-09-01T19:17:13Z
1,364,199
58
2009-09-01T19:21:49Z
[ "python" ]
I have a python script that uses threads and makes lots of HTTP requests. I think what's happening is that while a HTTP request (using urllib2) is reading, it's blocking and not responding to `Ctrl``C` to stop the program. Is there any way around this?
The only sure way is to use `Ctrl``Break`. Stops every python script instantly! (Note that on some keyboards, "Break" is labeled as "Pause".)
Stopping python using ctrl+c
1,364,173
45
2009-09-01T19:17:13Z
1,364,409
44
2009-09-01T20:12:04Z
[ "python" ]
I have a python script that uses threads and makes lots of HTTP requests. I think what's happening is that while a HTTP request (using urllib2) is reading, it's blocking and not responding to `Ctrl``C` to stop the program. Is there any way around this?
Pressing `Ctrl` + `c` while a python program is running will cause python to raise a [KeyboardInterupt](http://docs.python.org/library/exceptions.html#exceptions.KeyboardInterrupt) exception. It's likely that a program that makes lots of HTTP requests will have lots of exception handling code. If the except part of the...
Stopping python using ctrl+c
1,364,173
45
2009-09-01T19:17:13Z
21,460,045
14
2014-01-30T15:05:31Z
[ "python" ]
I have a python script that uses threads and makes lots of HTTP requests. I think what's happening is that while a HTTP request (using urllib2) is reading, it's blocking and not responding to `Ctrl``C` to stop the program. Is there any way around this?
The interrupt process is hardware and OS dependent. So you will have very different behavior depending on where you run your python script. For example, on Windows machines we have `Ctrl`+`C` (`SIGINT`) and `Ctrl`+`Break` (`SIGBREAK`). So while SIGINT is present on all systems and can be handled and caught, the SIGBRE...
Python generating Python
1,364,640
8
2009-09-01T21:02:28Z
1,364,718
17
2009-09-01T21:21:48Z
[ "code-generation", "python" ]
I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experiment...
We use Jinja2 to fill in a template. It's much simpler. The template looks a lot like Python code with a few `{{something}}` replacements in it.
Python generating Python
1,364,640
8
2009-09-01T21:02:28Z
1,365,182
7
2009-09-01T23:39:09Z
[ "code-generation", "python" ]
I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experiment...
Just read your comment to wintermute - ie: > What I have is a bunch of planets that > I want to store each as their own text > files. I'm not particularly attached > to storing them as python source code, > but I am attached to making them > human-readable. If that's the case, then it seems like you shouldn't need su...
Block requests from *.appspot.com and force custom domain in Google App Engine
1,364,733
14
2009-09-01T21:26:11Z
1,364,875
15
2009-09-01T22:02:16Z
[ "python", "google-app-engine", "redirect" ]
How can I prevent a user from accessing my app at example.appspot.com and force them to access it at example.com? I already have example.com working, but I don't want users to be able to access the appspot domain. I'm using python.
You can check if `os.environ['HTTP_HOST'].endswith('.appspot.com')` -- if so, then you're serving from `something.appspot.com` and can send a redirect, or otherwise alter your behavior as desired. You could deploy this check-and-redirect-if-needed (or other behavior alteration of your choice) in any of various ways (d...
Block requests from *.appspot.com and force custom domain in Google App Engine
1,364,733
14
2009-09-01T21:26:11Z
1,980,033
7
2009-12-30T12:45:25Z
[ "python", "google-app-engine", "redirect" ]
How can I prevent a user from accessing my app at example.appspot.com and force them to access it at example.com? I already have example.com working, but I don't want users to be able to access the appspot domain. I'm using python.
The code posted above has two problems - it tries to redirect secure traffic (which isn't supported on custom domains), and also your cron jobs will fail when Google call them on your appspot domain and you serve up a 301. I posted a slightly modified version to my blog: <http://blog.dantup.com/2009/12/redirecting-req...
Python on Snow Leopard, how to open >255 sockets?
1,364,955
4
2009-09-01T22:27:06Z
1,365,014
16
2009-09-01T22:44:06Z
[ "python", "sockets", "osx" ]
Consider this code: ``` import socket store = [] scount = 0 while True: scount+=1 print "Creating socket %d" % (scount) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) store.append(s) ``` Gives the following result: ``` Creating socket 1 Creating socket 2 ... Creating socket 253 Creating socket...
You can increase available sockets with `ulimit`. Looks like 1200 is the max for non-root users in bash. I can get up to 10240 with zsh. ``` $ ulimit -n 1200 $ python sockets .... Creating socket 1197 Creating socket 1198 Traceback (most recent call last): File "sockets", line 7, in <module> File "/System/Library/...
virtualenv in PowerShell?
1,365,081
11
2009-09-01T23:03:59Z
1,365,119
8
2009-09-01T23:15:02Z
[ "python", "powershell", "virtualenv" ]
Hi fellow pythonistas, there seems to be a problem when [virtualenv](http://pypi.python.org/pypi/virtualenv) is used in PowerShell. When I try to activate my environment in PowerShell like.. > env/scripts/activate .. nothing happens. (the shell prompt should have changed as well as the PATH env. variable .) I guess...
[Here](http://www.leeholmes.com/blog/NothingSolvesEverythingPowerShellAndOtherTechnologies.aspx)'s a post which contains a Powershell script which allows you to run batch files that persistently modify their environment variables. The script propagates any environment variable changes back to the calling PowerShell env...
virtualenv in PowerShell?
1,365,081
11
2009-09-01T23:03:59Z
10,030,999
26
2012-04-05T14:56:40Z
[ "python", "powershell", "virtualenv" ]
Hi fellow pythonistas, there seems to be a problem when [virtualenv](http://pypi.python.org/pypi/virtualenv) is used in PowerShell. When I try to activate my environment in PowerShell like.. > env/scripts/activate .. nothing happens. (the shell prompt should have changed as well as the PATH env. variable .) I guess...
**[The latest version of virtualenv](http://pypi.python.org/pypi/virtualenv) supports PowerShell out-of-the-box**. Just make sure you run: ``` Scripts\activate.ps1 ``` instead of ``` Scripts\activate ``` The latter will execute `activate.bat`, which doesn't work on PowerShell.
Is storing user configuration settings on database OK?
1,365,164
2
2009-09-01T23:32:52Z
1,365,178
8
2009-09-01T23:38:23Z
[ "python", "database", "settings", "code-smell" ]
I'm building a fairly large enterprise application made in python that on its first version will require network connection. I've been thinking in keeping some user settings stored on the database, instead of a file in the users home folder. Some of the advantages I've thought of are: * the user can change computers...
This is pretty standard. Go for it. The caveat is that when you take the database down for maintenance, no one can use the app because their profile is inaccessible. You can either solve that by making a 100%-on db solution, or, more easily, through some form of caching of profiles locally (an "offline" mode of operat...
On localhost, how to pick a free port number?
1,365,265
91
2009-09-02T00:07:14Z
1,365,281
28
2009-09-02T00:12:53Z
[ "python", "sockets", "ipc", "port" ]
I try to play with inter process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally, server is able to launch slaves in a separate process and listens on some port and the slaves do their work and submit the result to the ma...
Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with `getsockname()` right after `bind()`.
On localhost, how to pick a free port number?
1,365,265
91
2009-09-02T00:07:14Z
1,365,284
143
2009-09-02T00:14:14Z
[ "python", "sockets", "ipc", "port" ]
I try to play with inter process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally, server is able to launch slaves in a separate process and listens on some port and the slaves do their work and submit the result to the ma...
Do not bind to a specific port, or bind to port 0, e.g. `sock.bind(('', 0))`. The OS will then pick an available port for you. You can get the port that was chosen using `sock.getsockname()[1]`, and pass it on to the slaves so that they can connect back.
random.choice not random
1,366,047
13
2009-09-02T06:06:22Z
1,366,234
12
2009-09-02T07:11:52Z
[ "python", "random" ]
I'm using Python 2.5 on Linux, in multiple parallel FCGI processes. I use ``` chars = string.ascii_letters + string.digits cookie = ''.join([random.choice(chars) for x in range(32)]) ``` to generate distinct cookies. Assuming that the RNG is seeded from /dev/urandom, and that the sequence of random numbers co...
It shouldn't be generating duplicates. ``` import random chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" def gen(): return ''.join([random.choice(chars) for x in range(32)]) test = [gen() for i in range(100000)] print len(test), len(set(test)) # 100000 100000 ``` The chances of duplicate...
Django session expiry?
1,366,146
11
2009-09-02T06:42:14Z
1,371,117
25
2009-09-03T02:16:31Z
[ "python", "django" ]
From django's documentation, I became under the impression that calling: ``` request.session.set_expiry(300) ``` from one view would cause the session to expire after five minutes *inactivity*; however, this is not the behavior that I'm experiencing in django trunk. If I call this method from one view, and browse aro...
As the author of those methods, I can see that the documentation isn't very clear regarding this. Your observations are correct: only requests which cause the session to be altered is considered "activity". You can use the [`SESSION_SAVE_EVERY_REQUEST`](http://docs.djangoproject.com/en/dev/topics/http/sessions/#sessio...
Python (Imaging library): Resample string as argument
1,367,029
2
2009-09-02T11:03:37Z
1,367,066
7
2009-09-02T11:13:50Z
[ "python", "python-imaging-library" ]
Python beginner question. Code below should explain my problem: ``` import Image resolution = (200,500) scaler = "Image.ANTIALIAS" im = Image.open("/home/user/Photos/DSC00320.JPG") im.resize(resolution , scaler) ``` RESULT: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/...
Well, then Image.ANTIALIAS is not a string, so don't treat it as one: ``` scaler = Image.ANTIALIAS ```
Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"
1,367,373
62
2009-09-02T12:23:43Z
1,371,363
8
2009-09-03T03:55:58Z
[ "python", "linux", "memory" ]
**Note:** This question was originally asked [here](http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory) but the bounty time expired even though an acceptable answer was not actually found. I am re-asking this question including all details provided i...
swap may not be the red herring previously suggested. How big is the python process in question just before the `ENOMEM`? Under kernel 2.6, `/proc/sys/vm/swappiness` controls how aggressively the kernel will turn to swap, and `overcommit*` files how much and how precisely the kernel may apportion memory with a wink an...
Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"
1,367,373
62
2009-09-02T12:23:43Z
13,329,386
50
2012-11-11T07:30:08Z
[ "python", "linux", "memory" ]
**Note:** This question was originally asked [here](http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory) but the bounty time expired even though an acceptable answer was not actually found. I am re-asking this question including all details provided i...
As a general rule (i.e. in vanilla kernels), `fork`/`clone` failures with `ENOMEM` [**occur specifically**](https://github.com/torvalds/linux/blob/master/kernel/fork.c) because of either **an honest to God out-of-memory condition** (`dup_mm`, `dup_task_struct`, `alloc_pid`, `mpol_dup`, `mm_init` etc. croak), or because...
Reading a website with asyncore
1,367,453
7
2009-09-02T12:39:25Z
1,367,499
7
2009-09-02T12:47:16Z
[ "python", "web-services", "sockets" ]
I would like to read a website asynchronously, which isnt possible with urllib as far as I know. Now I tried reading with with plain sockets, but HTTP is giving me hell. I run into all kind of funky encodings, for example transfer-encoding: chunked, have to parse all that stuff manually, and I feel like coding C, not p...
You can implement an asynchronous call yourself. For each call, start a new thread (or try to get one from a pool) and use a callback to process it. You can do this very nicely with a decorator: ``` def threaded(callback=lambda *args, **kwargs: None, daemonic=False): """Decorate a function to run in its own thre...
How to decorate a method inside a class?
1,367,514
35
2009-09-02T12:50:19Z
1,367,530
27
2009-09-02T12:52:30Z
[ "python", "decorator" ]
Am attempting to decorate a method inside a class but python is throwing an error on me. My class looks like this: ``` from pageutils import formatHeader myPage(object): def __init__(self): self.PageName = '' def createPage(self): pageHeader = self.createHeader() @formatHeader #<----- decorat...
Python automatically passes the class instance as reference. (The `self` argument which is seen in all class methods). You could do: ``` def formatHeader(fn): def wrapped(self=None): return '<div class="page_header">'+fn(self)+'</div>' return wrapped ```
How to decorate a method inside a class?
1,367,514
35
2009-09-02T12:50:19Z
1,367,567
42
2009-09-02T13:01:30Z
[ "python", "decorator" ]
Am attempting to decorate a method inside a class but python is throwing an error on me. My class looks like this: ``` from pageutils import formatHeader myPage(object): def __init__(self): self.PageName = '' def createPage(self): pageHeader = self.createHeader() @formatHeader #<----- decorat...
You are omitting the self parameter which is present in the undecorated function (createHeader in your case). ``` def formatHeader(fn): from functools import wraps @wraps(fn) def wrapper(self): return '<div class="page_header">'+fn(self)+'</div>' return wrapper ``` If you are unsure about the ...
How to count possibilities in python lists
1,367,550
3
2009-09-02T12:57:47Z
1,367,582
10
2009-09-02T13:04:29Z
[ "python" ]
Given a list like this: ``` num = [1, 2, 3, 4, 5] ``` There are 10 three-element combinations: ``` [123, 124, 125, 134, 135, 145, 234, 235, 245, 345] ``` How can I generate this list?
Use [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations): ``` import itertools num = [1, 2, 3, 4, 5] combinations = [] for combination in itertools.combinations(num, 3): combinations.append(int("".join(str(i) for i in combination))) # => [123, 124, 125, 134, 135, 145, 234...
Python methods: default parameter values are evaluated ONCE
1,367,883
3
2009-09-02T14:00:28Z
1,367,928
7
2009-09-02T14:06:48Z
[ "python", "dictionary", "super" ]
I've found a strange issue with subclassing and dictionary updates in New-Style Classes: ``` Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 >>> class a(object): ... def __init__(self, props={}): ... self.props = props ... >>> class b(a): ... def __init__(self,...
`props` should not have a default value like that. Do this instead: ``` class a(object): def __init__(self, props=None): if props is None: props = {} self.props = props ``` This is a common python ["gotcha"](http://www.ferg.org/projects/python%5Fgotchas.html#contents%5Fitem%5F6rops).