title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Is there a Python interface to the Apache scoreboard (for server statistics)? | 1,028,408 | <p>In short: Is there an existing open-source Python interface for the Apache scoreboard IPC facility? I need to collect statistics from a running server WITHOUT using the "<a href="http://httpd.apache.org/docs/2.2/mod/mod%5Fstatus.html" rel="nofollow">mod_status</a>" HTTP interface, and I'd like to avoid Perl if pos... | 1 | 2009-06-22T17:20:22Z | 1,029,259 | <p>Apache::Scoreboard can both fetch the scoreboard over HTTP, or, if it is loaded into the same server, access the scoreboard memory directly. This is done via a XS extension (i.e. native C). See <a href="http://svn.apache.org/repos/asf/httpd/httpd/trunk/include/scoreboard.h" rel="nofollow">httpd/include/scoreboard.... | 3 | 2009-06-22T20:33:20Z | [
"python",
"perl",
"apache",
"http"
] |
Stop execution of a script called with execfile | 1,028,609 | <p>Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried <code>exit()</code>, but it doesn't allow <code>main.py</code> to finish. </p>
<pre><code># main.py
print "Main starting"
execfile("script.py")
print "This should print"
# scrip... | 9 | 2009-06-22T17:58:34Z | 1,028,628 | <pre><code># script.py
def main():
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
# <insert magic command>
return;
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not ... | 2 | 2009-06-22T18:02:36Z | [
"python",
"flow-control",
"execfile"
] |
Stop execution of a script called with execfile | 1,028,609 | <p>Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried <code>exit()</code>, but it doesn't allow <code>main.py</code> to finish. </p>
<pre><code># main.py
print "Main starting"
execfile("script.py")
print "This should print"
# scrip... | 9 | 2009-06-22T17:58:34Z | 1,028,632 | <p><code>main</code> can wrap the <code>execfile</code> into a <code>try</code>/<code>except</code> block: <code>sys.exit</code> raises a SystemExit exception which <code>main</code> can catch in the <code>except</code> clause in order to continue its execution normally, if desired. I.e., in <code>main.py</code>:</p>
... | 14 | 2009-06-22T18:04:03Z | [
"python",
"flow-control",
"execfile"
] |
Stop execution of a script called with execfile | 1,028,609 | <p>Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried <code>exit()</code>, but it doesn't allow <code>main.py</code> to finish. </p>
<pre><code># main.py
print "Main starting"
execfile("script.py")
print "This should print"
# scrip... | 9 | 2009-06-22T17:58:34Z | 1,029,296 | <p>What's wrong with plain old exception handling?</p>
<p>scriptexit.py</p>
<pre><code>class ScriptExit( Exception ): pass
</code></pre>
<p>main.py</p>
<pre><code>from scriptexit import ScriptExit
print "Main Starting"
try:
execfile( "script.py" )
except ScriptExit:
pass
print "This should print"
</code></p... | 1 | 2009-06-22T20:44:27Z | [
"python",
"flow-control",
"execfile"
] |
Python MySQLdb update query fails | 1,028,671 | <p>Okay. I've built here a mysql query browser, like navicat. Using MySQLdb to perform queries.</p>
<p>Here's the weird part. When i run the query through the program(using MySQLdb), it gives me success, affected rows = 1, but when i look at it in phpmyadmin, the value hasn't changed.</p>
<p>so before i perform the q... | 13 | 2009-06-22T18:14:45Z | 1,028,681 | <p>Just a guess: Perhaps the code in Python is running within a transaction, and the transaction might need to be explicitly committed?</p>
<p>Edit: There's an <a href="http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away">entry in the MySQLdb FAQ</a> that might be relevant.</p>
| 16 | 2009-06-22T18:17:32Z | [
"python",
"mysql"
] |
Python MySQLdb update query fails | 1,028,671 | <p>Okay. I've built here a mysql query browser, like navicat. Using MySQLdb to perform queries.</p>
<p>Here's the weird part. When i run the query through the program(using MySQLdb), it gives me success, affected rows = 1, but when i look at it in phpmyadmin, the value hasn't changed.</p>
<p>so before i perform the q... | 13 | 2009-06-22T18:14:45Z | 1,029,016 | <p>I believe @Jason Creighton and @S.Lott are correct.</p>
<p>At least if the table that you're updating is on a transactional storage engine. <code>InnoDB</code> is transactional, <code>ISAM</code> is not.</p>
<p>You either have to call <code>commit()</code> on your connection object before closing it, or you must s... | 19 | 2009-06-22T19:33:48Z | [
"python",
"mysql"
] |
Full-text search on App Engine with Whoosh | 1,028,992 | <p>I need to do full text searching with Google App Engine. I found the project <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh</a> and it works really well, as long as I use the App Engine Development Environement... When I upload my application to App Engine, I am getting the... | 10 | 2009-06-22T19:31:20Z | 1,029,099 | <p>The marshal module is not supported on app engine. It is there, but it is empty. That marshal is working as normal in the dev. environment has been <a href="http://code.google.com/p/googleappengine/issues/detail?id=892" rel="nofollow">registered as an issue</a>.</p>
<p>See <a href="http://code.google.com/appengine/... | 3 | 2009-06-22T19:52:39Z | [
"python",
"google-app-engine",
"full-text-search",
"whoosh"
] |
Full-text search on App Engine with Whoosh | 1,028,992 | <p>I need to do full text searching with Google App Engine. I found the project <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh</a> and it works really well, as long as I use the App Engine Development Environement... When I upload my application to App Engine, I am getting the... | 10 | 2009-06-22T19:31:20Z | 1,029,752 | <p>You could probably solve your problems by downloading and using <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh-Appengine</a>, the Whoosh version that's specifically targeted to working with Google App Engine.</p>
| 6 | 2009-06-22T22:38:53Z | [
"python",
"google-app-engine",
"full-text-search",
"whoosh"
] |
Full-text search on App Engine with Whoosh | 1,028,992 | <p>I need to do full text searching with Google App Engine. I found the project <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh</a> and it works really well, as long as I use the App Engine Development Environement... When I upload my application to App Engine, I am getting the... | 10 | 2009-06-22T19:31:20Z | 3,171,402 | <p>This is an official example about implementing full text search: <a href="http://code.google.com/p/guestbook-example-appengine-full-text-search/" rel="nofollow">http://code.google.com/p/guestbook-example-appengine-full-text-search/</a></p>
<p>I'm currently reading through it as I'm in the need of implementing it, m... | 4 | 2010-07-03T11:52:52Z | [
"python",
"google-app-engine",
"full-text-search",
"whoosh"
] |
Full-text search on App Engine with Whoosh | 1,028,992 | <p>I need to do full text searching with Google App Engine. I found the project <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh</a> and it works really well, as long as I use the App Engine Development Environement... When I upload my application to App Engine, I am getting the... | 10 | 2009-06-22T19:31:20Z | 4,506,020 | <p>See comment #71 here:
<a href="http://code.google.com/p/googleappengine/issues/detail?id=217&q=Whoosh&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary%20Log%20Component#c71" rel="nofollow">http://code.google.com/p/googleappengine/issues/detail?id=217&q=Whoosh&colspec=ID%20Type%20Statu... | 1 | 2010-12-22T03:49:58Z | [
"python",
"google-app-engine",
"full-text-search",
"whoosh"
] |
"Python.exe" crashes when PyQt's setPixmap() is called with a Pixmap | 1,029,033 | <p>I have a program that sends and receives images to each other using sockets.
The server sends the image data using 'image.tostring()' and the client side receives it and turns it back into an image using 'Image.fromstring', then into a QImage using 'ImageQt.ImageQt(image)', turns it into a QPixmap using 'QPixmap.fro... | 4 | 2009-06-22T19:38:05Z | 1,116,190 | <p>It may be worth dumping the image data to a file and checking that you have all the data by loading it into an image viewer. If you get incomplete data, you may still be able to obtain a QImage and create a QPixmap, but it may be invalid.</p>
| 0 | 2009-07-12T15:07:26Z | [
"python",
"pyqt",
"qpixmap"
] |
Interpolation in SciPy: Finding X that produces Y | 1,029,207 | <p>Is there a better way to find which <em>X</em> gives me the <em>Y</em> I am looking for in SciPy? I just began using SciPy and I am not too familiar with each function.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
x = [70, 80, 90, 100, 110]
y = [49.7, 80.6, 122.5,... | 11 | 2009-06-22T20:20:59Z | 1,030,601 | <p>If all you need is linear interpolation, you could use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html?highlight=interp#numpy.interp" rel="nofollow">interp</a> function in numpy.</p>
| 1 | 2009-06-23T04:20:10Z | [
"python",
"numpy",
"scipy",
"interpolation",
"scientific-computing"
] |
Interpolation in SciPy: Finding X that produces Y | 1,029,207 | <p>Is there a better way to find which <em>X</em> gives me the <em>Y</em> I am looking for in SciPy? I just began using SciPy and I am not too familiar with each function.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
x = [70, 80, 90, 100, 110]
y = [49.7, 80.6, 122.5,... | 11 | 2009-06-22T20:20:59Z | 1,031,510 | <p>The UnivariateSpline class in scipy makes doing splines much more pythonic.</p>
<pre><code>x = [70, 80, 90, 100, 110]
y = [49.7, 80.6, 122.5, 153.8, 163.0]
f = interpolate.UnivariateSpline(x, y, s=0)
xnew = np.arange(70,111,1)
plt.plot(x,y,'x',xnew,f(xnew))
</code></pre>
<p>To find x at y then do:</p>
<pre><code... | 15 | 2009-06-23T09:25:18Z | [
"python",
"numpy",
"scipy",
"interpolation",
"scientific-computing"
] |
Interpolation in SciPy: Finding X that produces Y | 1,029,207 | <p>Is there a better way to find which <em>X</em> gives me the <em>Y</em> I am looking for in SciPy? I just began using SciPy and I am not too familiar with each function.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
x = [70, 80, 90, 100, 110]
y = [49.7, 80.6, 122.5,... | 11 | 2009-06-22T20:20:59Z | 1,797,029 | <p>I may have misunderstood your question, if so I'm sorry. I don't think you need to use SciPy. NumPy has a least squares function.</p>
<pre><code>#!/usr/bin/env python
from numpy.linalg.linalg import lstsq
def find_coefficients(data, exponents):
X = tuple((tuple((pow(x,p) for p in exponents)) for (x,y) in da... | 0 | 2009-11-25T13:50:52Z | [
"python",
"numpy",
"scipy",
"interpolation",
"scientific-computing"
] |
Calling a hook function every time an Exception is raised | 1,029,318 | <p>Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code. </p>
<p>Of course, this could be generalized to being able to insert a hook every time an exception is raised.</p>
<p>Would the following code be considered safe for doin... | 9 | 2009-06-22T20:49:39Z | 1,029,342 | <p>If you want to log <em>uncaught</em> exceptions, just use <a href="http://docs.python.org/library/sys.html">sys.excepthook</a>.</p>
<p>I'm not sure I see the value of logging <em>all</em> raised exceptions, since lots of libraries will raise/catch exceptions internally for things you probably won't care about.</p>
| 11 | 2009-06-22T20:56:13Z | [
"python",
"exception"
] |
Calling a hook function every time an Exception is raised | 1,029,318 | <p>Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code. </p>
<p>Of course, this could be generalized to being able to insert a hook every time an exception is raised.</p>
<p>Would the following code be considered safe for doin... | 9 | 2009-06-22T20:49:39Z | 1,029,604 | <p>This code will not affect any exception classes that were created before the start of <code>main</code>, and most of the exceptions that happen will be of such kinds (<code>KeyError</code>, <code>AttributeError</code>, and so forth). And you can't really affect those "built-in exceptions" in the most important sense... | 5 | 2009-06-22T21:54:50Z | [
"python",
"exception"
] |
Calling a hook function every time an Exception is raised | 1,029,318 | <p>Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code. </p>
<p>Of course, this could be generalized to being able to insert a hook every time an exception is raised.</p>
<p>Would the following code be considered safe for doin... | 9 | 2009-06-22T20:49:39Z | 1,029,619 | <p>Your code as far as I can tell would not work. </p>
<ol>
<li><p><code>__init__</code> has to return None and you are trying to return an instance of backup exception. In general if you would like to change what instance is returned when instantiating a class you should override <code>__new__</code>.</p></li>
<li><p... | 6 | 2009-06-22T21:58:56Z | [
"python",
"exception"
] |
Calling a hook function every time an Exception is raised | 1,029,318 | <p>Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code. </p>
<p>Of course, this could be generalized to being able to insert a hook every time an exception is raised.</p>
<p>Would the following code be considered safe for doin... | 9 | 2009-06-22T20:49:39Z | 1,030,028 | <p>Download <a href="http://codespeak.net/pypy/dist/pypy/doc/" rel="nofollow">pypy</a> and instrument it.</p>
| -4 | 2009-06-23T00:12:47Z | [
"python",
"exception"
] |
Formatting cells in Excel with Python | 1,029,500 | <p>How do I format cells in Excel with python?</p>
<p>In particular I need to change the font of several subsequent rows
to be regular instead of bold.</p>
<p>Thnak you,</p>
<p>Alex</p>
| 2 | 2009-06-22T21:30:05Z | 1,029,542 | <p>For generic examples of Excel scripting from Python, <a href="http://snippets.dzone.com/posts/show/2036" rel="nofollow">this snippet</a> is very handy. It doesn't specifically do the "change font to regular", but that's just <code>range.Font.Bold = False</code> in a function otherwise very similar to the <code>set_b... | 1 | 2009-06-22T21:41:27Z | [
"python",
"excel",
"formatting"
] |
Formatting cells in Excel with Python | 1,029,500 | <p>How do I format cells in Excel with python?</p>
<p>In particular I need to change the font of several subsequent rows
to be regular instead of bold.</p>
<p>Thnak you,</p>
<p>Alex</p>
| 2 | 2009-06-22T21:30:05Z | 1,029,576 | <p>Using <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a>:</p>
<pre><code>from xlwt import *
font0 = Font()
font0.bold = False
style0 = XFStyle()
style0.font = font0
wb = Workbook()
ws0 = wb.add_sheet('0')
ws0.write(0, 0, 'myNormalText', style0)
font1 = Font()
font1.bold = True
style1 = XFStyle... | 2 | 2009-06-22T21:49:16Z | [
"python",
"excel",
"formatting"
] |
Formatting cells in Excel with Python | 1,029,500 | <p>How do I format cells in Excel with python?</p>
<p>In particular I need to change the font of several subsequent rows
to be regular instead of bold.</p>
<p>Thnak you,</p>
<p>Alex</p>
| 2 | 2009-06-22T21:30:05Z | 1,029,637 | <p>For using Python for Excel operations in general, I highly recommend checking out <a href="http://www.python-excel.org/" rel="nofollow">this site</a>. There are three python modules that allow you to do pretty much anything you need: <em>xlrd</em> (reading), <em>xlwt</em> (writing), and <em>xlutils</em> (copy/modif... | 1 | 2009-06-22T22:03:05Z | [
"python",
"excel",
"formatting"
] |
Formatting cells in Excel with Python | 1,029,500 | <p>How do I format cells in Excel with python?</p>
<p>In particular I need to change the font of several subsequent rows
to be regular instead of bold.</p>
<p>Thnak you,</p>
<p>Alex</p>
| 2 | 2009-06-22T21:30:05Z | 1,029,819 | <p><a href="http://www.dev-explorer.com/articles/excel-spreadsheets-and-python" rel="nofollow">Here</a> is a brief introduction to using <code>xlwt</code> and the complementary <code>xlrd</code> (for reading <code>.xls</code> files). However, the Reddit <a href="http://www.reddit.com/r/programming/comments/8nwc9/readin... | 1 | 2009-06-22T22:59:18Z | [
"python",
"excel",
"formatting"
] |
How to refuse a recipient in smtpd.SMTPServer.process_message? | 1,029,756 | <p>Let's say your processing a message in an overridden class like:</p>
<pre><code>class MailProcessorServer(smtpd.SMTPServer):
def process_message(self, peer, sender, rcpttos, data):
badrecipients = []
for rcpt in rcpttos:
badrecipients.append(rcpt)
#Here I want to warn the sender via a bounced e... | 1 | 2009-06-22T22:41:04Z | 1,029,829 | <p>As documented only in <a href="http://svn.python.org/view/python/trunk/Lib/smtpd.py?revision=69846&view=markup">the sources</a> (sorry!), <code>process_message</code>'s specs include:</p>
<blockquote>
<p>This function should return None, for
a normal `250 Ok' response; otherwise
it returns the desired re... | 5 | 2009-06-22T23:03:16Z | [
"python",
"email",
"smtp"
] |
How to refuse a recipient in smtpd.SMTPServer.process_message? | 1,029,756 | <p>Let's say your processing a message in an overridden class like:</p>
<pre><code>class MailProcessorServer(smtpd.SMTPServer):
def process_message(self, peer, sender, rcpttos, data):
badrecipients = []
for rcpt in rcpttos:
badrecipients.append(rcpt)
#Here I want to warn the sender via a bounced e... | 1 | 2009-06-22T22:41:04Z | 1,029,836 | <p>The way to reject a message is to return a string with the error code from your <code>process_message</code> method; e.g.</p>
<pre><code>return '550 No such user here'
</code></pre>
<p>However, RFC 821 doesn't allow error code 550 to be returned after the message data has been transfered (it should be returned aft... | 1 | 2009-06-22T23:07:46Z | [
"python",
"email",
"smtp"
] |
Holiday files for G20 countries | 1,029,794 | <p>For proper financial FX option pricing I require the exact number of <em>business</em> days between two dates. These dates can be up to 10 years in the future, for 2 different countries. I therefore need to know, in advance the holidays for both of those countries between the two dates. I plan to restrict myself to ... | 10 | 2009-06-22T22:51:25Z | 1,029,905 | <p><a href="http://www.goodbusinessday.com" rel="nofollow">www.goodbusinessday.com</a></p>
<p>Looks like 1000 USD per year though for what I need. Ouch. </p>
| 0 | 2009-06-22T23:28:49Z | [
"python",
"finance"
] |
Holiday files for G20 countries | 1,029,794 | <p>For proper financial FX option pricing I require the exact number of <em>business</em> days between two dates. These dates can be up to 10 years in the future, for 2 different countries. I therefore need to know, in advance the holidays for both of those countries between the two dates. I plan to restrict myself to ... | 10 | 2009-06-22T22:51:25Z | 1,029,939 | <p>www.bank-holidays.com seems cheaper. </p>
<p>However, if you look at the public holiday for banks in England, you see the following (<a href="http://www.direct.gov.uk/en/Governmentcitizensandrights/LivingintheUK/DG_073741" rel="nofollow">http://www.direct.gov.uk/en/Governmentcitizensandrights/LivingintheUK/DG_07374... | 2 | 2009-06-22T23:42:03Z | [
"python",
"finance"
] |
Holiday files for G20 countries | 1,029,794 | <p>For proper financial FX option pricing I require the exact number of <em>business</em> days between two dates. These dates can be up to 10 years in the future, for 2 different countries. I therefore need to know, in advance the holidays for both of those countries between the two dates. I plan to restrict myself to ... | 10 | 2009-06-22T22:51:25Z | 4,567,170 | <p>If you are able to use java libraries from python please see: <a href="http://jollyday.sourceforge.net" rel="nofollow">http://jollyday.sourceforge.net</a></p>
| 1 | 2010-12-30T23:52:21Z | [
"python",
"finance"
] |
Holiday files for G20 countries | 1,029,794 | <p>For proper financial FX option pricing I require the exact number of <em>business</em> days between two dates. These dates can be up to 10 years in the future, for 2 different countries. I therefore need to know, in advance the holidays for both of those countries between the two dates. I plan to restrict myself to ... | 10 | 2009-06-22T22:51:25Z | 21,462,251 | <p>I recently came across <a href="https://github.com/novapost/workalendar">https://github.com/novapost/workalendar</a>.
I use it for France and it works like a charm.</p>
<pre><code>"""
>>> from datetime import date
>>> from workalendar.europe import France
>>> cal = France()
>>> c... | 16 | 2014-01-30T16:39:01Z | [
"python",
"finance"
] |
python, unittest: is there a way to pass command line options to the app | 1,029,891 | <p>I have a module that imports unittest and has some TestCases. I would like
to accept some command line options (for example below, the name of a data file),
but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using op... | 30 | 2009-06-22T23:23:05Z | 1,029,923 | <p>In your <code>if __name__ == '__main__':</code> section, which you're not showing us, you'll need to <code>optparse</code> and then <code>del sys.argv[1:]</code> before you pass control to <code>unittest</code> code, so that the latter code doesn't try to interpret your command line options <em>again</em> when you'v... | 28 | 2009-06-22T23:37:01Z | [
"python",
"unit-testing"
] |
python, unittest: is there a way to pass command line options to the app | 1,029,891 | <p>I have a module that imports unittest and has some TestCases. I would like
to accept some command line options (for example below, the name of a data file),
but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using op... | 30 | 2009-06-22T23:23:05Z | 1,030,002 | <p>You should not take arguments and options to run unittests, as you make them run under different, less predictable conditions this way. You should figure out why you need to run tests with different data, and make you test suite complete enough to cover the ground of all data sets without being run differently each ... | -6 | 2009-06-23T00:02:49Z | [
"python",
"unit-testing"
] |
python, unittest: is there a way to pass command line options to the app | 1,029,891 | <p>I have a module that imports unittest and has some TestCases. I would like
to accept some command line options (for example below, the name of a data file),
but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using op... | 30 | 2009-06-22T23:23:05Z | 8,660,290 | <p>Building on Alex's answer, it's actually pretty easy to do using <a href="http://docs.python.org/library/argparse.html"><code>argparse</code></a>:</p>
<pre><code>if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--input', default='My Input')
parser.add_argument('filename... | 33 | 2011-12-28T19:23:36Z | [
"python",
"unit-testing"
] |
python, unittest: is there a way to pass command line options to the app | 1,029,891 | <p>I have a module that imports unittest and has some TestCases. I would like
to accept some command line options (for example below, the name of a data file),
but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using op... | 30 | 2009-06-22T23:23:05Z | 26,509,598 | <p>For small standalone apps, I use an initial sentinel option (-t) and call unittest.main() before calling argparse.ArgumentParser()</p>
<pre><code>if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] in ["-t", "--test"]:
del(sys.argv[1])
sys.exit(unittest.main()) # pass sys.argv[
... | 1 | 2014-10-22T14:15:55Z | [
"python",
"unit-testing"
] |
Formatting with mako | 1,029,965 | <p>Anyone know how to format the length of a string with Mako?</p>
<p>The equivalent of <em>print "%20s%10s" % ("string 1", "string 2")</em>?</p>
| 2 | 2009-06-22T23:51:31Z | 1,029,975 | <p>you can use python's string formatting fairly easily in mako</p>
<pre><code>${"%20s%10s" % ("string 1", "string 2")}
</code></pre>
<p>giving:</p>
<pre><code>>>> from mako.template import Template
>>> Template('${"%20s%10s" % ("string 1", "string 2")}').render()
' string 1 string 2'
<... | 7 | 2009-06-22T23:53:51Z | [
"python",
"template-engine",
"mako"
] |
Does python have a "causes_exception()" function? | 1,030,070 | <p>I have the following code:</p>
<pre><code>def causes_exception(lamb):
try:
lamb()
return False
except:
return True
</code></pre>
<p>I was wondering if it came already in any built-in library?</p>
<p>/YGA</p>
<p>Edit: Thx for all the commentary. It's actually impossible to detect whe... | 0 | 2009-06-23T00:33:17Z | 1,030,083 | <p>I'm not aware of that function, or anything similar, in the Python standard library.</p>
<p>It's rather misleading - if I saw it used, I might think it told you <em>without calling the function</em> whether the function could raise an exception.</p>
| 2 | 2009-06-23T00:38:30Z | [
"python"
] |
Does python have a "causes_exception()" function? | 1,030,070 | <p>I have the following code:</p>
<pre><code>def causes_exception(lamb):
try:
lamb()
return False
except:
return True
</code></pre>
<p>I was wondering if it came already in any built-in library?</p>
<p>/YGA</p>
<p>Edit: Thx for all the commentary. It's actually impossible to detect whe... | 0 | 2009-06-23T00:33:17Z | 1,030,085 | <p>No, as far as I know there is no such function in the standard library. How would it be useful? I mean, presumably you would use it like this:</p>
<pre><code>if causes_exception(func):
# do something
else:
# do something else
</code></pre>
<p>But instead, you could just do </p>
<pre><code>try:
func()
... | 8 | 2009-06-23T00:39:25Z | [
"python"
] |
Does python have a "causes_exception()" function? | 1,030,070 | <p>I have the following code:</p>
<pre><code>def causes_exception(lamb):
try:
lamb()
return False
except:
return True
</code></pre>
<p>I was wondering if it came already in any built-in library?</p>
<p>/YGA</p>
<p>Edit: Thx for all the commentary. It's actually impossible to detect whe... | 0 | 2009-06-23T00:33:17Z | 1,030,147 | <p>There's <code>assertRaises(exception, callable)</code> in <code>unittest</code> module and this is probably the only place where such check makes sense.</p>
<p>In regular code you can never be 100% sure that <code>causes_exception</code> you suggested are not causing any side effects.</p>
| 4 | 2009-06-23T01:01:14Z | [
"python"
] |
Does urllib2 in Python 2.6.1 support proxy via https | 1,030,113 | <p>Does <a href="http://docs.python.org/library/urllib2.html">urllib2</a> in Python 2.6.1 support proxy via https?</p>
<p>I've found the following at <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml">http://www.voidspace.org.uk/python/articles/urllib2.shtml</a>:</p>
<blockquote>
<p>NOTE</p>
<... | 6 | 2009-06-23T00:50:28Z | 1,030,435 | <p>I'm not sure Michael Foord's article, that you quote, is updated to Python 2.6.1 -- why not give it a try? Instead of telling ProxyHandler that the proxy is only good for http, as you're doing now, register it for https, too (of course you should format it into a variable just once before you call ProxyHandler and ... | 3 | 2009-06-23T02:53:30Z | [
"python",
"proxy",
"https",
"urllib2"
] |
Does urllib2 in Python 2.6.1 support proxy via https | 1,030,113 | <p>Does <a href="http://docs.python.org/library/urllib2.html">urllib2</a> in Python 2.6.1 support proxy via https?</p>
<p>I've found the following at <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml">http://www.voidspace.org.uk/python/articles/urllib2.shtml</a>:</p>
<blockquote>
<p>NOTE</p>
<... | 6 | 2009-06-23T00:50:28Z | 1,871,432 | <p>Incase anyone else have this issue in the future I'd like to point out that it does support https proxying now, make sure the proxy supports it too or you risk running into a bug that puts the python library into an infinite loop (this happened to me).</p>
<p>See the unittest in the python source that is testing ht... | 3 | 2009-12-09T03:35:25Z | [
"python",
"proxy",
"https",
"urllib2"
] |
Does urllib2 in Python 2.6.1 support proxy via https | 1,030,113 | <p>Does <a href="http://docs.python.org/library/urllib2.html">urllib2</a> in Python 2.6.1 support proxy via https?</p>
<p>I've found the following at <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml">http://www.voidspace.org.uk/python/articles/urllib2.shtml</a>:</p>
<blockquote>
<p>NOTE</p>
<... | 6 | 2009-06-23T00:50:28Z | 3,843,062 | <p>Fixed in Python 2.6.3 and several other branches:</p>
<ul>
<li><em><strong></em></strong>_bugs.python.org/issue1424152 (replace _ with http...)</li>
<li><p><a href="http://www.python.org/download/releases/2.6.3/NEWS.txt" rel="nofollow">http://www.python.org/download/releases/2.6.3/NEWS.txt</a></p>
<p>Issue #142415... | 6 | 2010-10-01T21:07:54Z | [
"python",
"proxy",
"https",
"urllib2"
] |
Calling an external program from python | 1,030,114 | <p>So I have this shell script:</p>
<pre><code>echo "Enter text to be classified, hit return to run classification."
read text
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "1.000000" ]
then
echo "Text is not likely to be stupid."
fi
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfil... | 3 | 2009-06-23T00:51:14Z | 1,030,130 | <p>You could clearly run the commands as sub-shells and read the return value, just as in the shell script, and then process the result in Python.</p>
<p>This is simpler than loading C functions.</p>
<p>If you really want to load a function from the <code>stupidfilter</code> library, then first look to see whether so... | 1 | 2009-06-23T00:55:59Z | [
"python",
"c"
] |
Calling an external program from python | 1,030,114 | <p>So I have this shell script:</p>
<pre><code>echo "Enter text to be classified, hit return to run classification."
read text
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "1.000000" ]
then
echo "Text is not likely to be stupid."
fi
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfil... | 3 | 2009-06-23T00:51:14Z | 1,030,227 | <p>To do it just like the shell script does:</p>
<pre><code>import subprocess
text = raw_input("Enter text to be classified: ")
p1 = subprocess.Popen('bin/stupidfilter', 'data/c_trbf')
stupid = float(p1.communicate(text)[0])
if stupid:
print "Text is likely to be stupid"
else:
print "Text is not likely to be... | 8 | 2009-06-23T01:36:00Z | [
"python",
"c"
] |
Flash Characters on Screen in Linux | 1,030,240 | <p>I have a XFCE 4.6 on kernel 2.6. Is there a quick and easy way to flash a message on the screen for a few seconds? </p>
<p>My Thinkpad T60 has 3 volume buttons (up, down, mute). When I pressed the buttons, I would like to flash the volume on the screen for a second on screen. Can it be done with Python? </p>
| 1 | 2009-06-23T01:41:02Z | 1,030,320 | <p><a href="http://goodies.xfce.org/projects/applications/notification-daemon-xfce" rel="nofollow">notification-daemon-xfce</a> allows <a href="http://www.galago-project.org/" rel="nofollow">libnotify</a> clients to show brief messages in XFCE. libnotify has <a href="http://www.galago-project.org/files/releases/source... | 1 | 2009-06-23T02:09:25Z | [
"python",
"linux",
"xfce"
] |
Flash Characters on Screen in Linux | 1,030,240 | <p>I have a XFCE 4.6 on kernel 2.6. Is there a quick and easy way to flash a message on the screen for a few seconds? </p>
<p>My Thinkpad T60 has 3 volume buttons (up, down, mute). When I pressed the buttons, I would like to flash the volume on the screen for a second on screen. Can it be done with Python? </p>
| 1 | 2009-06-23T01:41:02Z | 1,035,241 | <p>The quickest solution is to use notify-send (provided typically in package libnotify-bin) from the command line</p>
<pre><code>notify-send Hello!
</code></pre>
| 1 | 2009-06-23T21:07:53Z | [
"python",
"linux",
"xfce"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>Th... | 26 | 2009-06-23T01:53:37Z | 1,030,381 | <p>You have many ways to single-thread this kind of thing.</p>
<p>One standard approach is <strong>Update First</strong>. You do an update which will seize an exclusive lock on the row; then do your work; and finally commit the change. For this to work, you need to bypass the ORM's caching. </p>
<p>Another standard... | 5 | 2009-06-23T02:28:49Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>Th... | 26 | 2009-06-23T01:53:37Z | 1,030,464 | <p>Database locking is the way to go here. There are plans to add "select for update" support to Django (<a href="http://code.djangoproject.com/ticket/2705" rel="nofollow">here</a>), but for now the simplest would be to use raw SQL to UPDATE the user object before you start to calculate the score.</p>
<hr>
<p>Pessimi... | 8 | 2009-06-23T03:09:14Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>Th... | 26 | 2009-06-23T01:53:37Z | 1,030,471 | <p>This may be oversimplifying your situation, but what about just a JavaScript link replacement? In other words when the user clicks the link or button wrap the request in a JavaScript function which immediately disables / "greys out" the link and replaces the text with "Loading..." or "Submitting request..." info or... | 0 | 2009-06-23T03:15:06Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>Th... | 26 | 2009-06-23T01:53:37Z | 1,955,721 | <p>As of Django 1.1 you can use the ORM's F() expressions to solve this specific problem. </p>
<pre><code>from django.db.models import F
user = request.user
user.points = F('points') + calculate_points(user)
user.save()
</code></pre>
<p>For more details see the documentation:</p>
<p><a href="https://docs.djangopro... | 11 | 2009-12-23T22:40:34Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>Th... | 26 | 2009-06-23T01:53:37Z | 10,987,224 | <p>Django 1.4+ supports <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.select_for_update">select_for_update</a>, in earlier versions you may execute raw SQL queries e.g. <code>select ... for update</code> which depending on underlying DB will lock the row from any u... | 33 | 2012-06-11T20:41:10Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>Th... | 26 | 2009-06-23T01:53:37Z | 24,381,313 | <p>Now, you must use:</p>
<pre><code>Model.objects.select_for_update().get(foo=bar)
</code></pre>
| -1 | 2014-06-24T08:00:19Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Simple User management example for Google App Engine? | 1,030,293 | <p>I am newbie in Google App Engine. While I was going through the tutorial, I found several things that we do in php-mysql is not available in GAE. For example in dataStore auto increment feature is not available. Also I am confused about session management in GAE. Over all I am confused and can not visualize the whol... | 17 | 2009-06-23T01:58:46Z | 1,030,357 | <p><a href="http://www.bubblefoundry.com/blog/2009/05/installing-the-google-app-engine-sdk-and-django-102/">Django</a> is your best bet -- with the version I pointed you to, auth and sessions should both "just work" as per the Django docs. <a href="http://code.google.com/appengine/articles/appengine%5Fhelper%5Ffor%5Fd... | 6 | 2009-06-23T02:19:41Z | [
"php",
"python",
"google-app-engine"
] |
Simple User management example for Google App Engine? | 1,030,293 | <p>I am newbie in Google App Engine. While I was going through the tutorial, I found several things that we do in php-mysql is not available in GAE. For example in dataStore auto increment feature is not available. Also I am confused about session management in GAE. Over all I am confused and can not visualize the whol... | 17 | 2009-06-23T01:58:46Z | 1,030,362 | <p>You don't write user management and registration and all that, because you use Google's own authentication services. This is all included in the App Engine documentation.</p>
| 1 | 2009-06-23T02:22:54Z | [
"php",
"python",
"google-app-engine"
] |
Simple User management example for Google App Engine? | 1,030,293 | <p>I am newbie in Google App Engine. While I was going through the tutorial, I found several things that we do in php-mysql is not available in GAE. For example in dataStore auto increment feature is not available. Also I am confused about session management in GAE. Over all I am confused and can not visualize the whol... | 17 | 2009-06-23T01:58:46Z | 1,033,333 | <p>I tend to use my own user and session manangement</p>
<p>For my web handlers I will attach a decorator called <code>session</code> and one called <code>authorize</code>. The <code>session</code> decorator will attach a session to every request, and the <code>authorize</code> decorator will make sure that the user ... | 22 | 2009-06-23T15:33:11Z | [
"php",
"python",
"google-app-engine"
] |
How to Make a PyMe (Python library) Run in Python 2.4 on Windows? | 1,030,297 | <p>I want to run this <a href="http://pyme.sourceforge.net/" rel="nofollow">library</a> on Python 2.4 in Windows XP.</p>
<p>I installed the pygpgme-0.8.1.win32.exe file but got this:</p>
<pre><code>>>> from pyme import core
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Py... | 0 | 2009-06-23T01:59:42Z | 1,030,335 | <p>While the pygpgme project does not clearly document it, it's clear from the error message you got that their .win32.exe was indeed compiled for Python 2.5.</p>
<p>To compile their code for Python 2.4 (assuming they support that release!), download <a href="http://sourceforge.net/project/downloading.php?group%5Fid=1... | 2 | 2009-06-23T02:12:48Z | [
"python",
"c",
"installation",
"distutils"
] |
Unescape _xHHHH_ XML escape sequences using Python | 1,030,522 | <p>I'm using Python 2.x [not negotiable] to read XML documents [created by others] that allow the content of many elements to contain characters that are not valid XML characters by escaping them using the <code>_xHHHH_</code> convention e.g. ASCII BEL aka U+0007 is represented by the 7-character sequence <code>u"_x000... | 4 | 2009-06-23T03:39:47Z | 1,030,578 | <p>You might as well check for <code>'_x'</code> rather than just <code>_</code>, that won't matter much but surely the two-character sequence's even rarer than the single underscore. Apart from such details, you do seem to be making the best of a bad situation!</p>
| 1 | 2009-06-23T04:03:04Z | [
"python",
"xml",
"escaping"
] |
When to use a Templating Engine in Python? | 1,030,622 | <p>As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools.</p>
<p>But I am very interested in developing instincts on where to use specific tools/techniques.</p>
<p>I've seen a lot mentio... | 3 | 2009-06-23T04:29:34Z | 1,030,650 | <p>A templating engine works on templates to programmatically generate artifacts. A template specifies the skeleton of the artifact and the program fills in the blanks. This can be used to generate almost anything, be it HTML, some kind of script (ie: an RPM SPEC file), Python code which can be executed later, etc.</p>... | 2 | 2009-06-23T04:38:15Z | [
"python",
"templates",
"template-engine"
] |
When to use a Templating Engine in Python? | 1,030,622 | <p>As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools.</p>
<p>But I am very interested in developing instincts on where to use specific tools/techniques.</p>
<p>I've seen a lot mentio... | 3 | 2009-06-23T04:29:34Z | 1,030,697 | <p>As @mikem says, templates help generating whatever form of output you like, in the right conditions. Essentially the first meaningful thing I ever wrote in Python was a templating system -- <a href="http://code.activestate.com/recipes/52305/">YAPTU</a>, for Yet Another Python Templating Utility -- and that was 8+ ye... | 5 | 2009-06-23T05:02:54Z | [
"python",
"templates",
"template-engine"
] |
When to use a Templating Engine in Python? | 1,030,622 | <p>As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools.</p>
<p>But I am very interested in developing instincts on where to use specific tools/techniques.</p>
<p>I've seen a lot mentio... | 3 | 2009-06-23T04:29:34Z | 1,030,719 | <p>Simply put, templating lets you easily write a human readable document by hand and add very simple markup to identify areas that should be replaced by variables, area that should repeat, etc.</p>
<p>Typically a templating language can do only basic "template logic", meaning just enough logic to affect the layout of... | 0 | 2009-06-23T05:07:59Z | [
"python",
"templates",
"template-engine"
] |
Problem with SQLite executemany | 1,030,941 | <p>I can't find my error in the following code. When it is run a type error is given for line: <em>cur.executemany(sql % itr.next())</em> => '<strong>function takes exactly 2 arguments (1 given)</strong>,</p>
<pre><code>import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table ... | 3 | 2009-06-23T06:37:09Z | 1,030,958 | <p>See <a href="http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany" rel="nofollow">the sqlite3 documentation</a>. As you'll see, the <code>Cursor.executemany</code> method expects two parameters. Perhaps you mistook it for the <code>Connection.executemany</code> method which only takes one?</p>
| 2 | 2009-06-23T06:42:10Z | [
"python",
"pysqlite"
] |
Problem with SQLite executemany | 1,030,941 | <p>I can't find my error in the following code. When it is run a type error is given for line: <em>cur.executemany(sql % itr.next())</em> => '<strong>function takes exactly 2 arguments (1 given)</strong>,</p>
<pre><code>import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table ... | 3 | 2009-06-23T06:37:09Z | 1,030,963 | <p>Perhaps you meant:</p>
<blockquote>
<p>cur.executemany(sql, itr)</p>
</blockquote>
<p>also note that the print statement consumes one item from the iterator.</p>
| 0 | 2009-06-23T06:43:54Z | [
"python",
"pysqlite"
] |
Problem with SQLite executemany | 1,030,941 | <p>I can't find my error in the following code. When it is run a type error is given for line: <em>cur.executemany(sql % itr.next())</em> => '<strong>function takes exactly 2 arguments (1 given)</strong>,</p>
<pre><code>import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table ... | 3 | 2009-06-23T06:37:09Z | 1,030,965 | <p>Like it says, executemany takes two arguments. Instead of interpolating the string values yourself with the %, you should pass both the sql and the values and let the db adapter quote them.</p>
<pre><code>sql = " '''insert into %s (%s) values(%%s)'''," % (className, colNames)
cur.executemany(sql, itr.next())
</code... | 3 | 2009-06-23T06:44:18Z | [
"python",
"pysqlite"
] |
Problem with SQLite executemany | 1,030,941 | <p>I can't find my error in the following code. When it is run a type error is given for line: <em>cur.executemany(sql % itr.next())</em> => '<strong>function takes exactly 2 arguments (1 given)</strong>,</p>
<pre><code>import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table ... | 3 | 2009-06-23T06:37:09Z | 1,050,694 | <p>Thank you all for your answers. After pushing and poking for several days and using your guidance the following works. I'm guilty of overthinking my problem. Didn't need an iter() conversion. The objData variable is a list and already an iterable! This was one of the reasons the code didn't work.</p>
<pre><code>imp... | 2 | 2009-06-26T19:03:32Z | [
"python",
"pysqlite"
] |
Login input | 1,030,966 | <p>Suppose
My system login ID is tom2deu.
i have one Python program.
Now i am going to modified this Python program.</p>
<p>My question </p>
<p>Can we print my login ID to a seprate notepad or any other file ?</p>
<p>means can we print any person detail(login ID) who had logged the system and modified the program. ... | 0 | 2009-06-23T06:44:56Z | 1,030,996 | <p>try these..</p>
<p>import os<br>
print os.environ['USERNAME']</p>
<p>or </p>
<p>os.getlogin()</p>
<p>then save in a variable and use file handling to store it as a text file..</p>
| 1 | 2009-06-23T06:51:44Z | [
"python"
] |
Login input | 1,030,966 | <p>Suppose
My system login ID is tom2deu.
i have one Python program.
Now i am going to modified this Python program.</p>
<p>My question </p>
<p>Can we print my login ID to a seprate notepad or any other file ?</p>
<p>means can we print any person detail(login ID) who had logged the system and modified the program. ... | 0 | 2009-06-23T06:44:56Z | 1,031,006 | <p>I'm not sure what problem you're trying to solve, but if you want to track changes to source files you should probably use a version control system such as <a href="http://subversion.tigris.org/" rel="nofollow">Subversion</a>. In a nutshell, it will track all the changes to your source files and also manage conflict... | 2 | 2009-06-23T06:57:23Z | [
"python"
] |
Login input | 1,030,966 | <p>Suppose
My system login ID is tom2deu.
i have one Python program.
Now i am going to modified this Python program.</p>
<p>My question </p>
<p>Can we print my login ID to a seprate notepad or any other file ?</p>
<p>means can we print any person detail(login ID) who had logged the system and modified the program. ... | 0 | 2009-06-23T06:44:56Z | 1,031,130 | <p>If you want a general solution you should take <a href="http://pyinotify.sourceforge.net/" rel="nofollow"><code>pyinotify</code></a>, which is a wrapper for the Linux kernel's <a href="http://en.wikipedia.org/wiki/Inotify" rel="nofollow"><code>inotify</code></a> feature (kernel version >= 2.6.13). With it you can re... | 2 | 2009-06-23T07:37:32Z | [
"python"
] |
Login input | 1,030,966 | <p>Suppose
My system login ID is tom2deu.
i have one Python program.
Now i am going to modified this Python program.</p>
<p>My question </p>
<p>Can we print my login ID to a seprate notepad or any other file ?</p>
<p>means can we print any person detail(login ID) who had logged the system and modified the program. ... | 0 | 2009-06-23T06:44:56Z | 1,031,138 | <p>What you are asking is if you can track who made changes to a file. And that's not a Python question, but a question of the operating system. To be able to track who changed a file, you need to have an auditing system installed. If you use Linux, it has an audit subsystem that you can configure to track this informa... | 0 | 2009-06-23T07:39:13Z | [
"python"
] |
what is python equivalent to PHP $_SERVER? | 1,031,192 | <p>I couldn't find out python equivalent to PHP $_SERVER. </p>
<p>Is there any? Or, what are the methods to bring equivalent results?</p>
<p>Thanks in advance. </p>
| 6 | 2009-06-23T07:55:52Z | 1,031,259 | <p>Using <strong>mod_wsgi</strong>, which I would recommend over mod_python (long story but trust me) ... Your application is passed an <strong>environment</strong> variable such as:</p>
<pre><code>def application(environ, start_response):
...
</code></pre>
<p>And the environment contains typical elements from $_... | 11 | 2009-06-23T08:10:20Z | [
"php",
"python"
] |
what is python equivalent to PHP $_SERVER? | 1,031,192 | <p>I couldn't find out python equivalent to PHP $_SERVER. </p>
<p>Is there any? Or, what are the methods to bring equivalent results?</p>
<p>Thanks in advance. </p>
| 6 | 2009-06-23T07:55:52Z | 1,031,379 | <p>You don't state it explicitly, but I assume you are using <code>mod_python</code>? If so, (and if you don't want to use <code>mod_wsgi</code> instead as suggested earlier) take a look at the documentation for the <a href="http://www.modpython.org/live/current/doc-html/pyapi-mprequest.html" rel="nofollow">request obj... | 1 | 2009-06-23T08:43:04Z | [
"php",
"python"
] |
Find cpu-hogging plugin in multithreaded python | 1,031,425 | <p>I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience.</p>
<p>Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to use for an item and asks it to process th... | 8 | 2009-06-23T08:57:53Z | 1,031,578 | <p>As you said, because of the GIL it is impossible within the same process. </p>
<p>I recommend to start a second monitor process, which listens for life beats from another thread in your original app. Once that time beat is missing for a specified amount of time, the monitor can kill your app and restart it.</p>
| 0 | 2009-06-23T09:41:48Z | [
"python",
"regex",
"multithreading",
"profiling"
] |
Find cpu-hogging plugin in multithreaded python | 1,031,425 | <p>I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience.</p>
<p>Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to use for an item and asks it to process th... | 8 | 2009-06-23T08:57:53Z | 1,031,623 | <p>If would suggest as you have control over framework disable all but one plugin and see.
Basically if you have P1, P2...Pn plugins
run N process and disable P1 in first, P2 in second and so on</p>
<p>it would be much faster as compared to your multithreaded run, as no GIL blocking and you will come to know sooner wh... | 0 | 2009-06-23T09:52:37Z | [
"python",
"regex",
"multithreading",
"profiling"
] |
Find cpu-hogging plugin in multithreaded python | 1,031,425 | <p>I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience.</p>
<p>Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to use for an item and asks it to process th... | 8 | 2009-06-23T08:57:53Z | 1,033,784 | <p>You apparently don't need multithreading, only concurrency because your threads don't share any state : </p>
<p><strong>Try multiprocessing instead of multithreading</strong></p>
<p>Single thread / N subprocesses.
There you can time each request, since no GIL is hold.</p>
<p>Other possibility is to get rid of m... | 3 | 2009-06-23T16:44:16Z | [
"python",
"regex",
"multithreading",
"profiling"
] |
Find cpu-hogging plugin in multithreaded python | 1,031,425 | <p>I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience.</p>
<p>Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to use for an item and asks it to process th... | 8 | 2009-06-23T08:57:53Z | 1,036,119 | <p>I'd still look at nosklo's suggestion. You could profile on a single thread to find the item, and get the dump at your very long run an possibly see the culprit. Yeah, I know it's 20,000 items and will take a long time, but sometimes you just got to suck it up and find the darn thing to convince yourself the proble... | 0 | 2009-06-24T02:05:45Z | [
"python",
"regex",
"multithreading",
"profiling"
] |
Python/Django or C#/ASP.NET for web development? | 1,031,438 | <p>I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.</p>
<p>Thank you.</p>
| 7 | 2009-06-23T09:01:30Z | 1,031,492 | <p>Almost all the well known frameworks and languages can scale. </p>
<p>It doesn't really matter which one you use. Its about how well you structure the code that matters most. </p>
<p>On a personal level it is always good to know more than one language.</p>
<p>But, you can create perfectly scalable Python, PHP, ... | 13 | 2009-06-23T09:21:42Z | [
"asp.net",
"python",
"django",
"scalability"
] |
Python/Django or C#/ASP.NET for web development? | 1,031,438 | <p>I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.</p>
<p>Thank you.</p>
| 7 | 2009-06-23T09:01:30Z | 1,036,216 | <p>Much as I love Python (and, that's a LOT!-), if you're highly skilled at C# and, as you say, "have no experience on Python", <em>your</em> code will be more scalable and suitable (for the next several months, at least) if you stick with what you know best. For a hypothetical developer extremely skilled at both platf... | 14 | 2009-06-24T03:05:07Z | [
"asp.net",
"python",
"django",
"scalability"
] |
Python/Django or C#/ASP.NET for web development? | 1,031,438 | <p>I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.</p>
<p>Thank you.</p>
| 7 | 2009-06-23T09:01:30Z | 1,036,254 | <p>Derek had a great answer, so I won't repeat it. </p>
<p>I would like to make one observation, however. While for the most part, the language choice isn't really a big deal these days, if you really need high performance and scalability, the dynamic nature of python might come back to haunt you. For all the benefits... | 3 | 2009-06-24T03:27:10Z | [
"asp.net",
"python",
"django",
"scalability"
] |
Python/Django or C#/ASP.NET for web development? | 1,031,438 | <p>I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.</p>
<p>Thank you.</p>
| 7 | 2009-06-23T09:01:30Z | 3,224,766 | <p>There is a added scalability cost with going with .NET over Python, the cost of Windows Server licenses (at the minimum, you usually add SQL Server to that as well).</p>
| 1 | 2010-07-11T21:54:51Z | [
"asp.net",
"python",
"django",
"scalability"
] |
encyption/decryption of one time password in python | 1,031,588 | <p>how to encrypt one time password using the public key and again recover it by the private key of the user , i need to do it using python</p>
| 0 | 2009-06-23T09:45:49Z | 1,031,633 | <p>You can use Python's encryption library called PyCrypto (www.pycrypto.org). Here's some overview of Public Key encryption using PyCrypto: <a href="http://www.dlitz.net/software/pycrypto/doc/#crypto-publickey-public-key-algorithms" rel="nofollow">http://www.dlitz.net/software/pycrypto/doc/#crypto-publickey-public-key... | 4 | 2009-06-23T09:54:49Z | [
"python",
"encryption"
] |
encyption/decryption of one time password in python | 1,031,588 | <p>how to encrypt one time password using the public key and again recover it by the private key of the user , i need to do it using python</p>
| 0 | 2009-06-23T09:45:49Z | 1,031,660 | <p>Use an encryption library, for example <a href="https://launchpad.net/pyopenssl" rel="nofollow"><code>pyopenssl</code></a>, which looks more up-to-date then <code>pycrypto</code>.</p>
<blockquote>
<p><code>pyopenssl</code> is a rather thin wrapper around (a subset of) the OpenSSL
library. With thin wrapper I... | 0 | 2009-06-23T10:03:06Z | [
"python",
"encryption"
] |
Profiling self and arguments in python? | 1,031,657 | <p>How do I profile a call that involves self and arguments in python?</p>
<pre><code>def performProfile(self):
import cProfile
self.profileCommand(1000000)
def profileCommand(self, a):
for i in a:
pass
</code></pre>
<p>In the above example how would I profile just the call to profileCommand? I f... | 3 | 2009-06-23T10:02:41Z | 1,031,724 | <p>you need to pass locals/globals dict and pass first argument what you will usually type
e.g.</p>
<pre><code>cProfile.runctx("self.profileCommand(100)", globals(),locals())
</code></pre>
<p>use something like this</p>
<pre><code>class A(object):
def performProfile(self):
import cProfile
cProfil... | 11 | 2009-06-23T10:21:31Z | [
"python",
"profiling"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a modu... | 4 | 2009-06-23T10:03:02Z | 1,031,785 | <p>You should not be saving the IPython extension stuff (<code>?</code>, <code>!</code>, <code>%run</code>) in files. Ever. Those are interactive tools and they are something you type with your hands but never save to a file.</p>
<ol>
<li><p>Find the common features among your files. You have exactly four kinds of ... | 6 | 2009-06-23T10:36:48Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a modu... | 4 | 2009-06-23T10:03:02Z | 1,032,587 | <p>Have you had a look at the IPython module (<code>pydoc IPython</code>)? maybe you can access IPython's utilities through pure Python code.</p>
| 0 | 2009-06-23T13:29:47Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a modu... | 4 | 2009-06-23T10:03:02Z | 1,032,956 | <p>technically if you save a script with the <code>.ipy</code> extension, ipython will see that and use all it's fancy stuff rather than passing directly to the python interpreter. however, i would generally recommend against this, and go the route of S.Lott above.</p>
| 4 | 2009-06-23T14:36:20Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a modu... | 4 | 2009-06-23T10:03:02Z | 1,040,640 | <p>If you enter the commands into an interactive version of IPython and then use the hist command (with -n to remove line numbers), IPython spits out all of the commands that you ran, with the actual python code used in place of !cd !ls, etc. Here's an example. </p>
<pre><code>_ip.system("ls")
_ip.system("ls -F ")
_ip... | 2 | 2009-06-24T20:01:54Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a modu... | 4 | 2009-06-23T10:03:02Z | 7,682,136 | <p>A lot of people strongly believe you're not supposed to have scripts with IPython syntax in them, but if you were curious enough (as I am) and are looking for some fun ways to mix python and shell scripts, you should checkout out my <a href="https://github.com/adgaudio/My-Code/blob/master/projects/ipython_scripting/... | 3 | 2011-10-07T01:07:59Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a modu... | 4 | 2009-06-23T10:03:02Z | 34,419,367 | <p>You can do it.</p>
<p>Here is an example.</p>
<p>This is content of a.ipy file:</p>
<pre><code>%run b.ipy
print(myvar)
print(myfunc())
</code></pre>
<p>This is content of b.ipy file:</p>
<pre><code>myvar = !echo 1
def myfunc():
tmp_var = !echo 2
return tmp_var
</code></pre>
<p>As you can see b.ipy uses !... | 0 | 2015-12-22T15:37:37Z | [
"python",
"module",
"ipython"
] |
python service restart (when compiled to exe) | 1,031,705 | <p>I have a service, as follows:</p>
<pre><code>"""
The most basic (working) CherryPy 3.1 Windows service possible.
Requires Mark Hammond's pywin32 package.
"""
import cherrypy
import win32serviceutil
import win32service
import sys
import __builtin__
__builtin__.theService = None
class HelloWorld:
""" Sample re... | 0 | 2009-06-23T10:16:01Z | 1,031,780 | <p>A non programming-related option:</p>
<p>A windows service can be configured for recovery. Select the <code>recovery</code> tag of the <code>service properties</code> window. You can select to <code>Restart the Service</code> after the first, second or subsequent failures.</p>
<p>A simple idea - why don't you drop... | 3 | 2009-06-23T10:35:25Z | [
"python",
"windows-services",
"restart"
] |
python service restart (when compiled to exe) | 1,031,705 | <p>I have a service, as follows:</p>
<pre><code>"""
The most basic (working) CherryPy 3.1 Windows service possible.
Requires Mark Hammond's pywin32 package.
"""
import cherrypy
import win32serviceutil
import win32service
import sys
import __builtin__
__builtin__.theService = None
class HelloWorld:
""" Sample re... | 0 | 2009-06-23T10:16:01Z | 4,133,207 | <p>I've had exactly the same issue: trying to make a Python-based service exit with an error code so that the services framework can restart it. I tried the approach with <code>ReportServiceStatus(win32service.SERVICE_STOP_PENDING, win32ExitCode=1, svcExitCode=1)</code> as well as <code>sys.exit(1)</code> but none of t... | 2 | 2010-11-09T11:35:18Z | [
"python",
"windows-services",
"restart"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 1,031,860 | <p><code>res = dict(zip(a.values(), a.keys()))</code></p>
| 10 | 2009-06-23T10:55:34Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 1,031,878 | <pre><code>res = dict((v,k) for k,v in a.iteritems())
</code></pre>
| 51 | 2009-06-23T11:00:16Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 1,031,887 | <p>You could try:</p>
<pre><code>d={'one':1,'two':2}
d2=dict((value,key) for key,value in d.iteritems())
d2
{'two': 2, 'one': 1}
</code></pre>
<p>Beware that you cannot 'reverse' a dictionary if</p>
<ol>
<li>More than one key shares the same value. For example <code>{'one':1,'two':1}</code>. The new dictionary can... | 16 | 2009-06-23T11:02:07Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 1,087,700 | <pre><code>In [1]: my_dict = {'x':1, 'y':2, 'z':3}
In [2]: dict((value, key) for key, value in my_dict.iteritems())
Out[2]: {1: 'x', 2: 'y', 3: 'z'}
</code></pre>
| 30 | 2009-07-06T15:43:30Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 1,087,723 | <pre><code>new_dict = dict( (my_dict[k], k) for k in my_dict)
</code></pre>
<p>or even better, but only works in Python 3:</p>
<pre><code>new_dict = { my_dict[k]: k for k in my_dict}
</code></pre>
| 13 | 2009-07-06T15:46:48Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 1,087,838 | <pre><code>new_dict = dict (zip(my_dict.values(),my_dict.keys()))
</code></pre>
| 44 | 2009-07-06T16:09:46Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 1,087,957 | <p>From Python 2.7 on, including 3.0+, there's an arguably shorter, more readable version:</p>
<pre><code>>>> my_dict = {'x':1, 'y':2, 'z':3}
>>> {v: k for k, v in my_dict.items()}
{1: 'x', 2: 'y', 3: 'z'}
</code></pre>
| 29 | 2009-07-06T16:36:39Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 6,855,684 | <p>Suggestion for an improvement for Javier answer :</p>
<pre><code>dict(zip(d.values(),d))
</code></pre>
<p>Instead of <code>d.keys()</code> you can write just <code>d</code>, because if you go through dictionary with an iterator, it will return the keys of the relevant dictionary.</p>
<p>Ex. for this behavior : </... | 4 | 2011-07-28T07:53:07Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 18,043,402 | <p>You can make use of <a href="http://www.python.org/dev/peps/pep-0274/">dict comprehensions</a>:</p>
<pre><code>res = {v : k for k, v in a.iteritems()}
</code></pre>
| 15 | 2013-08-04T13:21:19Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 23,441,363 | <p>Using <strong>loop</strong>:-</p>
<pre><code>newdict = {} #Will contain reversed key:value pairs.
for key, value in zip(my_dict.keys(), my_dict.values()):
# Operations on key/value can also be performed.
newdict[value] = key
</code></pre>
| 0 | 2014-05-03T07:05:45Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 25,221,360 | <p>If you're using Python3, it's slightly different:</p>
<pre><code>res = dict((v,k) for k,v in a.items())
</code></pre>
| 1 | 2014-08-09T17:42:46Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 31,886,677 | <pre><code>dict(map(lambda x: x[::-1], YourDict.items()))
</code></pre>
<p><code>.items()</code> returns a list of tuples of <code>(key, value)</code>. <code>map()</code> goes through elements of the list and applies <code>lambda x:[::-1]</code> to each its element (tuple) to reverse it, so each tuple becomes <code>(v... | 1 | 2015-08-07T21:09:06Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 35,905,027 | <p>Another way to expand on <a href="http://stackoverflow.com/users/4636182/ilya-prokin"">Ilya Prokin</a>'s response is to actually use the <code>reversed</code> function.</p>
<pre><code>dict(map(reversed, my_dict.items()))
</code></pre>
<p>In essence, your dictionary is iterated through (using <code>.items()</c... | 1 | 2016-03-09T23:53:44Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to b... | 28 | 2009-06-23T10:53:12Z | 36,640,615 | <p>Adding an in-place solution:</p>
<pre><code>>>> d = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> for k in list(d.keys()):
... d[d.pop(k)] = k
...
>>> d
{'two': 2, 'one': 1, 'four': 4, 'three': 3}
</code></pre>
<p>In Python3, it is critical that you use <code>list(d.keys())</code>... | 0 | 2016-04-15T07:17:01Z | [
"python",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.