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
list
How to add an automatic filter to a relation with SQLAlchemy?
267,861
<p>I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)</p> <p>For example, if an object "parent" has a "children" re...
7
2008-11-06T07:33:11Z
267,975
<p>I'm only currently developing agains 0.4.something, but here's how I'd suggest it:</p> <pre><code>db.query(Object).filter(Object.first==value).filter(Object.second==False).all() </code></pre> <p>I think that's what you are trying to do, right?</p> <p>(Note: written in a web browser, not real code!)</p>
-1
2008-11-06T08:48:54Z
[ "python", "sqlalchemy" ]
How to add an automatic filter to a relation with SQLAlchemy?
267,861
<p>I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)</p> <p>For example, if an object "parent" has a "children" re...
7
2008-11-06T07:33:11Z
278,710
<p>The and_() function is the correct way to do logical conjunctions in SQLAlchemy, together with the &amp; operator, but be careful with the latter as it has surprising precedence rules, i.e. higher precedence than comparison operators. </p> <p>You could also use a string as a primary join with the text() constructor...
3
2008-11-10T18:23:30Z
[ "python", "sqlalchemy" ]
How to add an automatic filter to a relation with SQLAlchemy?
267,861
<p>I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)</p> <p>For example, if an object "parent" has a "children" re...
7
2008-11-06T07:33:11Z
13,887,876
<blockquote> <p>but is there a way to use a string as primaryjoin instead?</p> </blockquote> <p>You can use the following:</p> <pre><code>children = relationship("Children", primaryjoin="and_(Parent.id==Children.parent_id, Children.logically_deleted==False)" </code></pre> <p>This worked for me!</p>
5
2012-12-14T23:51:38Z
[ "python", "sqlalchemy" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some ...
2
2008-11-06T08:50:09Z
267,992
<p>For modules paths, a common practice is putting them in <em>.pth</em> files, as <a href="http://docs.python.org/library/site.html#module-site" rel="nofollow">documented here</a>. The <em>site</em> module provides a space for Site-specific configuration hooks, you can use it to tailor your environment.</p>
1
2008-11-06T08:58:39Z
[ "python" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some ...
2
2008-11-06T08:50:09Z
268,189
<p>Well, with distutils (in the standard library) you have "package data". This is data that lives inside the package itself. <a href="http://docs.python.org/distutils/setupscript.html#installing-package-data" rel="nofollow">Explained here how to do it.</a> This is clearly not ideal, as you will have to use some kind o...
1
2008-11-06T10:11:50Z
[ "python" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some ...
2
2008-11-06T08:50:09Z
268,348
<p>"I often find a need to put paths in my code" -- this isn't very Pythonic to begin with.</p> <p>Ideally, your code lives in some place like site-packages and that's the end of that.</p> <p>Often, we have an installed "application" that uses a fairly fixed set of directories for working files. In linux, we get th...
-1
2008-11-06T11:28:13Z
[ "python" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some ...
2
2008-11-06T08:50:09Z
348,082
<p>The OP here, I've not finally managed to log in using my OpenID.</p> <p>@S.Lott</p> <p>Point well taken, but for some Linux distros it seems to be standard to install application-specific data and application-specific modules in specific locations. I think that making these locations configurable at build/install...
0
2008-12-07T21:09:31Z
[ "python" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some ...
2
2008-11-06T08:50:09Z
349,509
<p>Currently, the best way to bundle data with code is going the <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow">setuptools</a> way and use <code>pkg_resources</code>:</p> <pre><code>from pkg_resources import resource_filename, resource_stream stream = resource_stream("PACKAGE", "path/to/da...
1
2008-12-08T13:11:51Z
[ "python" ]
apache user can not write to .python-eggs
268,015
<p>I have read that I need to set the <code>PYTHON_EGG_CACHE</code> environment variable, or install the python library as an uncompressed .egg</p> <p>Which do you suggest?</p>
3
2008-11-06T09:11:07Z
268,087
<p>It totally depends on if you want to make the egg available as a generally available library or just for a single (or a handful of applications). Are you talking about a Trac installation? If so, there are also a handful of alternatives to make the egg available per instance:</p> <p><a href="http://trac.edgewall.or...
1
2008-11-06T09:38:47Z
[ "python", "apache", "egg", "python-egg-cache" ]
apache user can not write to .python-eggs
268,015
<p>I have read that I need to set the <code>PYTHON_EGG_CACHE</code> environment variable, or install the python library as an uncompressed .egg</p> <p>Which do you suggest?</p>
3
2008-11-06T09:11:07Z
268,106
<p>I got it working by uncompressing the .egg so it did not require the cache directory:</p> <p><a href="http://stackoverflow.com/questions/268025/install-mysqldb-for-python-as-non-compressed-egg">http://stackoverflow.com/questions/268025/install-mysqldb-for-python-as-non-compressed-egg</a></p>
2
2008-11-06T09:46:05Z
[ "python", "apache", "egg", "python-egg-cache" ]
apache user can not write to .python-eggs
268,015
<p>I have read that I need to set the <code>PYTHON_EGG_CACHE</code> environment variable, or install the python library as an uncompressed .egg</p> <p>Which do you suggest?</p>
3
2008-11-06T09:11:07Z
268,110
<p>If you are talking about Trac then the issue you are having is <a href="http://stackoverflow.com/questions/215267/how-do-you-fix-a-trac-installation-that-begins-giving-errors-relating-to-python">this one</a>. It should be solved in trac 0.11.1.</p>
0
2008-11-06T09:47:32Z
[ "python", "apache", "egg", "python-egg-cache" ]
Install MySQLdb (for python) as non-compressed egg
268,025
<p>The install instructions are:</p> <pre><code>$ python setup.py build $ sudo python setup.py install # or su first </code></pre> <p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p> <p>Thanks!</p>
4
2008-11-06T09:15:21Z
268,054
<p>From the <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#command-line-options" rel="nofollow">EasyInstall</a> doc, command line options:</p> <blockquote> <p>--always-unzip, -Z</p> <p>Don't install any packages as zip files, even if the packages are marked as safe for running as a zipfile. </p> ...
3
2008-11-06T09:26:17Z
[ "python", "install", "mysql", "egg" ]
Install MySQLdb (for python) as non-compressed egg
268,025
<p>The install instructions are:</p> <pre><code>$ python setup.py build $ sudo python setup.py install # or su first </code></pre> <p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p> <p>Thanks!</p>
4
2008-11-06T09:15:21Z
268,101
<p>OK, I hate to answer my own question, but:</p> <p>find your python site-packages (mine is /usr/local/lib/python2.5/site-packages )</p> <p>then:</p> <pre><code>$ unzip MySQL_python-1.2.2-py2.5-linux-i686.egg </code></pre> <p>This worked fine for me</p>
7
2008-11-06T09:44:54Z
[ "python", "install", "mysql", "egg" ]
Install MySQLdb (for python) as non-compressed egg
268,025
<p>The install instructions are:</p> <pre><code>$ python setup.py build $ sudo python setup.py install # or su first </code></pre> <p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p> <p>Thanks!</p>
4
2008-11-06T09:15:21Z
268,111
<p>This will tell setuptools to not zip it up:</p> <pre><code>sudo python setup.py install --single-version-externally-managed </code></pre>
1
2008-11-06T09:47:56Z
[ "python", "install", "mysql", "egg" ]
Install MySQLdb (for python) as non-compressed egg
268,025
<p>The install instructions are:</p> <pre><code>$ python setup.py build $ sudo python setup.py install # or su first </code></pre> <p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p> <p>Thanks!</p>
4
2008-11-06T09:15:21Z
1,460,602
<p>I'm a little late to this party, but here's a way to do it that seems to work great:</p> <pre><code>sudo python setup.py install --single-version-externally-managed --root=/ </code></pre> <p>And then you don't use a .python-egg, any *.pth files etc.</p>
4
2009-09-22T14:57:28Z
[ "python", "install", "mysql", "egg" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
268,369
<p>The most recent discussion I've seen on it was in the <a href="http://groups.google.com/group/django-developers/browse_thread/thread/9f0353fe0682b73" rel="nofollow">Proposal: user-friendly API for multi-database support</a> django-developers thread, which also has an example of one way to use multiple databases usin...
4
2008-11-06T11:35:55Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
271,220
<p>I think you will have to resort to "raw sql" .. kinda thing .. <br> look here: <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/sql/</a></p> <p>you need a "connection" to your other database, if you look at <code>django/db/__init__.py</code...
0
2008-11-07T04:08:19Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
272,522
<p>If you read a few of the many (<em>many</em>) threads on this subject in django-dev, you will see that what <em>looks</em> straightforward, isn't. If you pick a single use case, then it looks easy, but as soon as you start to generalize in any way you start to run into trouble.</p> <p>To use the above-referenced th...
3
2008-11-07T15:54:37Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
997,136
<p>Eric Florenzano wrote a very good blog post that allows you some multiple database support at: <a href="http://www.eflorenzano.com/blog/post/easy-multi-database-support-django/" rel="nofollow">Easy MultipleDatabase Support for Django</a>.</p> <p>It starts by creating a new custom manager that allows you to specify ...
2
2009-06-15T16:46:56Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
1,287,729
<p>Eric Florenzano's approach works well if all your databases use the same engine. If you have different engines (Postgres and MSSQL in my case) you will run into many issues deep in the ORM code (such as models/sql/where.py using the default connection's SQL syntax).</p> <p>If you need this to work, you should wait ...
0
2009-08-17T12:37:13Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
1,836,058
<p>If you simply need multiple connections, you can do something like this:</p> <pre><code>from django.db import load_backend myBackend = load_backend('postgresql_psycopg2') # or 'mysql', 'sqlite3', 'oracle' myConnection = myBackend.DatabaseWrapper({ 'DATABASE_HOST': '192.168.1.1', 'DATABASE_NAME': 'my_databas...
9
2009-12-02T21:49:37Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
2,277,593
<p>This will be in Django 1.2.</p> <p>See <a href="http://docs.djangoproject.com/en/dev/topics/db/multi-db/">http://docs.djangoproject.com/en/dev/topics/db/multi-db/</a></p>
6
2010-02-17T00:52:00Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
2,583,949
<p>From Django 1.2, it will support multiple databases. See: <a href="http://docs.djangoproject.com/en/dev/topics/db/multi-db/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/multi-db/</a> Version 1.2 is now in beta</p>
0
2010-04-06T10:00:48Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
8,539,232
<p>There is a "using" directive for queries,saves, and deletes</p> <p><a href="https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database</a></p>
1
2011-12-16T19:33:51Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support M...
9
2008-11-06T09:39:20Z
14,604,432
<p>Multiple database to choose from </p> <p>We always need one named default, the names of the rest are up to you.</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mupltiple_datab_app1', 'USER': 'root', ...
1
2013-01-30T12:49:34Z
[ "python", "django", "database-connection" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
268,285
<p>You can use <code>operator.itemgetter</code> for that:</p> <pre><code>import operator stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iteritems(), key=operator.itemgetter(1))[0] </code></pre> <p>And instead of building a new list in memory use <code>stats.iteritems()</code>. The <code>key</code> parameter to the ...
253
2008-11-06T10:58:45Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
268,303
<p>Thanks, very elegant, I didn't remember that max allows a "key" parameter.</p> <p>BTW, to get the right answer ('b') it has to be:</p> <pre><code>import operator stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iteritems(), key=operator.itemgetter(1))[0] </code></pre>
3
2008-11-06T11:04:28Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
268,350
<p>Here is another one:</p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iterkeys(), key=lambda k: stats[k]) </code></pre> <p>The function <code>key</code> simply returns the value that should be used for ranking and <code>max()</code> returns the demanded element right away.</p>
24
2008-11-06T11:28:56Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
272,269
<pre><code>key, value = max(stats.iteritems(), key=lambda x:x[1]) </code></pre> <p>If you don't care about value (I'd be surprised, but) you can do:</p> <pre><code>key, _ = max(stats.iteritems(), key=lambda x:x[1]) </code></pre> <p>I like the tuple unpacking better than a [0] subscript at the end of the expression. ...
18
2008-11-07T14:41:33Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
280,156
<pre><code>max(stats, key=stats.get) </code></pre>
299
2008-11-11T06:24:30Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
12,343,826
<p>I have tested MANY variants, and this is the fastest way to return the key of dict with the max value:</p> <pre><code>def keywithmaxval(d): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d.values()) k=list(d.keys()) return k[v.index...
104
2012-09-09T23:30:37Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
17,217,820
<pre><code>Counter = 0 for word in stats.keys(): if stats[word]&gt; counter: Counter = stats [word] print Counter </code></pre>
0
2013-06-20T15:32:51Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
23,428,922
<p>Given that more than one entry my have the max value. I would make a list of the keys that have the max value as their value.</p> <pre><code>&gt;&gt;&gt; stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000} &gt;&gt;&gt; [key for key,val in stats.iteritems() if val == max(stats.values())] ['b', 'd'] </code></pre> <p>Th...
10
2014-05-02T13:07:23Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
30,043,094
<p>Per the iterated solutions via comments in the selected answer... </p> <p>In Python 3:</p> <pre><code>max(stats.keys(), key=(lambda k: stats[k])) </code></pre> <p>In Python 2:</p> <pre><code>max(stats.iterkeys(), key=(lambda k: stats[k])) </code></pre>
5
2015-05-05T02:03:11Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
35,256,685
<p>If you need to know only a key with the max value you can do it without <code>iterkeys</code> or <code>iteritems</code> because iteration through a dictionary on Python is just an iteration through a dictionary keys.</p> <pre><code>ddd = {'a': 3, 'b': 1} max_key = max(ddd, key=lambda k: ddd[k]) </code></pre>
11
2016-02-07T17:31:32Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with rever...
302
2008-11-06T10:49:58Z
35,585,900
<p>With <code>collections.Counter</code> you could do</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; stats = {'a':1000, 'b':3000, 'c': 100} &gt;&gt;&gt; stats = collections.Counter(stats) &gt;&gt;&gt; stats.most_common(1) [('b', 3000)] </code></pre> <p>If appropriate, you could simply start with an empty...
4
2016-02-23T18:58:38Z
[ "python", "dictionary", "max" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer...
22
2008-11-06T13:10:54Z
268,660
<p>I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve_forever (from SocketServer.py) method looks like this:</p> <pre><code>def serve_forever(self): """Handle one request at a time until doomsday.""" while 1: self.handle_request() </code></pre> <p>You...
15
2008-11-06T13:21:35Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer...
22
2008-11-06T13:10:54Z
268,686
<p>In my python 2.6 installation, I can call it on the underlying TCPServer - it still there inside your <code>HTTPServer</code>:</p> <pre><code>TCPServer.shutdown &gt;&gt;&gt; import BaseHTTPServer &gt;&gt;&gt; h=BaseHTTPServer.HTTPServer(('',5555), BaseHTTPServer.BaseHTTPRequestHandler) &gt;&gt;&gt; h.shutdown &lt...
15
2008-11-06T13:30:25Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer...
22
2008-11-06T13:10:54Z
4,020,093
<p>I think you can use <code>[serverName].socket.close()</code></p>
8
2010-10-26T01:38:35Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer...
22
2008-11-06T13:10:54Z
19,211,760
<p>Another way to do it, based on <a href="http://docs.python.org/2/library/basehttpserver.html#more-examples">http://docs.python.org/2/library/basehttpserver.html#more-examples</a>, is: instead of serve_forever(), keep serving as long as a condition is met, with the server checking the condition before and after each ...
5
2013-10-06T17:32:17Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer...
22
2008-11-06T13:10:54Z
22,493,362
<p>In python 2.7, calling shutdown() works but only if you are serving via serve_forever, because it uses async select and a polling loop. Running your own loop with handle_request() ironically excludes this functionality because it implies a dumb blocking call.</p> <p>From SocketServer.py's BaseServer:</p> <pre><cod...
7
2014-03-18T23:38:21Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer...
22
2008-11-06T13:10:54Z
35,358,134
<p>I tried all above possible solution and ended up with having a "sometime" issue - somehow it did not really do it - so I ended up making a dirty solution that worked all the time for me:</p> <p>If all above fails, then brute force kill your thread using something like this:</p> <pre><code>import subprocess cmdkill...
0
2016-02-12T08:41:21Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer...
22
2008-11-06T13:10:54Z
35,576,127
<p>The event-loops ends on SIGTERM, <kbd>Ctrl</kbd>+<kbd>C</kbd> or when <code>shutdown()</code> is called.</p> <p><code>server_close()</code> must be called after <code>server_forever()</code> to close the listening socket.</p> <pre class="lang-py prettyprint-override"><code>import http.server class StoppableHTTPSe...
1
2016-02-23T11:18:35Z
[ "python", "http", "basehttpserver" ]
Replacing multiple occurrences in nested arrays
268,891
<p>I've got this python dictionary "mydict", containing arrays, here's what it looks like :</p> <pre><code>mydict = dict( one=['foo', 'bar', 'foobar', 'barfoo', 'example'], two=['bar', 'example', 'foobar'], three=['foo', 'example']) </code></pre> <p>i'd like to replace all the occurrences of "example" b...
3
2008-11-06T14:36:01Z
269,043
<pre><code>for arr in mydict.values(): for i, s in enumerate(arr): if s == 'example': arr[i] = 'someotherword' </code></pre>
2
2008-11-06T15:13:48Z
[ "python", "arrays", "dictionary", "replace" ]
Replacing multiple occurrences in nested arrays
268,891
<p>I've got this python dictionary "mydict", containing arrays, here's what it looks like :</p> <pre><code>mydict = dict( one=['foo', 'bar', 'foobar', 'barfoo', 'example'], two=['bar', 'example', 'foobar'], three=['foo', 'example']) </code></pre> <p>i'd like to replace all the occurrences of "example" b...
3
2008-11-06T14:36:01Z
270,535
<p>If you want to leave the original untouched, and just return a new dictionary with the modifications applied, you can use:</p> <pre><code>replacements = {'example' : 'someotherword'} newdict = dict((k, [replacements.get(x,x) for x in v]) for (k,v) in mydict.iteritems()) </code></pre> <p>This also...
2
2008-11-06T22:15:59Z
[ "python", "arrays", "dictionary", "replace" ]
Replacing multiple occurrences in nested arrays
268,891
<p>I've got this python dictionary "mydict", containing arrays, here's what it looks like :</p> <pre><code>mydict = dict( one=['foo', 'bar', 'foobar', 'barfoo', 'example'], two=['bar', 'example', 'foobar'], three=['foo', 'example']) </code></pre> <p>i'd like to replace all the occurrences of "example" b...
3
2008-11-06T14:36:01Z
271,294
<p>Here's another take:</p> <pre><code>for key, val in mydict.items(): mydict[key] = ["someotherword" if x == "example" else x for x in val] </code></pre> <p>I've found that building lists is <strong>very</strong> fast, but of course profile if performance is important.</p>
1
2008-11-07T05:18:17Z
[ "python", "arrays", "dictionary", "replace" ]
How can you emulate a mailing list in Django?
268,930
<p>I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.</p> <p>The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.</p> <p>Now, we...
3
2008-11-06T14:45:37Z
269,377
<p>Did you take a look at <a href="http://www.greatcircle.com/majordomo/" rel="nofollow">majordomo</a>, or <a href="http://www.gnu.org/software/mailman/index.html" rel="nofollow">mailman</a>?</p>
1
2008-11-06T16:42:00Z
[ "python", "django", "mailing-list" ]
How can you emulate a mailing list in Django?
268,930
<p>I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.</p> <p>The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.</p> <p>Now, we...
3
2008-11-06T14:45:37Z
269,379
<p><a href="http://www.apps.ietf.org/rfc/rfc2919.html" rel="nofollow">RFC 2919</a> has some info and more references on this.</p>
2
2008-11-06T16:42:10Z
[ "python", "django", "mailing-list" ]
How can you emulate a mailing list in Django?
268,930
<p>I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.</p> <p>The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.</p> <p>Now, we...
3
2008-11-06T14:45:37Z
6,985,535
<p>What about <a href="http://labs.freehackers.org/projects/colibri/wiki" rel="nofollow">http://labs.freehackers.org/projects/colibri/wiki</a> It seems to do what you want: a mailing list manager with a django frontend.</p>
3
2011-08-08T16:47:09Z
[ "python", "django", "mailing-list" ]
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwin...
14
2008-11-06T15:18:20Z
269,105
<p>You may be interested in <a href="http://pypi.python.org/pypi/chardet">Universal Encoding Detector</a>.</p>
19
2008-11-06T15:26:25Z
[ "python", "email", "character-encoding", "invalid-characters" ]
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwin...
14
2008-11-06T15:18:20Z
269,276
<p>+1 for the <a href="http://web.archive.org/web/20110709171259/http://chardet.feedparser.org/docs/faq.html">chardet</a> module (suggested by <a href="http://stackoverflow.com/questions/269060/is-there-a-python-library-function-which-attempts-to-guess-the-character-encoding/269105#269105"><code>@insin</code></a>).</p>...
15
2008-11-06T16:13:29Z
[ "python", "email", "character-encoding", "invalid-characters" ]
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwin...
14
2008-11-06T15:18:20Z
271,058
<p>The best way to do this that I've found is to iteratively try decoding a prospective with each of the most common encodings inside of a try except block.</p>
1
2008-11-07T02:31:26Z
[ "python", "email", "character-encoding", "invalid-characters" ]
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwin...
14
2008-11-06T15:18:20Z
273,631
<p>As far as I can tell, the standard library doesn't have a function, though it's not too difficult to write one as suggested above. I think the real thing I was looking for was a way to decode a string and guarantee that it wouldn't throw an exception. The errors parameter to string.decode does that.</p> <pre><cod...
9
2008-11-07T21:03:20Z
[ "python", "email", "character-encoding", "invalid-characters" ]
What mime-type should I return for a python string
269,292
<p>I have a web API that returns python dictionaries or lists as a response that I eval() in python scripts that use the API, for completness I wanted to set a proper content-type but not sure what would be best to use "text/x-python" or maybe "application/python", or something else? </p> <p>[edit] I'm also outputting...
3
2008-11-06T16:19:58Z
269,364
<p>I doubt there's an established MIME type. Have you considered using JSON instead, it is almost the same as a Python dict, and has a better established culture of tools and techniques.</p>
8
2008-11-06T16:38:35Z
[ "python", "http", "mime-types" ]
What mime-type should I return for a python string
269,292
<p>I have a web API that returns python dictionaries or lists as a response that I eval() in python scripts that use the API, for completness I wanted to set a proper content-type but not sure what would be best to use "text/x-python" or maybe "application/python", or something else? </p> <p>[edit] I'm also outputting...
3
2008-11-06T16:19:58Z
271,988
<p>The authoritative registry is <a href="http://www.iana.org/assignments/media-types/" rel="nofollow">at IANA</a> and, no, there is no standard subtype for Python. So, do not use type like "application/python" but you may use private subtypes such as "text/x-python" (the one I find in the mime-support package on my De...
3
2008-11-07T12:59:35Z
[ "python", "http", "mime-types" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0...
8
2008-11-06T18:06:13Z
270,449
<p>you can always run LOCK TABLE tablename from another session (mysql CLI for instance). That might do the trick.</p> <p>It will remain locked until you release it or disconnect the session.</p>
1
2008-11-06T21:51:06Z
[ "python", "mysql", "database", "deadlock" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0...
8
2008-11-06T18:06:13Z
270,492
<p>I'm not familar with Python, so excuse my incorrect language If I'm saying this wrong... but open two sessions (in separate windows, or from separate Python processes - from separate boxes would work ... ) Then ... </p> <p>. In Session A:</p> <pre><code> Begin Transaction Insert TableA() Values()... </c...
1
2008-11-06T22:01:53Z
[ "python", "mysql", "database", "deadlock" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0...
8
2008-11-06T18:06:13Z
271,789
<p>You want something along the following lines.</p> <p><strong>parent.py</strong></p> <pre><code>import subprocess c1= subprocess.Popen( ["python", "child.py", "1"], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) c2= subprocess.Popen( ["python", "child.py", "2"], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) out1...
1
2008-11-07T11:12:14Z
[ "python", "mysql", "database", "deadlock" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0...
8
2008-11-06T18:06:13Z
1,468,676
<p>Not sure if either above is correct. Check out this:</p> <p><a href="http://www.xaprb.com/blog/2006/08/08/how-to-deliberately-cause-a-deadlock-in-mysql/" rel="nofollow">http://www.xaprb.com/blog/2006/08/08/how-to-deliberately-cause-a-deadlock-in-mysql/</a></p>
1
2009-09-23T21:42:49Z
[ "python", "mysql", "database", "deadlock" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0...
8
2008-11-06T18:06:13Z
8,100,573
<p>Here's some pseudocode for how i do it in PHP:</p> <p>Script 1:</p> <pre><code>START TRANSACTION; INSERT INTO table &lt;anything you want&gt;; SLEEP(5); UPDATE table SET field = 'foo'; COMMIT; </code></pre> <p>Script 2:</p> <pre><code>START TRANSACTION; UPDATE table SET field = 'foo'; SLEEP(5); INSERT INTO table...
1
2011-11-11T22:09:50Z
[ "python", "mysql", "database", "deadlock" ]
Using Python to authenticate against raw username, hash, salt in DB created by ASP.NET roles/membership
269,713
<p>We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash.</p> <p>These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user n...
6
2008-11-06T18:14:45Z
269,888
<p>Two thoughts as to what could be going wrong.</p> <p>First the code from the reflection has three paths:</p> <ul> <li>If passwordFormat is 0 it returns the password as is.</li> <li>If passwordFormat is 1 it creates the hash as your python code does.</li> <li>If passwordFormat is anything other than 0 or 1 it calls...
0
2008-11-06T19:06:58Z
[ "asp.net", "python", "hash", "passwords" ]
Using Python to authenticate against raw username, hash, salt in DB created by ASP.NET roles/membership
269,713
<p>We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash.</p> <p>These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user n...
6
2008-11-06T18:14:45Z
270,670
<p>It appears python is inserting a byte order marker when you convert a UTF16 string to binary. The .NET byte array contains no BOM, so I did some ghetto python that turns the UTF16 into hex, removes the first 4 characters, then decodes it to binary.</p> <p>There may be a better way to rip out the BOM, but this work...
8
2008-11-06T22:57:12Z
[ "asp.net", "python", "hash", "passwords" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,803
<p>The <code>sys.path</code> list contains the list of directories which will be searched for modules at runtime:</p> <pre><code>python -v &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ] </code></pre>
25
2008-11-06T18:39:52Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,806
<p>Running <code>python -v</code> from the command line should tell you what is being imported and from where. This works for me on Windows and Mac OS X.</p> <pre><code>C:\&gt;python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # C:\Python24\lib\site.pyc has bad mtime import si...
136
2008-11-06T18:40:27Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,810
<p><code>datetime</code> is a builtin module, so there is no (Python) source file.</p> <p>For modules coming from <code>.py</code> (or <code>.pyc</code>) files, you can use <code>mymodule.__file__</code>, e.g.</p> <pre><code>&gt; import random &gt; random.__file__ 'C:\\Python25\\lib\\random.pyc' </code></pre>
25
2008-11-06T18:41:56Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,814
<p>Not all python modules are written in python. Datetime happens to be one of them that is not, and (on linux) is datetime.so.</p> <p>You would have to download the source code to the python standard library to get at it.</p>
0
2008-11-06T18:43:03Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,825
<p>For a pure python module you can find the source by looking at <code>themodule.__file__</code>. The datetime module, however, is written in C, and therefore <code>datetime.__file__</code> points to a .so file (there is no <code>datetime.__file__</code> on Windows), and therefore, you can't see the source.</p> <p>If...
211
2008-11-06T18:45:33Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
2,723,437
<p>Check out this <a href="http://chris-lamb.co.uk/2010/04/22/locating-source-any-python-module/" rel="nofollow">nifty "cdp" command</a> to cd to the directory containing the source for the indicated Python module:</p> <pre><code>cdp () { cd "$(python -c "import os.path as _, ${1}; \ print _.dirname(_.realpath($...
7
2010-04-27T17:22:07Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
5,089,930
<p>New in Python 3.2, you can now use e.g. <code>code_info()</code> from the dis module: <a href="http://docs.python.org/dev/whatsnew/3.2.html#dis">http://docs.python.org/dev/whatsnew/3.2.html#dis</a></p>
10
2011-02-23T10:56:12Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
5,740,458
<p>In the python interpreter you could import the particular module and then type help(module). This gives details such as Name, File, Module Docs, Description et al.</p> <p>Ex:</p> <pre><code>import os help(os) Help on module os: NAME os - OS routines for Mac, NT, or Posix depending on what system we're on. FI...
8
2011-04-21T06:39:13Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
13,888,157
<p>I realize this answer is 4 years late, but the existing answers are misleading people.</p> <p>The right way to do this is never <code>__file__</code>, or trying to walk through <code>sys.path</code> and search for yourself, etc. (unless you need to be backward compatible beyond 2.1).</p> <p>It's the <a href="http:...
77
2012-12-15T00:31:15Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
15,211,581
<p>Here's a one-liner to get the filename for a module, suitable for shell aliasing:</p> <pre><code>echo 'import sys; t=__import__(sys.argv[1],fromlist=[\".\"]); print(t.__file__)' | python - </code></pre> <p>Set up as an alias:</p> <pre><code>alias getpmpath="echo 'import sys; t=__import__(sys.argv[1],fromlist=[\...
4
2013-03-04T21:35:24Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
16,370,057
<p>from the standard library try <a href="http://docs.python.org/2/library/imp.html#imp.find_module">imp.find_module</a></p> <pre><code>&gt;&gt;&gt; import imp &gt;&gt;&gt; imp.find_module('fontTools') (None, 'C:\\Python27\\lib\\site-packages\\FontTools\\fontTools', ('', '', 5)) &gt;&gt;&gt; imp.find_module('datetime'...
17
2013-05-04T02:40:30Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
24,117,914
<p>On windows you can find the location of the python module as shown below:i.e find rest_framework module <img src="http://i.stack.imgur.com/TsWpv.png" alt="enter image description here"></p>
2
2014-06-09T10:04:36Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
27,230,006
<p>For those who prefer a GUI solution: if you're using a gui such as Spyder (part of the Anaconda installation) you can just right-click the module name (such as "csv" in "import csv") and select "go to definition" - this will open the file, but also on the top you can see the exact file location ("C:....csv.py") </p>...
0
2014-12-01T14:00:13Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
32,784,452
<p>If you're using pip to install your modules, just <code>pip show $module</code> the location is returned.</p>
9
2015-09-25T14:27:58Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
37,970,790
<p>On Ubuntu 12.04, for example numpy package for python2, can be found at:</p> <pre><code>/usr/lib/python2.7/dist-packages/numpy </code></pre> <p>Of course, this is not generic answer</p>
0
2016-06-22T14:18:30Z
[ "python", "module" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </cod...
3
2008-11-06T19:16:12Z
270,006
<p>It's probably a bit of overkill, but you could use boost to interface to python. At the worst, difflib is implemented in pure python, and it's not too long. It should be possible to port from python to C...</p>
1
2008-11-06T19:46:23Z
[ "c++", "python", "algorithm", "diff" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </cod...
3
2008-11-06T19:16:12Z
270,143
<p>This might work, it at least passes your demonstration test: EDIT: I've made some modifications to deal with some string indexing issues. I believe it should be good now.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;cctype&gt; bool...
2
2008-11-06T20:33:58Z
[ "c++", "python", "algorithm", "diff" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </cod...
3
2008-11-06T19:16:12Z
270,155
<p>You could do an ad hoc approach: You're looking to match strings s and s', where s=abc and s'=ab'c, and the b and b' should be two distinct numbers (possible empty). So:</p> <ol> <li>Compare the strings from the left, char by char, until you hit different characters, and then stop. You </li> <li>Similarly, compare ...
1
2008-11-06T20:36:24Z
[ "c++", "python", "algorithm", "diff" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </cod...
3
2008-11-06T19:16:12Z
270,241
<p>@Evan Teran: looks like we did this in parallel -- I have a markedly less readable O(n) implementation:</p> <pre><code>#include &lt;cassert&gt; #include &lt;cctype&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; using namespace std; ostringstream debug; const bool DEBUG = true; boo...
0
2008-11-06T20:56:26Z
[ "c++", "python", "algorithm", "diff" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </cod...
3
2008-11-06T19:16:12Z
270,251
<p>How about using something like boost::regex?</p> <pre> // pseudo code, may or may not compile bool match_except_numbers(const std::string& s1, const std::string& s2) { static const boost::regex fooNumberBar("foo\\d+bar"); return boost::match(s1, fooNumberBar) && boost::match(s2, fooNumberBar); } </pre>
0
2008-11-06T20:58:45Z
[ "c++", "python", "algorithm", "diff" ]
Tkinter: invoke event in main loop
270,648
<p>How do you invoke a tkinter <code>event</code> from a separate object? </p> <p>I'm looking for something like wxWidgets <code>wx.CallAfter</code>. For example, If I create an object, and pass to it my <code>Tk</code> root instance, and then try to call a method of that root window from my object, my app locks up....
14
2008-11-06T22:49:44Z
276,069
<p>To answer your specific question of "How do you invoke a TkInter event from a separate object", use the <code>event_generate</code> command. It allows you to inject events into the event queue of the root window. Combined with Tk's powerful virtual event mechanism it becomes a handy message passing mechanism. </p> ...
21
2008-11-09T16:26:28Z
[ "python", "user-interface", "communication", "tkinter" ]
Tkinter: invoke event in main loop
270,648
<p>How do you invoke a tkinter <code>event</code> from a separate object? </p> <p>I'm looking for something like wxWidgets <code>wx.CallAfter</code>. For example, If I create an object, and pass to it my <code>Tk</code> root instance, and then try to call a method of that root window from my object, my app locks up....
14
2008-11-06T22:49:44Z
36,778,730
<p>Here below just some doc and link to better understand Bryan's answer above. </p> <p>function description from <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html" rel="nofollow">New Mexico Tech</a> :</p> <p><code>w.event_generate(sequence, **kw)</code></p> <blockquote> <p>This method caus...
3
2016-04-21T19:25:28Z
[ "python", "user-interface", "communication", "tkinter" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
270,777
<p>You should directly obtain all IP configured IP addresses, e.g. by running ifconfig and parsing its output (it's also possible to do what <a href="http://pypi.python.org/pypi/netifaces/0.3" rel="nofollow">ifconfig does directly in Python</a>, <a href="http://stackoverflow.com/questions/259389/finding-an-ip-from-an-i...
0
2008-11-06T23:32:44Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
273,112
<p>It's linux only, but there's a very simple recipe here <a href="http://code.activestate.com/recipes/439094/" rel="nofollow">http://code.activestate.com/recipes/439094/</a> </p> <p>It probably uses similar code to the <a href="http://pypi.python.org/pypi/netifaces/" rel="nofollow">netifaces package</a> mentioned in ...
1
2008-11-07T18:36:31Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
274,644
<p>Use the <a href="http://alastairs-place.net/netifaces/"><code>netifaces</code></a> module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want:</p> <pre><code>&gt;&gt;&gt; import netifaces &gt;&gt;&gt; netifaces.interfaces() ['lo', 'eth0'] &gt;&gt;&gt; netiface...
30
2008-11-08T11:43:25Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
1,491,617
<p>Here is a routine for finding all IPv4 and IPv6 interfaces. As a previous poster pointed out, socket.gethostbyname_ex() does not work for IPv6, and the Python documentation recommends one use <a href="http://docs.python.org/library/socket.html#socket.getaddrinfo" rel="nofollow">socket.getaddressinfo()</a> instead.</...
1
2009-09-29T09:59:20Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
16,412,986
<pre><code>import socket [i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)] </code></pre>
3
2013-05-07T06:56:09Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
27,494,105
<p><a href="https://docs.python.org/3.4/library/socket.html#socket.if_nameindex" rel="nofollow">https://docs.python.org/3.4/library/socket.html#socket.if_nameindex</a></p> <p>socket.if_nameindex()</p> <p>Return a list of network interface information (index int, name string) tuples. OSError if the system call fails.<...
1
2014-12-15T22:11:42Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
33,946,251
<p>All addresses in one line with the help of the <code>netifaces</code> module:</p> <pre><code>[netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifaces.ifaddresses(iface)] </code></pre>
4
2015-11-26T20:05:35Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
35,776,008
<p>You can do it fairly easily like this:</p> <pre><code>import netifaces for interface in netifaces.interfaces(): print netifaces.ifaddresses(interface) </code></pre> <p>For more information you can look up the <a href="https://pypi.python.org/pypi/netifaces" rel="nofollow">netifaces documentation</a>.</p>
0
2016-03-03T15:17:34Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
39,951,087
<p>This snippet will give a list of all available IPV4 addresses in the system.</p> <pre><code>import itertools from netifaces import interfaces, ifaddresses, AF_INET links = filter(None, (ifaddresses(x).get(AF_INET) for x in interfaces())) links = itertools.chain(*links) ip_addresses = [x['addr'] for x in links] </c...
0
2016-10-10T03:53:27Z
[ "python", "sockets", "ip-address" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo ...
62
2008-11-07T00:24:04Z
270,891
<p>Withough testing, I'd try:</p> <pre><code>for c in session.query(Stuff).all(): c.foo = c.foo+1 session.commit() </code></pre> <p>(IIRC, commit() works without flush()).</p> <p>I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of quer...
0
2008-11-07T00:35:19Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo ...
62
2008-11-07T00:24:04Z
270,942
<p>If it is because of the overhead in terms of creating objects, then it probably can't be sped up at all with SA.</p> <p>If it is because it is loading up related objects, then you might be able to do something with lazy loading. Are there lots of objects being created due to references? (IE, getting a Company obj...
0
2008-11-07T01:08:04Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo ...
62
2008-11-07T00:24:04Z
278,606
<p>SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the...
99
2008-11-10T17:40:42Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo ...
62
2008-11-07T00:24:04Z
4,540,110
<pre><code>session.query(Clients).filter(Clients.id == client_id_list).update({'status': status}) session.commit() </code></pre> <p>Try this =)</p>
45
2010-12-27T16:28:03Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo ...
62
2008-11-07T00:24:04Z
32,447,458
<p>Here's an example of how to solve the same problem without having to map the fields manually:</p> <pre><code>from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime, text, create_engine from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.declarative import declarative_base from sqlalche...
0
2015-09-08T00:10:34Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo ...
62
2008-11-07T00:24:04Z
33,638,391
<p>There are several ways to UPDATE using sqlalchemy</p> <pre><code>1) for c in session.query(Stuff).all(): c.foo += 1 session.commit() 2) session.query().\ update({"foo": (Stuff.foo + 1)}) session.commit() 3) conn = engine.connect() stmt = Stuff.update().\ values(Stuff.foo = (Stuff.foo...
3
2015-11-10T19:53:27Z
[ "python", "orm", "sqlalchemy" ]
How can I apply authenticated proxy exceptions to an opener using urllib2?
270,983
<p>When using urllib2 (and maybe urllib) on windows python seems to magically pick up the authenticated proxy setting applied to InternetExplorer. However, it doesn't seem to check and process the Advance setting "Exceptions" list.</p> <p>Is there a way I can get it to process the exceptions list? Or, ignore the IE ...
4
2008-11-07T01:29:14Z
271,023
<p>By default <code>urllib2</code> gets the proxy settings from the environment variable, which is why it is using the IE settings. This is very handy, because you don't need to setup authentication yourself.</p> <p>You can't apply exceptions like you want to, the easiest way to do this would be to have two <code>ope...
2
2008-11-07T01:58:09Z
[ "python", "windows", "proxy" ]