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
How can I use C++ class in Python?
602,580
27
2009-03-02T14:47:11Z
602,594
21
2009-03-02T14:49:48Z
[ "c++", "python", "class" ]
I have implemented a class in C++. I want to use it with Python. **Please suggest step by step method and elaborate each step.** Somthing like this... ``` class Test{ private: int n; public: Test(int k){ n=k; } void setInt(int k){ n = k; } ...
Look into [Boost.Python](http://www.boost.org/doc/libs/1%5F38%5F0/libs/python/doc/index.html). It's a library to write python modules with C++. Also look into [SWIG](http://www.swig.org/) which can also handle modules for other scripting languages. I've used it in the past to write modules for my class and use them wi...
How can I use C++ class in Python?
602,580
27
2009-03-02T14:47:11Z
602,666
8
2009-03-02T15:06:33Z
[ "c++", "python", "class" ]
I have implemented a class in C++. I want to use it with Python. **Please suggest step by step method and elaborate each step.** Somthing like this... ``` class Test{ private: int n; public: Test(int k){ n=k; } void setInt(int k){ n = k; } ...
[ctypes](https://docs.python.org/2/library/ctypes.html) is good. It is really easy to use, and it comes standard with Python. Unfortunately it can only talk to shared libraries (Unix) or DLLs (Windows) that have a C-style interface, which means you can't directly interface to a C++ object. But you could use a handle sy...
How can I access the current executing module or class name in Python?
602,846
15
2009-03-02T15:55:53Z
602,881
9
2009-03-02T16:04:33Z
[ "python", "module" ]
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code: **foo.py:** ``` def f(): print __name__ ``` **bar.py:** ``` from foo import f def b(): f() ``` This obviously does not work as `__name__` is the name of the module that...
I think what you want to use is the [inspect](http://docs.python.org/library/inspect.html) module, to inspect the python runtime stack. Check out this [tutorial](http://telin.ugent.be/~slippens/drupal/node/148). I think it provides an almost exact example of what you want to do.
How can I access the current executing module or class name in Python?
602,846
15
2009-03-02T15:55:53Z
602,967
10
2009-03-02T16:27:58Z
[ "python", "module" ]
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code: **foo.py:** ``` def f(): print __name__ ``` **bar.py:** ``` from foo import f def b(): f() ``` This obviously does not work as `__name__` is the name of the module that...
The "currently executing module" clearly is foo, as that's what contains the function currently running - I think a better description as to what you want is the module of foo's immediate caller (which may itself be foo if you're calling a f() from a function in foo called by a function in bar. How far you want to go u...
How can I access the current executing module or class name in Python?
602,846
15
2009-03-02T15:55:53Z
603,460
26
2009-03-02T18:36:31Z
[ "python", "module" ]
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code: **foo.py:** ``` def f(): print __name__ ``` **bar.py:** ``` from foo import f def b(): f() ``` This obviously does not work as `__name__` is the name of the module that...
From the comment -- not the question. "I am simply curious to see if what I am trying to do is possible." The answer to "is it possible" is always "yes". Always. Unless your question involves time travel, anti-gravity or perpetual motion. Since the answer is always "yes", your question is ill-formed. The real questi...
How can I access the current executing module or class name in Python?
602,846
15
2009-03-02T15:55:53Z
7,810,592
13
2011-10-18T16:27:55Z
[ "python", "module" ]
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code: **foo.py:** ``` def f(): print __name__ ``` **bar.py:** ``` from foo import f def b(): f() ``` This obviously does not work as `__name__` is the name of the module that...
This should work for referencing the current module: ``` import sys sys.modules[__name__] ```
python opens text file with a space between every character
603,115
8
2009-03-02T17:09:38Z
603,162
7
2009-03-02T17:22:06Z
[ "python", "csv", "text-files" ]
Whenever I try to open a .csv file with the python command `fread = open('input.csv', 'r')` it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know ...
The file is encoded in some unicode encoding, but you are reading it as ascii. Try to convert the file to ascii before using it in python.
python opens text file with a space between every character
603,115
8
2009-03-02T17:09:38Z
603,233
12
2009-03-02T17:36:55Z
[ "python", "csv", "text-files" ]
Whenever I try to open a .csv file with the python command `fread = open('input.csv', 'r')` it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know ...
The post by recursive is probably right... the contents of the file are likely encoded with a multi-byte charset. If this is, in fact, the case you can likely read the file in python itself without having to convert it first outside of python. Try something like: ``` fread = open('input.csv', 'rb').read() mytext = fr...
Need python lxml syntax help for parsing html
603,287
16
2009-03-02T17:48:28Z
603,630
27
2009-03-02T19:27:20Z
[ "python", "html-parsing", "lxml" ]
I am brand new to python, and I need some help with the syntax for finding and iterating through html tags using lxml. Here are the use-cases I am dealing with: HTML file is fairly well formed (but not perfect). Has multiple tables on screen, one containing a set of search results, and one each for a header and footer...
Okay, first, in regards to parsing the HTML: if you follow the recommendation of zweiterlinde and S.Lott at least use the version of [beautifulsoup included with lxml](http://lxml.de/elementsoup.html). That way you will also reap the benefit of a nice xpath or css selector interface. However, I personally prefer Ian B...
Using for...else in Python generators
603,641
7
2009-03-02T19:28:09Z
603,651
11
2009-03-02T19:32:18Z
[ "python", "syntax", "for-loop", "generator", "yield" ]
I'm a big fan of Python's [for...else syntax](http://docs.python.org/reference/compound_stmts.html#the-for-statement) - it's surprising how often it's applicable, and how effectively it can simplify code. However, I've not figured out a nice way to use it in a generator, for example: ``` def iterate(i): for value...
You're breaking the definition of a generator, which should throw a StopIteration exception when iteration is complete (which is automatically handled by a return statement in a generator function) So: ``` def iterate(i): for value in i: yield value return ``` Best to let the calling code handle the ...
Multicast in Python
603,852
61
2009-03-02T20:24:10Z
1,151,620
15
2009-07-20T03:40:37Z
[ "python", "multicast" ]
How do you send and receive UDP Multicast in Python? Is there a standard library to do so?
Multicast sender that broadcasts to a multicast group: ``` #!/usr/bin/env python import socket import struct def main(): MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) sock...
Multicast in Python
603,852
61
2009-03-02T20:24:10Z
1,794,373
69
2009-11-25T03:03:07Z
[ "python", "multicast" ]
How do you send and receive UDP Multicast in Python? Is there a standard library to do so?
This works for me: Receive ``` import socket import struct MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', MCAST_PORT)) # use MCAST_GRP instead of '' to listen only ...
Multicast in Python
603,852
61
2009-03-02T20:24:10Z
7,675,304
8
2011-10-06T13:55:47Z
[ "python", "multicast" ]
How do you send and receive UDP Multicast in Python? Is there a standard library to do so?
better use: ``` sock.bind((MCAST_GRP, MCAST_PORT)) ``` instead of: ``` sock.bind(('', MCAST_PORT)) ``` ... because if you want to listen to multiple mcast groups on the same port, you'll get all messages on all listeners
How do you get default headers in a urllib2 Request?
603,856
13
2009-03-02T20:24:41Z
4,034,430
10
2010-10-27T14:36:54Z
[ "python", "urllib2" ]
I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer. However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When...
If you want to see the literal HTTP request that is sent out, and therefore see every last header exactly as it is represented on the wire, then you can tell `urllib2` to use your own version of an `HTTPHandler` that prints out (or saves, or whatever) the outgoing HTTP request. ``` import httplib, urllib2 class MyHTT...
Django set default form values
604,266
136
2009-03-02T22:18:18Z
604,325
245
2009-03-02T22:29:46Z
[ "python", "django", "forms", "model" ]
I have a Model as follows ``` class TankJournal(models.Model): user = models.ForeignKey(User) tank = models.ForeignKey(TankProfile) ts = models.IntegerField(max_length=15) title = models.CharField(max_length=50) body = models.TextField() ``` I have a modelform as follows for that model ``` class JournalFor...
You can use *initial* which is explained [here](http://www.djangobook.com/en/1.0/chapter07/) You have two options either populate the value when calling form constructor: ``` form = JournalForm(initial={'tank': 123}) ``` or set the value in the form definition: ``` tank = forms.IntegerField(widget=forms.HiddenInput...
Analyze audio using Fast Fourier Transform
604,453
83
2009-03-02T23:13:17Z
604,498
10
2009-03-02T23:29:37Z
[ "python", "audio", "signal-processing", "fft", "spectrum" ]
I am trying to create a graphical spectrum analyzer in python. I am currently reading 1024 bytes of a 16 bit dual channel 44,100 Hz sample rate audio stream and averaging the amplitude of the 2 channels together. So now I have an array of 256 signed shorts. I now want to preform a fft on that array, using a module lik...
what you have is a sample whose length in time is 256/44100 = 0.00580499 seconds. This means that your frequency resolution is 1 / 0.00580499 = 172 Hz. The 256 values you get out from Python correspond to the frequencies, basically, from 86 Hz to 255\*172+86 Hz = 43946 Hz. The numbers you get out are complex numbers (h...
Analyze audio using Fast Fourier Transform
604,453
83
2009-03-02T23:13:17Z
604,756
160
2009-03-03T01:19:43Z
[ "python", "audio", "signal-processing", "fft", "spectrum" ]
I am trying to create a graphical spectrum analyzer in python. I am currently reading 1024 bytes of a 16 bit dual channel 44,100 Hz sample rate audio stream and averaging the amplitude of the 2 channels together. So now I have an array of 256 signed shorts. I now want to preform a fft on that array, using a module lik...
The array you are showing is the Fourier Transform coefficients of the audio signal. These coefficients can be used to get the frequency content of the audio. The FFT is defined for complex valued input functions, so the coefficients you get out will be imaginary numbers even though your input is all real values. In or...
Analyze audio using Fast Fourier Transform
604,453
83
2009-03-02T23:13:17Z
10,462,090
23
2012-05-05T13:01:10Z
[ "python", "audio", "signal-processing", "fft", "spectrum" ]
I am trying to create a graphical spectrum analyzer in python. I am currently reading 1024 bytes of a 16 bit dual channel 44,100 Hz sample rate audio stream and averaging the amplitude of the 2 channels together. So now I have an array of 256 signed shorts. I now want to preform a fft on that array, using a module lik...
Although this thread is years old, I found it very heplful. I just wanted to give my input to anyone who finds this and are trying to create something similar. As for the division into bars this should not be done as antti suggest, by dividing the data equally based on the number of bars. The most useful would be to d...
Does Python have something like Perl 5.10's "state" variables?
604,622
8
2009-03-03T00:17:47Z
604,645
17
2009-03-03T00:27:45Z
[ "python", "perl" ]
In Perl 5.10, I can say: ``` sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); ``` ...and it will print out: ``` 1 2 3 ``` Does Python have something like this?
A class may be a better fit here (and is usually a better fit for anything involving "state"): ``` class Stateful(object): def __init__(self): self.state_var = 0 def __call__(self): self.state_var = self.state_var + 1 print self.state_var foo = Stateful() foo() foo() ```
Does Python have something like Perl 5.10's "state" variables?
604,622
8
2009-03-03T00:17:47Z
604,651
9
2009-03-03T00:28:47Z
[ "python", "perl" ]
In Perl 5.10, I can say: ``` sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); ``` ...and it will print out: ``` 1 2 3 ``` Does Python have something like this?
Python has generators which do something similar: <http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement>
Does Python have something like Perl 5.10's "state" variables?
604,622
8
2009-03-03T00:17:47Z
604,657
12
2009-03-03T00:30:11Z
[ "python", "perl" ]
In Perl 5.10, I can say: ``` sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); ``` ...and it will print out: ``` 1 2 3 ``` Does Python have something like this?
The closest parallel is probably to attach values to the function itself. ``` def foo(): foo.bar = foo.bar + 1 foo.bar = 0 foo() foo() foo() print foo.bar # prints 3 ```
Does Python have something like Perl 5.10's "state" variables?
604,622
8
2009-03-03T00:17:47Z
604,658
8
2009-03-03T00:30:49Z
[ "python", "perl" ]
In Perl 5.10, I can say: ``` sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); ``` ...and it will print out: ``` 1 2 3 ``` Does Python have something like this?
Not sure if this is what you're looking for, but python has generator functions that don't return a value per se, but a generator object that generates a new value everytime ``` def gen(): x = 10 while True: yield x x += 1 ``` usage: ``` >>> a = gen() >>> a.next() 10 >>> a.next() 11 >>> a.next() 12...
How would you translate this from Perl to Python?
604,721
11
2009-03-03T00:59:21Z
604,777
7
2009-03-03T01:27:41Z
[ "python", "perl" ]
I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique: ``` sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $tim...
Look at [this answer for a robust method to convert a number to an alphanumeric id](http://stackoverflow.com/questions/410485/whats-the-5-character-alphanumeric-id-in-reddit-url/410504#410504) The code I present doesn't go from 'Z' to 'AA', instead goes to 'BA', but I suppose that doesn't matter, it still produces a u...
How do I access my webcam in Python?
604,749
37
2009-03-03T01:11:44Z
606,154
25
2009-03-03T12:09:22Z
[ "python", "webcam" ]
I would like to access my webcam from Python. I tried using the [VideoCapture](http://videocapture.sourceforge.net/) extension ([tutorial](http://technobabbler.com/?p=22)), but that didn't work very well for me, I had to work around some problems such as it's a bit slow with resolutions >320x230, and sometimes it retu...
OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install `numpy` for the OpenCV Python extension (called `cv2`) to work. At the time of writing (January 2015) there is no Python 3 support yet, so you need to use Python 2. [More information on using Ope...
What's the search engine used in the new Python documentation?
605,888
12
2009-03-03T10:32:52Z
606,064
21
2009-03-03T11:43:27Z
[ "python", "python-sphinx" ]
Is it built-in in [Sphinx](http://sphinx.pocoo.org/)?
It look like Sphinx contains own search engine for English language. See <http://sphinx.pocoo.org/_static/searchtools.js> and searchindex.js/.json (see [Sphinx docs index](http://sphinx.pocoo.org/searchindex.js) 36Kb, [Python docs index](http://docs.python.org/searchindex.js) 857Kb, and [Grok docs](http://grok.zope.org...
Python: how to dump cookies of a mechanize.Browser instance?
606,072
11
2009-03-03T11:47:21Z
606,133
22
2009-03-03T12:02:03Z
[ "python", "cookies", "mechanize-python" ]
I am learning how to use [mechanize](http://wwwsearch.sourceforge.net/mechanize/), a Python module to automate interacting with websites. One feature is the automated handling of cookies. I would to want to dump cookies from a `mechanize.Browser` instance for debugging purposes, but I can't seem to figure this out mys...
``` >>> from mechanize import Browser >>> b = Browser() >>> b._ua_handlers['_cookies'].cookiejar mechanize._clientcookie.CookieJar[] >>> b.open('http://google.com') response_seek_wrapper at 0xb7a922ccL whose wrapped object = closeable_response at 0xb7aa070cL whose fp = socket._fileobject object at 0xb7a94224 >>> >>> b....
Convert bytes to a Python string
606,191
538
2009-03-03T12:23:01Z
606,199
888
2009-03-03T12:26:18Z
[ "python", "string", "python-3.x" ]
I'm using this code to get standard output from an external program: ``` >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] ``` The communicate() method returns an array of bytes: ``` >>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-r...
You need to decode the bytes object to produce a string: ``` >>> b"abcde" b'abcde' # utf-8 is used here because it is a very common encoding, but you # need to use the encoding your data is actually in. >>> b"abcde".decode("utf-8") 'abcde' ```
Convert bytes to a Python string
606,191
538
2009-03-03T12:23:01Z
606,205
66
2009-03-03T12:28:31Z
[ "python", "string", "python-3.x" ]
I'm using this code to get standard output from an external program: ``` >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] ``` The communicate() method returns an array of bytes: ``` >>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-r...
You need to decode the byte string and turn it in to a character (unicode) string. ``` b'hello'.decode(encoding) ``` or ``` str(b'hello', encoding) ```
Convert bytes to a Python string
606,191
538
2009-03-03T12:23:01Z
6,738,578
23
2011-07-18T19:51:15Z
[ "python", "string", "python-3.x" ]
I'm using this code to get standard output from an external program: ``` >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] ``` The communicate() method returns an array of bytes: ``` >>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-r...
I think what you actually want is this: ``` >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] >>> command_text = command_stdout.decode(encoding='windows-1252') ``` Aaron's answer was correct, except that you need to know WHICH encoding to use. And I believe that Windo...
Convert bytes to a Python string
606,191
538
2009-03-03T12:23:01Z
12,073,686
61
2012-08-22T12:57:08Z
[ "python", "string", "python-3.x" ]
I'm using this code to get standard output from an external program: ``` >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] ``` The communicate() method returns an array of bytes: ``` >>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-r...
I think this way is easy: ``` bytes = [112, 52, 52] "".join(map(chr, bytes)) >> p44 ```
Convert bytes to a Python string
606,191
538
2009-03-03T12:23:01Z
21,262,396
14
2014-01-21T15:31:09Z
[ "python", "string", "python-3.x" ]
I'm using this code to get standard output from an external program: ``` >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] ``` The communicate() method returns an array of bytes: ``` >>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-r...
Set universal\_newlines to True, i.e. ``` command_stdout = Popen(['ls', '-l'], stdout=PIPE, universal_newlines=True).communicate()[0] ```
Convert bytes to a Python string
606,191
538
2009-03-03T12:23:01Z
27,527,728
23
2014-12-17T14:23:09Z
[ "python", "string", "python-3.x" ]
I'm using this code to get standard output from an external program: ``` >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] ``` The communicate() method returns an array of bytes: ``` >>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-r...
If you don't know the encoding, then to read binary input into string in Python 3 and Python 2 compatible way, use ancient MS-DOS [cp437](https://en.wikipedia.org/wiki/Code_page_437) encoding: ``` PY3K = sys.version_info >= (3, 0) lines = [] for line in stream: if not PY3K: lines.append(line) else: ...
How can I debug a regular expression in python?
606,350
10
2009-03-03T13:13:45Z
606,371
16
2009-03-03T13:21:12Z
[ "python", "regex", "debugging" ]
Is there a way to debug a regular expression in Python? And I'm not referring to the process of trying and trying till they work :) EDIT: here is how regexes can be debugged in perl : ``` use re 'debug'; my $str = "GET http://some-site.com HTTP/1.1"; if($str =~/get\s+(\S+)/i) { print "MATCH:$1\n"; } ``` The cod...
``` >>> p = re.compile('.*', re.DEBUG) max_repeat 0 65535 any None >>> ``` <http://stackoverflow.com/questions/580993/regex-operator-vs-separate-runs-for-each-sub-expression/582227#582227>
How to get filename of the __main__ module in Python?
606,561
38
2009-03-03T14:24:11Z
606,574
22
2009-03-03T14:27:58Z
[ "python", "python-module" ]
Suppose I have two modules: a.py: ``` import b print __name__, __file__ ``` b.py: ``` print __name__, __file__ ``` I run the "a.py" file. This prints: ``` b C:\path\to\code\b.py __main__ C:\path\to\code\a.py ``` **Question**: how do I obtain the path to the `__main__` module ("a.py" in this case) from wit...
Perhaps this will do the trick: ``` import sys from os import path print path.abspath(sys.modules['__main__'].__file__) ``` Note that, for safety, you should check whether the `__main__` module has a `__file__` attribute. If it's dynamically created, or is just being run in the interactive python console, it won't ha...
How to get filename of the __main__ module in Python?
606,561
38
2009-03-03T14:24:11Z
606,998
49
2009-03-03T16:04:22Z
[ "python", "python-module" ]
Suppose I have two modules: a.py: ``` import b print __name__, __file__ ``` b.py: ``` print __name__, __file__ ``` I run the "a.py" file. This prints: ``` b C:\path\to\code\b.py __main__ C:\path\to\code\a.py ``` **Question**: how do I obtain the path to the `__main__` module ("a.py" in this case) from wit...
``` import __main__ print __main__.__file__ ```
How to get filename of the __main__ module in Python?
606,561
38
2009-03-03T14:24:11Z
608,036
13
2009-03-03T20:29:30Z
[ "python", "python-module" ]
Suppose I have two modules: a.py: ``` import b print __name__, __file__ ``` b.py: ``` print __name__, __file__ ``` I run the "a.py" file. This prints: ``` b C:\path\to\code\b.py __main__ C:\path\to\code\a.py ``` **Question**: how do I obtain the path to the `__main__` module ("a.py" in this case) from wit...
The python code below provides additional functionality, including that it works seamlessly with [`py2exe`](http://www.py2exe.org/) executables. I use similar code to like this to find paths relative to the running script, aka `__main__`. as an added benefit, it works cross-platform including Windows. ``` import imp ...
How does Python's "super" do the right thing?
607,186
43
2009-03-03T16:45:37Z
607,298
33
2009-03-03T17:17:53Z
[ "python", "constructor", "multiple-inheritance", "super", "python-2.5" ]
I'm running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to rig...
Change your code to this and I think it'll explain things (presumably `super` is looking at where, say, `B` is in the `__mro__`?): ``` class A(object): def __init__(self): print "A init" print self.__class__.__mro__ class B(A): def __init__(self): print "B init" print self.__cl...
How does Python's "super" do the right thing?
607,186
43
2009-03-03T16:45:37Z
607,448
14
2009-03-03T17:58:41Z
[ "python", "constructor", "multiple-inheritance", "super", "python-2.5" ]
I'm running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to rig...
I have provided a bunch of links below, that answer your question in more detail and more precisely than I can ever hope to. I will however give an answer to your question in my own words as well, to save you some time. I'll put it in points - 1. super is a builtin function, not an attribute. 2. Every *type* (class) i...
Integrate postfix mail into my (python)webapp
607,548
4
2009-03-03T18:23:31Z
607,622
9
2009-03-03T18:50:21Z
[ "python", "email", "message", "postfix-mta" ]
I have a postfix server listening and receiving all emails received at mywebsite.com Now I want to show these postfix emails in a customized interface and that too for each user To be clear, all the users of mywebsite.com will be given mail addresses like [email protected] who receives email on my production machi...
You want to have postfix deliver to a local mailbox, and then use a webmail system for people to access that stored mail. Don't get hung up on postfix - it just a transfer agent - it takes messages from one place, and puts them somewhere else, it doesn't store messages. So postfix will take the messages over SMTP, and...
Integrate postfix mail into my (python)webapp
607,548
4
2009-03-03T18:23:31Z
607,741
7
2009-03-03T19:17:57Z
[ "python", "email", "message", "postfix-mta" ]
I have a postfix server listening and receiving all emails received at mywebsite.com Now I want to show these postfix emails in a customized interface and that too for each user To be clear, all the users of mywebsite.com will be given mail addresses like [email protected] who receives email on my production machi...
First of all, Postfix mail routing rules can be very complex and your presumably preferred solution involves a lot of trickery in the wrong places. You do not want to accidentally show some user anothers mails, do you? Second, although Postfix can do almost anything, it shouldn't as it only is a MDA (mail delivery agen...
Python parsing
607,760
4
2009-03-03T19:25:17Z
607,803
16
2009-03-03T19:35:41Z
[ "python", "regex", "parsing", "text-parsing" ]
I'm trying to parse the title tag in an RSS 2.0 feed into three different variables for each entry in that feed. Using ElementTree I've already parsed the RSS so that I can print each title [minus the trailing `)`] with the code below: > ``` > feed = getfeed("http://www.tourfilter.com/dallas/rss/by_concert_date") > > ...
Don't let regex scare you off... it's well worth learning. Given the examples above, you might try putting the trailing parenthesis back in, and then using this pattern: ``` import re pat = re.compile('([\w\s]+)\(([\w\s]+)(\d+/\d+)\)') info = pat.match(s) print info.groups() ('Michael Schenker Group ', 'House of Blu...
Python parsing
607,760
4
2009-03-03T19:25:17Z
607,804
7
2009-03-03T19:35:51Z
[ "python", "regex", "parsing", "text-parsing" ]
I'm trying to parse the title tag in an RSS 2.0 feed into three different variables for each entry in that feed. Using ElementTree I've already parsed the RSS so that I can print each title [minus the trailing `)`] with the code below: > ``` > feed = getfeed("http://www.tourfilter.com/dallas/rss/by_concert_date") > > ...
Regular expressions are a great solution to this problem: ``` >>> import re >>> s = 'Michael Schenker Group (House of Blues Dallas 3/26' >>> re.match(r'(.*) \((.*) (\d+/\d+)', s).groups() ('Michael Schenker Group', 'House of Blues Dallas', '3/26') ``` As a side note, you might want to look at the [Universal Feed Par...
Django email
607,819
11
2009-03-03T19:40:23Z
608,218
21
2009-03-03T21:15:14Z
[ "python", "django", "email", "django-email" ]
I am using the Gmail SMTP server to send out emails from users of my website. These are the default settings in my settings.py ``` EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '[email protected]' EMAIL_HOST_PASSWORD = 'pwd' EMAIL_PORT = 587 EMAIL_USE_TLS = True SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL =...
Django only uses **settings.DEFAULT\_FROM\_EMAIL** when any of the mail sending functions pass `None` or empty string as the *sender address*. This can be verified in `django/core/mail.py`. When there is an unhandled exception Django calls the `mail_admins()` function in `django/core/mail.py` which always uses **setti...
is there COMMIT analog in python for writing into a file?
608,316
5
2009-03-03T21:33:02Z
608,322
15
2009-03-03T21:34:57Z
[ "python", "file-io", "commit", "buffering" ]
I have a file open for writing, and a process running for days -- something is written into the file in relatively random moments. My understanding is -- until I do file.close() -- there is a chance nothing is really saved to disk. Is that true? What if the system crashes when the main process is not finished yet? Is ...
You should be able to use `file.flush()` to do this.
Python port binding
608,558
5
2009-03-03T22:46:08Z
608,589
13
2009-03-03T22:55:10Z
[ "python" ]
I've recently been learning python and I just started playing with networking using python's `socket` library. Everything has been going well until recently when my script terminated without closing the connection. The next time I ran the script, I got: ``` File "./alert_server.py", line 9, in <module> s.bind((HOST,...
What you want to do is just before the `bind`, do: ``` s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ``` The reason you are seeing the behaviour you are is that the OS is reserving that particular port for some time after the last connection terminated. This is so that it can properly discard any stray furt...
django- run a script from admin
608,789
4
2009-03-04T00:17:13Z
608,823
10
2009-03-04T00:31:24Z
[ "python", "django" ]
I would like to write a script that is not activated by a certain URL, but by clicking on a link from the admin interface. How do I do this? Thanks!
But a link has to go to a URL, so I think what you mean is you want to have a view function that is only visible in the admin interface, and that view function runs a script? If so, override `admin/base_site.html` template with something this simple: ``` {% extends "admin/base.html" %} {% block nav-global %} <p><a ...
Getting the name of the active window
608,809
5
2009-03-04T00:24:57Z
608,814
7
2009-03-04T00:27:40Z
[ "python", "windows" ]
I want to write a python script on Windows that saves the title of the program that the user uses at a given time like the <http://www.rescuetime.com> . I don't want to use rescuetime because of privacy consideration but instead write a script that does something similar myself to capture data about how much I use my c...
[From daniweb](http://www.daniweb.com/forums/thread134111.html) ``` import win32gui w=win32gui w.GetWindowText (w.GetForegroundWindow()) ```
Creating lists using yield in Ruby and Python
608,951
3
2009-03-04T01:39:33Z
609,059
10
2009-03-04T02:34:45Z
[ "python", "ruby", "list", "yield" ]
I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby. In Python: ``` def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) ``` In Ruby: ``` def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| r...
So, for your new example, try this: ``` def foo(x) (0..x).select { |i| bar(i) } end ``` Basically, unless you're writing an iterator of your own, you don't need `yield` very often in Ruby. You'll probably do a lot better if you stop trying to write Python idioms using Ruby syntax.
Creating lists using yield in Ruby and Python
608,951
3
2009-03-04T01:39:33Z
609,077
7
2009-03-04T02:53:40Z
[ "python", "ruby", "list", "yield" ]
I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby. In Python: ``` def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) ``` In Ruby: ``` def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| r...
For the Python version I would use a generator expression like: ``` (i for i in range(x) if bar(i)) ``` Or for this specific case of filtering values, even more simply ``` itertools.ifilter(bar,range(x)) ```
PY: Url Encode without variable name
609,212
3
2009-03-04T04:23:36Z
609,228
7
2009-03-04T04:31:00Z
[ "python" ]
Is there a way in python to url encode list without variables names? for example q=['with space1', 'with space2'] into qescaped=['with%20space1', 'with%20space2']
You can use [urllib.quote](http://docs.python.org/library/urllib.html#urllib.quote) together with [map](http://docs.python.org/library/functions.html#map): ``` import urllib q = ['with space1', 'with space2'] qescaped = map(urllib.quote, q) ```
<class> has no foreign key to <class> in Django when trying to inline models
609,556
6
2009-03-04T07:22:27Z
611,145
14
2009-03-04T15:46:04Z
[ "python", "django", "django-admin" ]
I need to be able to create a quiz type application with 20 some odd multiple choice questions. I have 3 models: `Quizzes`, `Questions`, and `Answers`. I want in the admin interface to create a quiz, and inline the quiz and answer elements. The goal is to click "Add Quiz", and be transferred to a page with 20 questi...
You can't do ["nested" inlines](http://code.djangoproject.com/ticket/9025) in the Django admin (i.e. you can't have a Quiz with inline Questions, with each inline Question having inline Answers). So you'll need to lower your sights to just having inline Questions (then if you navigate to view a single Question, it coul...
Problems title-casing a string in Python
609,830
2
2009-03-04T09:24:35Z
609,857
8
2009-03-04T09:31:19Z
[ "python" ]
I have a name as a string, in this example "markus johansson". I'm trying to code a program that makes 'm' and 'j' uppercase: ``` name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name...
I guess that what you're trying to achieve is: ``` from string import capwords capwords(name) ``` Which yields: ``` 'Markus Johansson' ``` EDIT: OK, I see you want to tear down a open door. Here's low level implementation. ``` ''.join([char.upper() if prev==' ' else char for char,prev in zip(name,' '+name)]) ```
Problems title-casing a string in Python
609,830
2
2009-03-04T09:24:35Z
610,095
9
2009-03-04T10:55:15Z
[ "python" ]
I have a name as a string, in this example "markus johansson". I'm trying to code a program that makes 'm' and 'j' uppercase: ``` name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name...
``` >>> "markus johansson".title() 'Markus Johansson' ``` Built in string methods are the way to go. EDIT: I see you want to re-invent the wheel. Any particular reason ? You can choose from any number of convoluted methods like: ``` ' '.join(j[0].upper()+j[1:] for j in "markus johansson".split()) ``` Standard Libra...
Charts in django Web Applications
609,944
20
2009-03-04T10:08:21Z
610,019
7
2009-03-04T10:29:38Z
[ "python", "django", "charts" ]
I want to Embed a chart in a Web Application developed using django. I have come across [Google charts API](http://code.google.com/p/google-chartwrapper/), [ReportLab](http://code.djangoproject.com/wiki/Charts), [PyChart](http://home.gna.org/pychart/), [MatPlotLib](http://matplotlib.sourceforge.net/) and [ChartDirecto...
Another choice is [CairoPlot](http://linil.wordpress.com/2008/09/16/cairoplot-11/). We picked matplotlib over the others for some serious graphing inside one of our django apps, primarily because it was the only one that gave us exactly the kind of control we needed. Performance generating PNG's was fine for us but.....
How to know if an object has an attribute in Python
610,883
737
2009-03-04T14:45:59Z
610,893
1,006
2009-03-04T14:48:43Z
[ "python", "attributes" ]
Is there a way in Python to determine if an object has some attribute? For example: ``` >>> a = SomeClass() >>> a.someProperty = value >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' ``` How can you tell if `a` has ...
Try hasattr(): ``` if hasattr(a, 'property'): a.property ``` EDIT: See [zweiterlinde's answer](http://stackoverflow.com/a/610923/117030) below, who offers good advice about asking forgiveness! A very pythonic approach! The general practice in python is that, if the property is likely to be there most of the time...
How to know if an object has an attribute in Python
610,883
737
2009-03-04T14:45:59Z
610,907
23
2009-03-04T14:52:26Z
[ "python", "attributes" ]
Is there a way in Python to determine if an object has some attribute? For example: ``` >>> a = SomeClass() >>> a.someProperty = value >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' ``` How can you tell if `a` has ...
I think what you are looking for is **hasattr**. However, I'd recommend something like this if you want to detect **python properties**- ``` try: getattr(someObject, 'someProperty') except AttributeError: print "Doesn't exist" else print "Exists" ``` The disadvantage here is that attribute errors...
How to know if an object has an attribute in Python
610,883
737
2009-03-04T14:45:59Z
610,922
15
2009-03-04T14:56:26Z
[ "python", "attributes" ]
Is there a way in Python to determine if an object has some attribute? For example: ``` >>> a = SomeClass() >>> a.someProperty = value >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' ``` How can you tell if `a` has ...
According to pydoc, hasattr(obj, prop) simply calls getattr(obj, prop) and catches exceptions. So, it is just as valid to wrap the attribute access with a try statement and catch AttributeError as it is to use hasattr() beforehand. ``` a = SomeClass() try: return a.fake_prop except AttributeError: return defau...
How to know if an object has an attribute in Python
610,883
737
2009-03-04T14:45:59Z
610,923
322
2009-03-04T14:56:28Z
[ "python", "attributes" ]
Is there a way in Python to determine if an object has some attribute? For example: ``` >>> a = SomeClass() >>> a.someProperty = value >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' ``` How can you tell if `a` has ...
As [Jarret Hardie](http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610893#610893) answered, `hasattr` will do the trick. I would like to add, though, that many in the Python community recommend a strategy of "easier to ask for forgiveness than permission" (EAFP) rather than...
How to know if an object has an attribute in Python
610,883
737
2009-03-04T14:45:59Z
611,122
8
2009-03-04T15:41:04Z
[ "python", "attributes" ]
Is there a way in Python to determine if an object has some attribute? For example: ``` >>> a = SomeClass() >>> a.someProperty = value >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' ``` How can you tell if `a` has ...
Depending on the situation you can check with `isinstance` what kind of object you have, and then use the corresponding attributes. With the introduction of [abstract base classes](http://www.python.org/dev/peps/pep-3119/) in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a mo...
How to know if an object has an attribute in Python
610,883
737
2009-03-04T14:45:59Z
611,708
251
2009-03-04T17:54:29Z
[ "python", "attributes" ]
Is there a way in Python to determine if an object has some attribute? For example: ``` >>> a = SomeClass() >>> a.someProperty = value >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' ``` How can you tell if `a` has ...
You can use `hasattr()` or catch `AttributeError`, but if you really just want the value of the attribute with a default if it isn't there, the best option is just to use `getattr()`: ``` getattr(a, 'property', 'default value') ```
What is a good strategy for constructing a directed graph for a game map (in Python)?
610,892
9
2009-03-04T14:48:19Z
611,124
7
2009-03-04T15:41:51Z
[ "python", "graph", "procedural-generation" ]
I'm developing a procedurally-generated game world in Python. The structure of the world will be similar to the MUD/MUSH paradigm of rooms and exits arranged as a directed graph (rooms are nodes, exits are edges). (Note that this is *not* necessarily an acyclic graph, though I'm willing to consider acyclic solutions.) ...
First, you need some sense of Location. Your various objects occupy some amount of coordinate space. You have to decide how regular these various things are. In the trivial case, you can drop them into your coordinate space as simple rectangles (or rectangular solids) to make locations simpler to plan out. If the thi...
Can you give a Django app a verbose name for use throughout the admin?
612,372
95
2009-03-04T20:51:03Z
615,760
11
2009-03-05T17:29:30Z
[ "python", "django" ]
In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?
Give them a verbose\_name property. Don't get your hopes up. You will also need to copy the index view from django.contrib.admin.sites into your own ProjectAdminSite view and include it in your own custom admin instance: ``` class ProjectAdminSite(AdminSite): def index(self, request, extra_context=None): ...
Can you give a Django app a verbose name for use throughout the admin?
612,372
95
2009-03-04T20:51:03Z
3,164,163
85
2010-07-02T08:20:34Z
[ "python", "django" ]
In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?
**Prior to Django 1.7** You can give your application a custom name by defining app\_label in your model definition. But as django builds the admin page it will hash models by their app\_label, so if you want them to appear in one application, you have to define this name in all models of your application. ``` class ...
Can you give a Django app a verbose name for use throughout the admin?
612,372
95
2009-03-04T20:51:03Z
3,628,988
10
2010-09-02T16:08:22Z
[ "python", "django" ]
In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?
Well I started an app called **todo** and have now decided I want it to be named **Tasks**. The problem is that I already have data within my table so my work around was as follows. Placed into the models.py: ``` class Meta: app_label = 'Tasks' db_table = 'mytodo_todo' ``` Hope it helps.
Can you give a Django app a verbose name for use throughout the admin?
612,372
95
2009-03-04T20:51:03Z
5,819,110
30
2011-04-28T13:08:37Z
[ "python", "django" ]
In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?
If you have more than one model in the app just create a model with the Meta information and create subclasses of that class for all your models. ``` class MyAppModel(models.Model): class Meta: app_label = 'My App Label' abstract = True class Category(MyAppModel): name = models.CharField(max_...
Can you give a Django app a verbose name for use throughout the admin?
612,372
95
2009-03-04T20:51:03Z
6,312,798
7
2011-06-10T22:47:20Z
[ "python", "django" ]
In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?
For Django 1.4 (not yet released, but trunk is pretty stable), you can use the following method. It relies on the fact that AdminSite now returns a TemplateResponse, which you can alter before it is rendered. Here, we do a small bit of monkey patching to insert our behaviour, which can be avoided if you use a custom A...
Can you give a Django app a verbose name for use throughout the admin?
612,372
95
2009-03-04T20:51:03Z
27,254,978
19
2014-12-02T17:05:26Z
[ "python", "django" ]
In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?
As stated by rhunwicks' comment to OP, this is now possible out of the box since Django 1.7 Taken from the [docs](https://docs.djangoproject.com/en/1.7/ref/applications/#for-application-authors): ``` # in yourapp/apps.py from django.apps import AppConfig class YourAppConfig(AppConfig): name = 'yourapp' verbo...
Code samples for Django + SWFUpload?
612,734
5
2009-03-04T22:21:07Z
612,898
17
2009-03-04T23:05:31Z
[ "python", "django", "swfupload" ]
Does anyone have any simple code samples for Django + [SWFUpload](http://swfupload.org/)? I have it working perfectly in my PHP application but Django is giving me headaches.
Unfortunately I can't give you any very detailed code samples, but I have quite a bit of experience with working with SWFUpload + Django (for a photo sharing site I work on). Anyway, here are a few pointers that will hopefully help you on your quest for DjSWF happiness :) 1. You'll want to use the cookies plugin (if o...
Why do I get wrong results for hmac in Python but not Perl?
613,111
2
2009-03-05T00:20:15Z
613,271
9
2009-03-05T01:23:29Z
[ "python", "perl", "hash", "hmac" ]
I'm trying to compute hmac using sha-512. The Perl code: ``` use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; ``` and gives the correct hash of ``` 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a70203...
yes indeed -- it seems the Leopard version of python2.5 is the one that is broken. below run on a Penryn-based MBP... ``` $ **uname -a** Darwin lizard-wifi 9.6.0 Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386 i386 dpc@lizard-wifi:~$ **which python** /usr/bin/python ``` R...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
613,207
12
2009-03-05T00:56:12Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
Technically, dictionaries aren't sequences, and therefore can't be sorted. You can do something like ``` sorted(a_dictionary.values()) ``` assuming performance isn't a huge deal. UPDATE: Thanks to the commenters for pointing out that I made this way too complicated in the beginning.
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
613,218
2,257
2009-03-05T00:59:34Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples. For instance, ``` import operator x = {1: 2, 3: 4, 4: 3, ...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
613,228
114
2009-03-05T01:05:22Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
Dicts can't be sorted, but you can build a sorted list from them. A sorted list of dict values: ``` sorted(d.values()) ``` A list of (key, value) pairs, sorted by value: ``` from operator import itemgetter sorted(d.items(), key=itemgetter(1)) ```
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
613,230
34
2009-03-05T01:06:04Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
Pretty much the same as Hank Gay's answer; ``` sorted([(value,key) for (key,value) in mydict.items()]) ```
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
613,326
16
2009-03-05T01:52:18Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
You can create an "inverted index", also ``` from collections import defaultdict inverse= defaultdict( list ) for k, v in originalDict.items(): inverse[v].append( k ) ``` Now your inverse has the values; each value has a list of applicable keys. ``` for k in sorted(inverse): print k, inverse[k] ```
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
2,258,273
365
2010-02-13T16:33:51Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
You could use: `sorted(d.items(), key=lambda x: x[1])` This will sort the dictionary by the values of each entry within the dictionary from smallest to largest.
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
3,177,025
78
2010-07-05T02:50:41Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
In recent Python 2.7, we have the new [OrderedDict](http://docs.python.org/dev/whatsnew/2.7.html#pep-372-adding-an-ordered-dictionary-to-collections) type, which remembers the order in which the items were added. ``` >>> d = {"third": 3, "first": 1, "fourth": 4, "second": 2} >>> for k, v in d.items(): ... print "...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
3,177,911
659
2010-07-05T08:01:16Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
## As simple as: `sorted(dict1, key=dict1.get)` Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question *[Code golf: Word frequency chart](http://stackoverflow.com/questions/3169051/code-golf-word-frequency-chart#3170549)*). Abridged, the pro...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
4,068,769
9
2010-11-01T12:16:41Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
``` from django.utils.datastructures import SortedDict def sortedDictByKey(self,data): """Sorted dictionary order by key""" sortedDict = SortedDict() if data: if isinstance(data, dict): sortedKey = sorted(data.keys()) for k in sortedKey: sortedDict[k] = data[...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
4,215,710
20
2010-11-18T14:19:57Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
I had the same problem, I solved it like this: ``` WantedOutput = sorted(MyDict, key=lambda x : MyDict[x]) ``` (people who answer: "It is not possible to sort a dict" did not read the question!! In fact "I can sort on the keys, but how can I sort based on the values?" clearly means that he wants a list of the keys so...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
5,227,519
12
2011-03-08T02:06:25Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
This is the code: ``` import operator origin_list = [ {"name": "foo", "rank": 0, "rofl": 20000}, {"name": "Silly", "rank": 15, "rofl": 1000}, {"name": "Baa", "rank": 300, "rofl": 20}, {"name": "Zoo", "rank": 10, "rofl": 200}, {"name": "Penguin", "rank": -1, "rofl": 10000} ] print ">> Original >>" f...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
7,237,524
38
2011-08-30T00:30:15Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
It can often be very handy to use **[namedtuple](http://docs.python.org/library/collections.html#collections.namedtuple)**. For example, you have a dictionary of 'name' as keys and 'score' as values and you want to sort on 'score': ``` import collections Player = collections.namedtuple('Player', 'score name') d = {'Jo...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
11,230,132
14
2012-06-27T15:43:45Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
If values are numeric you may also use Counter from collections ``` from collections import Counter x={'hello':1,'python':5, 'world':3} c=Counter(x) print c.most_common() >> [('python', 5), ('world', 3), ('hello', 1)] ```
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
15,310,681
17
2013-03-09T12:30:22Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
You can use the [collections.Counter](http://docs.python.org/2/library/collections.html#collections.Counter). Note, this will work for both numeric and non-numeric values. ``` >>> x = {1: 2, 3: 4, 4:3, 2:1, 0:0} >>> from collections import Counter >>> #To sort in reverse order >>> Counter(x).most_common() [(3, 4), (4,...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
18,375,444
23
2013-08-22T08:38:48Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
In Python 2.7, simply do: ``` from collections import OrderedDict # regular unsorted dictionary d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} # dictionary sorted by key OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) # dictionary sorted...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
22,903,797
9
2014-04-07T04:46:44Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
Why not try this approach. Let us define a dictionary called mydict with the following data: ``` mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':3} ``` If one wanted to sort the dictionary by keys, one could do something like: ``` for key in sorted(mydict.iterkeys()): print "%s: %s"...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
26,049,456
9
2014-09-25T22:56:55Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
You can use a [skip dict](https://pypi.python.org/pypi/skipdict/1.0) which is a dictionary that's permanently sorted by value. ``` >>> data = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} >>> SkipDict(data) {0: 0.0, 2: 1.0, 1: 2.0, 4: 3.0, 3: 4.0} ``` If you use `keys()`, `values()` or `items()` then you'll iterate in sorted order ...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
34,103,440
29
2015-12-05T09:46:06Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
**UPDATE: 5 DECEMBER 2015 using Python 3.5** Whilst I found the accepted answer useful, I was also surprised that it hasn't been updated to reference **[OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict)** from the standard library **collections** module as a viable, modern altern...
Sort a Python dictionary by value
613,183
1,837
2009-03-05T00:49:05Z
34,995,529
13
2016-01-25T14:54:43Z
[ "python", "sorting", "dictionary" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question [How do I sort a list of dictionaries by val...
``` >>> e = {1:39, 4:34, 7:110, 2:87} >>> sortE = sorted(e.items(), key=lambda value: value[1]) >>> print(sortE) [(4, 34), (1, 39), (2, 87), (7, 110)] ``` You can use a lambda function to sort things up by value and store them processed inside a variable, in this case **sortE** with **e** the original dictionary.
Is there a need for a "use strict" Python compiler?
613,364
28
2009-03-05T02:08:25Z
613,435
10
2009-03-05T02:54:53Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
There exist [static analysis tools for Python](http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python), but compile time checks tend to be diametrically opposed to the [run-time binding philosophy](http://python-history.blogspot.com/2009/01/introduction-and-overview.html) that Python em...
Python does have something that can change script syntax: ``` from __future__ import print_function ``` and various other future-features that have syntax implications. It's just that Python's syntax has been stricter, stabler and more well-defined than historical Perl; the kind of things that ‘strict refs’ and â...
Is there a need for a "use strict" Python compiler?
613,364
28
2009-03-05T02:08:25Z
613,499
11
2009-03-05T03:36:24Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
There exist [static analysis tools for Python](http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python), but compile time checks tend to be diametrically opposed to the [run-time binding philosophy](http://python-history.blogspot.com/2009/01/introduction-and-overview.html) that Python em...
"the run-time binding philosophy that Python embraces... makes "use strict" behavior unnecessary [and] especially undesirable" Pretty good summary. Thanks. That is essentially it. Static analysis tools don't help Python enough to be worthwhile. --- **Edit** "I'm asking for us to introspect on *why* we don't need i...
Is there a need for a "use strict" Python compiler?
613,364
28
2009-03-05T02:08:25Z
614,570
7
2009-03-05T12:27:03Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
There exist [static analysis tools for Python](http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python), but compile time checks tend to be diametrically opposed to the [run-time binding philosophy](http://python-history.blogspot.com/2009/01/introduction-and-overview.html) that Python em...
I think there's some confusion as the what "use strict" does, from the comments I'm seeing. It does not turn on compile time type checks (to be like Java). In that sense, Perl progammers are in agreement with python programmers. As S.Lott says above these types of checks don't protect against logic bugs, don't reduce t...
Is there a need for a "use strict" Python compiler?
613,364
28
2009-03-05T02:08:25Z
615,306
32
2009-03-05T15:37:14Z
[ "python", "perl", "compiler-construction", "static-analysis", "use-strict" ]
There exist [static analysis tools for Python](http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python), but compile time checks tend to be diametrically opposed to the [run-time binding philosophy](http://python-history.blogspot.com/2009/01/introduction-and-overview.html) that Python em...
Well, I'm not much of a python programmer, but I'd say that the answer is 'YES'. Any dynamic language that lets you create a variable with any name at any time, could use a 'strict' pragma. Strict vars (one of the options for strict in Perl, 'use strict' turns them all on at once) in Perl requires that all variables ...
Discovering public IP programatically
613,471
23
2009-03-05T03:18:42Z
613,473
8
2009-03-05T03:20:57Z
[ "python", "ip-address", "tcp" ]
I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results) Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it? P.S. I'm planning on writing a short python script to do it
Whenever I wanted to do this, I would just scrape [whatismyip.org](http://whatismyip.org). When you go to the site, it gives you your plain text public IP. Plain and simple. Just have your script access that site and read the IP. I don't know if you were implying this in your post or not, but it isn't possible to get...
Discovering public IP programatically
613,471
23
2009-03-05T03:18:42Z
613,482
17
2009-03-05T03:26:16Z
[ "python", "ip-address", "tcp" ]
I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results) Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it? P.S. I'm planning on writing a short python script to do it
I have made a program that connects to <http://automation.whatismyip.com/n09230945.asp> it is is written in D an getting someone else to tell you what they see your ip as is probably the most reliable way: ``` /* Get my IP address */ import tango.net.http.HttpGet; import tango.io.Stdout; void main() { try...
Discovering public IP programatically
613,471
23
2009-03-05T03:18:42Z
613,565
10
2009-03-05T04:30:19Z
[ "python", "ip-address", "tcp" ]
I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results) Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it? P.S. I'm planning on writing a short python script to do it
Targeting www.whatsmyip.org is rude. They plea not to do that on the page. Only a system on the same level of NAT as your target will see the same IP. For instance, your application may be behind multiple layers of NAT (this happens more as you move away from the US, where the glut of IPs are). STUN is indeed the bes...
Discovering public IP programatically
613,471
23
2009-03-05T03:18:42Z
613,600
20
2009-03-05T04:47:07Z
[ "python", "ip-address", "tcp" ]
I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results) Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it? P.S. I'm planning on writing a short python script to do it
This may be the easiest way. Parse the output of the following commands: 1. run a traceroute to find a router that is less than 3 hops out from your machine. 2. run ping with the option to record the source route and parse the output. The first IP address in the recorded route is your public one. For example, I am on...
Discovering public IP programatically
613,471
23
2009-03-05T03:18:42Z
16,698,596
8
2013-05-22T17:57:52Z
[ "python", "ip-address", "tcp" ]
I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results) Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it? P.S. I'm planning on writing a short python script to do it
**EDIT**: curlmyip.com is no longer available. (thanks maxywb) **Original Post**: As of writing this post, curlmyip.com works. From the command line: ``` curl curlmyip.com ``` It's a third-party website, which may or may not be available a couple years down the road. But for the time being, it seems pretty simple a...
Tool/library for calculating intervals like "last thursday of the month"
614,518
2
2009-03-05T12:11:07Z
614,662
7
2009-03-05T13:03:01Z
[ "python", "datetime", "date" ]
I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month". i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever...
Neither mxDateTime nor Datejs nor that webservice support "last thursday of the month". The OP wants to know all of the last thursdays of the month for, say, a full year. mxDateTime supports the operations, but the question must be posed in Python code, not as a string. The best I could figure is [parsedatetime](http...
Is it possible to remove recursion from this function?
616,416
3
2009-03-05T20:09:17Z
616,432
21
2009-03-05T20:12:19Z
[ "python", "recursion" ]
I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY\_Go function. ``` def XinY_Go(x,y,index,slots): if (y - index) == 1: slots[index] = x print slots slots[index] = 0 return for i in range(x+1): slots[index] = ...
Everything we think of as recursion can also be thought of as a stack-based problem, where the recursive function just uses the program's call stack rather than creating a separate stack. That means any recursive function can be re-written using a stack instead. I don't know python well enough to give you an implement...
Is it possible to remove recursion from this function?
616,416
3
2009-03-05T20:09:17Z
616,666
14
2009-03-05T21:19:22Z
[ "python", "recursion" ]
I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY\_Go function. ``` def XinY_Go(x,y,index,slots): if (y - index) == 1: slots[index] = x print slots slots[index] = 0 return for i in range(x+1): slots[index] = ...
A naive implementation of [@Joel Coehoorn's suggestion](http://stackoverflow.com/questions/616416/is-it-possible-to-remove-recursion-from-this-function/616432#616432) follows: ``` def XinY_Stack(x, y): stack = [(x, 0, [0]*y)] while stack: x, index, slots = stack.pop() if (y - index) == 1: ...