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
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For e...
23
2009-08-24T13:21:37Z
18,252,518
<p>A 0-d array of None looks like None but it is not the same:</p> <pre><code>In [1]: print None None In [2]: import numpy In [3]: print numpy.array(None) None In [4]: numpy.array(None) is None Out[4]: False In [5]: numpy.array(None) == None Out[5]: False In [6]: print repr(numpy.array(None)) array(None, dtype=ob...
1
2013-08-15T12:21:21Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For e...
23
2009-08-24T13:21:37Z
28,183,264
<p>A surprise with the <code>*=</code> assignment in combination with <code>numpy.array</code>:</p> <pre><code>&gt;&gt;&gt; from numpy import array &gt;&gt;&gt; a = array([1, 2, 3]) &gt;&gt;&gt; a *= 1.1 &gt;&gt;&gt; print(a) [1 2 3] # not quite what we expect or would like to see &gt;&gt;&gt; print(a.dtype) int...
2
2015-01-28T01:43:25Z
[ "python", "numpy" ]
Django Admin - Bulk editing data?
1,322,425
<p>Are there any admin extensions to let bulk editing data in Django Admin? (ie. Changing the <em>picture</em> fields of all <em>product</em> models at once. Note that this is needed for a users POV so scripting doesn't count.) Any thoughts on subject welcome.</p>
3
2009-08-24T13:30:04Z
1,322,450
<p>You have SQL. You can write SQL UPDATE statements.</p> <p>You have Python for writing batch scripts that interact with the Django ORM. This works really, really well for bulk changes.</p>
-1
2009-08-24T13:33:31Z
[ "python", "django", "django-models", "django-admin" ]
Django Admin - Bulk editing data?
1,322,425
<p>Are there any admin extensions to let bulk editing data in Django Admin? (ie. Changing the <em>picture</em> fields of all <em>product</em> models at once. Note that this is needed for a users POV so scripting doesn't count.) Any thoughts on subject welcome.</p>
3
2009-08-24T13:30:04Z
1,322,459
<p>With Django 1.1, you can create admin actions which can be applied to multiple entries at once. See <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#ref-contrib-admin-actions">the documentation</a> on this subject.</p>
8
2009-08-24T13:34:59Z
[ "python", "django", "django-models", "django-admin" ]
Django Admin - Bulk editing data?
1,322,425
<p>Are there any admin extensions to let bulk editing data in Django Admin? (ie. Changing the <em>picture</em> fields of all <em>product</em> models at once. Note that this is needed for a users POV so scripting doesn't count.) Any thoughts on subject welcome.</p>
3
2009-08-24T13:30:04Z
6,698,899
<p><a href="http://algoholic.eu/django-mass-change-admin-site-extension/" rel="nofollow">Django "Mass Change" Admin Site Extension</a>.</p>
4
2011-07-14T19:32:00Z
[ "python", "django", "django-models", "django-admin" ]
python time format check
1,322,464
<p>I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result.</p> <p>How can I achieve this by using regular expression ?</p>
5
2009-08-24T13:36:10Z
1,322,524
<p>You can achieve this without regular expressions:</p> <pre><code>import time def isTimeFormat(input): try: time.strptime(input, '%H:%M') return True except ValueError: return False &gt;&gt;&gt;isTimeFormat('12:12') True &gt;&gt;&gt;isTimeFormat('012:12') False </code></pre>
14
2009-08-24T13:45:51Z
[ "python", "regex" ]
python time format check
1,322,464
<p>I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result.</p> <p>How can I achieve this by using regular expression ?</p>
5
2009-08-24T13:36:10Z
1,322,529
<p>This will give you the regexp object which will check it. However, depending on who you ask 24:00 might not be a valid time (it's 00:00). But I guess this is easy to modify to suit your needs.</p> <pre><code>import re regexp = re.compile("(24:00|2[0-3]:[0-5][0-9]|[0-1][0-9]:[0-5][0-9])") </code></pre>
1
2009-08-24T13:46:20Z
[ "python", "regex" ]
python time format check
1,322,464
<p>I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result.</p> <p>How can I achieve this by using regular expression ?</p>
5
2009-08-24T13:36:10Z
1,322,532
<pre><code>import re time_re = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$') def is_time_format(s): return bool(time_re.match(s)) </code></pre> <p>Matches everything from 00:00 to 24:00.</p>
2
2009-08-24T13:46:31Z
[ "python", "regex" ]
python time format check
1,322,464
<p>I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result.</p> <p>How can I achieve this by using regular expression ?</p>
5
2009-08-24T13:36:10Z
1,322,533
<p>This patters will help you: <a href="http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&amp;categoryId=5" rel="nofollow">http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&amp;categoryId=5</a></p> <p>BTW, you should use google before asking this kind of questions...</p>
3
2009-08-24T13:46:40Z
[ "python", "regex" ]
Python - How to edit hexadecimal file byte by byte
1,322,508
<p>I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tuto...
5
2009-08-24T13:42:53Z
1,322,542
<p>The Hachoir framework is a set of Python library and tools to parse and edit binary files:</p> <p><a href="http://pypi.python.org/pypi/hachoir-core" rel="nofollow">http://pypi.python.org/pypi/hachoir-core</a></p> <p>It has knowledge of common file types, so this could just be what you need.</p>
4
2009-08-24T13:47:51Z
[ "python", "byte", "hex", "filereader" ]
Python - How to edit hexadecimal file byte by byte
1,322,508
<p>I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tuto...
5
2009-08-24T13:42:53Z
1,322,570
<p>Python standard library has mmap module, which can be used to do exactly this. Take a look on <a href="http://docs.python.org/library/mmap.html">the documentation</a> for further information.</p>
7
2009-08-24T13:50:13Z
[ "python", "byte", "hex", "filereader" ]
Python - How to edit hexadecimal file byte by byte
1,322,508
<p>I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tuto...
5
2009-08-24T13:42:53Z
1,322,579
<p>Depending on what you want to do it might be enough to <a href="http://docs.python.org/library/functions.html#open" rel="nofollow">open the file in binary mode</a> and read the data with the normal <a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects" rel="nofollow">file</a> functions:</p> <pre>...
9
2009-08-24T13:51:39Z
[ "python", "byte", "hex", "filereader" ]
Python - How to edit hexadecimal file byte by byte
1,322,508
<p>I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tuto...
5
2009-08-24T13:42:53Z
1,323,602
<p>Check out the <a href="http://docs.python.org/library/struct.html" rel="nofollow">stuct</a> module.</p> <blockquote> <p>This module performs conversions between Python values and C structs represented as Python strings. It uses format strings (explained below) as compact descriptions of the lay-out of the C struc...
1
2009-08-24T17:09:37Z
[ "python", "byte", "hex", "filereader" ]
Ipython common problems
1,322,569
<p>I love iPython's so many features, magic functions.</p> <p>I recently upgraded to the latest 0.10 version. But I face following common problems:</p> <ul> <li><code>%hist</code> one of the most frequently used magic functions, doesn't exist.</li> <li><code>dreload</code> doesn't seems to work (works only for module...
2
2009-08-24T13:50:06Z
1,322,837
<p>sounds like an issue with your particular setup. ? and ?? have always worked on my machine, hist is still a magic function, and dreload has always only worked for modules--what else would it do?</p> <p>as for the debug thing, it's a known issue with python 2.6: <a href="https://bugs.launchpad.net/ipython/+bug/3810...
1
2009-08-24T14:46:39Z
[ "python", "django", "command-line", "ipython" ]
What numbers can you pass as verbosity in running Python Unit Test Suites?
1,322,575
<p>The Python unittest framework has a concept of verbosity that I can't seem to find defined anywhere. For instance, I'm running test cases like this (<a href="http://docs.python.org/library/unittest.html#basic-example">like in the documentation</a>):</p> <pre><code>suite = unittest.TestLoader().loadTestsFromTestCase...
26
2009-08-24T13:51:20Z
1,322,648
<p>You only have 3 different levels:</p> <ul> <li>0 <strong><em>(quiet)</em></strong>: you just get the total numbers of tests executed and the global result</li> <li>1 <strong><em>(default)</em></strong>: you get the same plus a dot for every successful test or a F for every failure</li> <li>2 <strong><em>(verbose)</...
43
2009-08-24T14:08:36Z
[ "python", "unit-testing", "verbosity" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So...
3
2009-08-24T14:37:40Z
1,322,962
<p>One way is to write a COM server in Python, and call that from Excel. There are tutorials describing <a href="http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartServerCom.html">Win32 COM servers</a>, and <a href="http://showmedo.com/videotutorials/video?name=2190050&amp;fromSeriesI...
6
2009-08-24T15:08:42Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So...
3
2009-08-24T14:37:40Z
1,322,983
<p>I don't know any py2dll similar to py2exe.</p> <p>However, you could create a dll in C and use the <a href="http://docs.python.org/c-api/veryhigh.html" rel="nofollow">Very High Level Layer</a> to call your script. I don't know it is an acceptable solution for you. Just an idea. </p>
0
2009-08-24T15:12:57Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So...
3
2009-08-24T14:37:40Z
1,323,280
<p>This is probably not a possible solution for you, but there is the <a href="http://www.resolversystems.com/products/resolver-one/" rel="nofollow">Resolver One</a> spreadsheet application (which is like Excel combined with Python). It is not connected with Excel in any way, but claims to be compatible to some extent....
4
2009-08-24T16:07:51Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So...
3
2009-08-24T14:37:40Z
2,066,291
<p>I had to do this some years back. My solution was to run small Python server that exported the functions using SOAP, then call the functions using Visual Basic's SOAP library. The advantage is that you don't have to ship a Python environment with your spreadsheets. The disadvantage is that the clients will need a ne...
0
2010-01-14T17:56:03Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So...
3
2009-08-24T14:37:40Z
2,066,349
<p>There is an Excel Addin that allows you to do this called <a href="http://www.xefion.com/getting_started_diss.html" rel="nofollow">Discovery Script</a> at xefion.com.</p> <p>It's free but not open source. It's also based on the IronPython implementation.</p>
0
2010-01-14T18:06:26Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So...
3
2009-08-24T14:37:40Z
7,824,872
<p>Im surprised nobody mentioned <a href="http://www.pyxll.com/" rel="nofollow">pyxll</a>. From the website:</p> <blockquote> <p>PyXLL is an Excel addin that enables functions written in Python to be called in Excel. Python functions can either be exposed as Excel user defined functions that can be called from ...
4
2011-10-19T16:42:51Z
[ "python", "excel" ]
Finding "closest" strings in a Python list (alphabetically)
1,322,934
<p>I have a Python list of strings, e.g. initialized as follows:</p> <pre><code>l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] </code></pre> <p>I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitiv...
2
2009-08-24T15:04:06Z
1,323,000
<p>You can rephrase the problem to this:</p> <p>Given a sorted list of strings <code>l</code> and an input string <code>s</code>, find the index in <code>l</code> where <code>s</code> should be inserted so that <code>l</code> remains sorted after insertion.</p> <p>The elements of <code>l</code> at <code>index-1</code...
2
2009-08-24T15:15:49Z
[ "python", "string" ]
Finding "closest" strings in a Python list (alphabetically)
1,322,934
<p>I have a Python list of strings, e.g. initialized as follows:</p> <pre><code>l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] </code></pre> <p>I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitiv...
2
2009-08-24T15:04:06Z
1,323,010
<p>A very naive implementation, good only for short lists: you can pretty easily iterate through the list and compare your choice against each one, then break the first time your choice is 'greater' than the item being compared.</p> <pre><code>for i, item in enumerate(l): if lower(item) &gt; lower(input): ...
1
2009-08-24T15:17:18Z
[ "python", "string" ]
Finding "closest" strings in a Python list (alphabetically)
1,322,934
<p>I have a Python list of strings, e.g. initialized as follows:</p> <pre><code>l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] </code></pre> <p>I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitiv...
2
2009-08-24T15:04:06Z
1,323,025
<p>This is exactly what the bisect module is for. It will be much faster than just iterating through large lists. </p> <pre><code>import bisect def closest(haystack, needle): if len(haystack) == 0: return None, None index = bisect.bisect_left(haystack, needle) if index == 0: return None, haystac...
15
2009-08-24T15:21:21Z
[ "python", "string" ]
Finding "closest" strings in a Python list (alphabetically)
1,322,934
<p>I have a Python list of strings, e.g. initialized as follows:</p> <pre><code>l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] </code></pre> <p>I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitiv...
2
2009-08-24T15:04:06Z
1,323,368
<p>Are these relatively short lists, and do the contents change or are they fairly static? </p> <p>If you've got a large number of strings, and they're relatively fixed, you might want to look into storing your data in a Trie structure. Once you build it, then it's quick &amp; easy to search through and find your ne...
0
2009-08-24T16:23:07Z
[ "python", "string" ]
Multiprocessing with renewable queue
1,323,086
<p>I'm trying to figure out how to write a program in python that uses the multiprocessing queue.</p> <p>I have multiple servers and one of them will provide the queue remotely with this:</p> <pre><code>from multiprocessing.managers import BaseManager import Queue import daemonme queue = Queue.Queue() class QueueMa...
2
2009-08-24T15:34:12Z
1,323,195
<p>You should use the master-slave (aka. farmer-worker) pattern. The initial process would be the master and creates the jobs. It </p> <ol> <li>creates a Queue</li> <li>creates 7 slave processes, passing the queue as a parameter</li> <li>starts writing jobs into the queue</li> </ol> <p>The slave processes continuousl...
0
2009-08-24T15:53:11Z
[ "python", "queue", "multiprocessing" ]
Multiprocessing with renewable queue
1,323,086
<p>I'm trying to figure out how to write a program in python that uses the multiprocessing queue.</p> <p>I have multiple servers and one of them will provide the queue remotely with this:</p> <pre><code>from multiprocessing.managers import BaseManager import Queue import daemonme queue = Queue.Queue() class QueueMa...
2
2009-08-24T15:34:12Z
1,323,211
<p>Look to the doc how to retreive a queue from the <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing.managers" rel="nofollow">manager</a> (paragraph 17.6.2.7) than with a <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing.managers" rel="nofollow">pool<...
2
2009-08-24T15:55:54Z
[ "python", "queue", "multiprocessing" ]
How to extend and modify PyUnit
1,323,188
<p>I'm about to embark upon extending and modifying PyUnit. For instance, I will add warnings to it, in addition to failures.</p> <p>I'm interested in hearing words of advice on how to start, for instance, subclass every PyUnit class? What to avoid and misc caveats.</p> <p>Looking for input from those that have exte...
1
2009-08-24T15:50:14Z
1,323,966
<p>I recommend studying the <a href="http://code.google.com/p/python-nose/" rel="nofollow">nose</a> project, a popular and well designed extension of PyUnit. You can browse its sources online <a href="http://code.google.com/p/python-nose/source/browse/" rel="nofollow">here</a> or get a copy on your machine via <a href=...
3
2009-08-24T18:28:47Z
[ "python", "pyunit" ]
Getting Wing IDE to stop catching the exceptions that wxPython catches
1,323,361
<p>I started using Wing IDE and it's great. I'm building a wxPython app, and I noticed that Wing IDE catches exceptions that are usually caught by wxPython and not really raised. This is usually useful, but I would like to disable this behavior occasionally. How do I do that?</p>
0
2009-08-24T16:21:53Z
1,323,458
<p>There is a <code>Ignore this exception location</code> check box in the window where the exception is reported in wing, or you could explicitly silence that specific exception in you code with a <code>try except</code> block.</p>
0
2009-08-24T16:40:33Z
[ "python", "wxpython", "wing-ide" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to...
26
2009-08-24T16:22:05Z
1,323,374
<p>Here's a simple, pure-Python implementation. It should be used when performance is not critical (included for future Googlers).</p> <pre><code>import string allowed = set(string.ascii_lowercase + string.digits + '.') def check(test_str): set(test_str) &lt;= allowed </code></pre> <p><hr /></p> <p>Regarding pe...
37
2009-08-24T16:24:38Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to...
26
2009-08-24T16:22:05Z
1,323,385
<p>Simpler approach? A little more Pythonic?</p> <pre><code>&gt;&gt;&gt; ok = "0123456789abcdef" &gt;&gt;&gt; all(c in ok for c in "123456abc") True &gt;&gt;&gt; all(c in ok for c in "hello world") False </code></pre> <p>It certainly isn't the most efficient, but it's sure readable.</p>
14
2009-08-24T16:26:21Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to...
26
2009-08-24T16:22:05Z
1,323,402
<p><strong>EDIT: Changed the regular expression to exclude A-Z</strong></p> <p>Regular expression solution is the fastest pure python solution so far</p> <pre><code>reg=re.compile('^[a-z0-9\.]+$') &gt;&gt;&gt;reg.match('jsdlfjdsf12324..3432jsdflsdf') True &gt;&gt;&gt; timeit.Timer("reg.match('jsdlfjdsf12324..3432jsdf...
11
2009-08-24T16:28:56Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to...
26
2009-08-24T16:22:05Z
1,325,265
<p><strong>Final(?) edit</strong></p> <p>Answer, wrapped up in a function, with annotated interactive session:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; def special_match(strg, search=re.compile(r'[^a-z0-9.]').search): ... return not bool(search(strg)) ... &gt;&gt;&gt; special_match("") True &gt;&gt;&gt;...
17
2009-08-24T23:12:00Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to...
26
2009-08-24T16:22:05Z
24,769,085
<p>This has already been answered satisfactorily, but for people coming across this after the fact, I have done some profiling of several different methods of accomplishing this. In my case I wanted uppercase hex digits, so modify as necessary to suit your needs.</p> <p>Here are my test implementations:</p> <pre><cod...
0
2014-07-15T22:15:35Z
[ "python", "regex", "search", "character" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,323,426
<p><code>in</code> is definitely more pythonic.</p> <p>In fact <a href="http://docs.python.org/3.1/whatsnew/3.0.html#builtins"><code>has_key()</code> was removed in Python 3.x</a>.</p>
651
2009-08-24T16:33:18Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,323,429
<p>According to python <a href="http://docs.python.org/library/stdtypes.html#dict.has_key">docs</a>:</p> <blockquote> <p><code>has_key()</code> is deprecated in favor of <code>key in d</code>.</p> </blockquote>
48
2009-08-24T16:33:51Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,323,880
<p><code>in</code> wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:</p> <pre><code>$ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d' 10000000 loops, best of 3: 0.0983 usec per loop $ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)' 1000000 loops, ...
189
2009-08-24T18:12:28Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,323,998
<p><code>has_key</code> is a dictionary method, but <code>in</code> will work on any collection, and even when <code>__contains__</code> is missing, <code>in</code> will use any other method to iterate the collection to find out.</p>
11
2009-08-24T18:35:22Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,325,066
<p>Use <code>dict.has_key()</code> if (and only if) your code is required to be runnable by Python versions earlier than 2.3 (when <code>key in dict</code> was introduced). </p>
30
2009-08-24T22:11:34Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
8,913,940
<p>There is one example where <code>in</code> actually kills your performance.</p> <p>If you use <code>in</code> on a O(1) container that only implements <code>__getitem__</code> and <code>has_key()</code> but not <code>__contains__</code> you will turn an O(1) search into an O(N) search (as <code>in</code> falls back...
16
2012-01-18T16:45:39Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
10,512,159
<p>Python 2.x supports <code>has_key()</code>.</p> <p>Python 2.3+ and Python 3.x support <code>in</code>.</p>
9
2012-05-09T08:06:54Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
31,766,439
<p>If your intention is to use a default value in case a key is not in the dictionary then</p> <pre><code>my_dict.get('key') or default_value </code></pre> <p>is a way of skipping the <code>in</code> check. <code>get</code> returns <code>None</code> if the key is not in the dictionary. The speed is also O(1) as with ...
3
2015-08-01T21:32:13Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
33,964,603
<p>The API looks the way it does for a reason... Using the builtin type APIs as documented is Pythonic...</p> <p>You should typically do <code>my_dict.get('key', default_value)</code> rather than <code>my_dict.get('key') or default_value</code>.</p> <p>The exception would be the odd case want to replace all false-equ...
0
2015-11-27T20:46:23Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
35,574,940
<p>Solution to dict.has_key() is deprecated, use 'in' -- sublime text editor 3</p> <p>Here I have taken an example of dictionary named 'ages' -</p> <pre><code>ages = {} # Add a couple of names to the dictionary ages['Sue'] = 23 ages['Peter'] = 19 ages['Andrew'] = 78 ages['Karren'] = 45 # use of 'in' in if condit...
1
2016-02-23T10:29:07Z
[ "python" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
1,323,503
<p>Change the BaseTest method name to setUp:</p> <pre><code>class BaseTest(unittest.TestCase): def setUp(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub...
-2
2009-08-24T16:48:27Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
1,323,519
<p>What are you trying to achieve? If you have common test code (assertions, template tests, etc), then place them in methods which aren't prefixed with <code>test</code> so <code>unittest</code> won't load them.</p> <pre><code>import unittest class CommonTests(unittest.TestCase): def common_assertion(self, foo...
7
2009-08-24T16:52:44Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
1,323,554
<p>Use multiple inheritance, so your class with common tests doesn't itself inherit from TestCase.</p> <pre><code>import unittest class CommonTests(object): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(unittest.TestCase, Co...
99
2009-08-24T17:00:01Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
6,459,279
<p>Matthew's answer is the one I needed to use since I'm on 2.5 still. But as of 2.7 you can use the @unittest.skip() decorator on any test methods you want to skip.</p> <p><a href="http://docs.python.org/library/unittest.html#skipping-tests-and-expected-failures" rel="nofollow">http://docs.python.org/library/unittest...
4
2011-06-23T19:01:10Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
17,696,807
<p>Matthew Marshall's answer is great, but it requires that you inherit from two classes in each of your test cases, which is error-prone. Instead, I use this (python>=2.7):</p> <pre><code>class BaseTest(unittest.TestCase): @classmethod def setUpClass(cls): if cls is BaseTest: raise unitte...
16
2013-07-17T10:01:59Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
22,836,015
<p>You can solve this problem with a single command:</p> <pre><code>del(BaseTest) </code></pre> <p>So the code would look like this:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(va...
17
2014-04-03T11:20:31Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
24,924,066
<p>A way I've thought of solving this is by hiding the test methods if the base class is used. This way the tests aren't skipped, so the test results can be green instead of yellow in many test reporting tools.</p> <p>Compared to the mixin method, ide's like PyCharm won't complain that unit test methods are missing fr...
2
2014-07-24T02:15:58Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
25,695,512
<p>Do not use multiple inheritance, it will bite you <a href="http://nedbatchelder.com/blog/201210/multiple_inheritance_is_hard.html">later</a>.</p> <p>Instead you can just move your base class into the separate module or wrap it with the blank class:</p> <pre><code>import unittest class BaseTestCases: class Ba...
47
2014-09-05T23:58:24Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
25,895,445
<p>Another option is not to execute</p> <pre><code>unittest.main() </code></pre> <p>Instead of that you can use</p> <pre><code>suite = unittest.TestLoader().loadTestsFromTestCase(TestClass) unittest.TextTestRunner(verbosity=2).run(suite) </code></pre> <p>So you only execute the tests in the class <code>TestClass</c...
1
2014-09-17T16:09:50Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
32,642,151
<p>Just rename the testCommon method to something else. Unittest (usually) skips anything that doesn't have 'test' in it.</p> <p>Quick and simple </p> <pre><code> import unittest class BaseTest(unittest.TestCase): def methodCommon(self): print 'Calling BaseTest:testCommon' value = 5 self....
-1
2015-09-18T00:45:16Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def...
65
2009-08-24T16:39:41Z
37,285,261
<p>I made about the same than @Vladim P. (<a href="http://stackoverflow.com/a/25695512/2451329">http://stackoverflow.com/a/25695512/2451329</a>) but slightly modified:</p> <pre><code>import unittest2 from some_module import func1, func2 def make_base_class(func): class Base(unittest2.TestCase): def t...
0
2016-05-17T20:02:34Z
[ "python", "unit-testing", "testing" ]
Why do I get 'service unavailable' with multiple chat sends when using XMPP?
1,323,693
<p>I have made a simple IM client in both Python and C#, using a few different XMPP libraries for each.</p> <p>They work very well as simple autoresponders, or trivial bots, but when I turn them into chat rooms (ie, a message gets reflected to many other JIDs), I suddenly start getting 503 service-unavailable response...
1
2009-08-24T17:29:05Z
1,337,596
<p>Do you have all people you try to send messages to in your rooster? Otherwise GTalk won't allow the message to be sent and instead return Error 503.</p> <p>There was a pidgin bug tracker describing a similar problem: <a href="http://pidgin.im/pipermail/tracker/2007-December/019925.html" rel="nofollow">Pidgin #4236<...
2
2009-08-26T21:27:55Z
[ "c#", "python", "xmpp" ]
Why do I get 'service unavailable' with multiple chat sends when using XMPP?
1,323,693
<p>I have made a simple IM client in both Python and C#, using a few different XMPP libraries for each.</p> <p>They work very well as simple autoresponders, or trivial bots, but when I turn them into chat rooms (ie, a message gets reflected to many other JIDs), I suddenly start getting 503 service-unavailable response...
1
2009-08-24T17:29:05Z
1,339,931
<p>If you're looking to create actual chat rooms, why not rather get a jabber server to host those (following <a href="http://xmpp.org/extensions/xep-0045.html" rel="nofollow">http://xmpp.org/extensions/xep-0045.html</a> - ejabberd has these as default and there are plugins for most jabber servers to implement them), a...
1
2009-08-27T09:28:51Z
[ "c#", "python", "xmpp" ]
Running Panda3D on Python 2.6
1,323,887
<p>I just got Panda3D for the first time. I deleted the included Python version. In my Python dir, I put a file <code>panda.pth</code> that looks like this:</p> <pre><code>C:\Panda3D-1.6.2 C:\Panda3D-1.6.2\bin </code></pre> <p>But when I run <code>import direct.directbase.DirectStart</code>, I get:</p> <pre><code>Tr...
0
2009-08-24T18:13:17Z
1,323,989
<p>Python extensions aren't binary compatible across major releases. Your options are:</p> <p>A. Recompile panda3d for python 2.6.</p> <p>B. Use python 2.5.</p> <p>No way around it.</p>
2
2009-08-24T18:32:29Z
[ "python", "panda3d" ]
Running Panda3D on Python 2.6
1,323,887
<p>I just got Panda3D for the first time. I deleted the included Python version. In my Python dir, I put a file <code>panda.pth</code> that looks like this:</p> <pre><code>C:\Panda3D-1.6.2 C:\Panda3D-1.6.2\bin </code></pre> <p>But when I run <code>import direct.directbase.DirectStart</code>, I get:</p> <pre><code>Tr...
0
2009-08-24T18:13:17Z
1,324,037
<p>If you can wait for the upcoming 1.7.0 release, it will be compiled against Python 2.6 - see <a href="http://www.panda3d.org/phpbb2/viewtopic.php?p=42778&amp;sid=d77e7708ac0d9d3f79c19c0fcd5c4621" rel="nofollow">this thread</a>.</p>
1
2009-08-24T18:44:32Z
[ "python", "panda3d" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to ...
48
2009-08-24T18:52:52Z
1,324,114
<p>The Unicode version of translate requires a mapping from Unicode ordinals (which you can retrieve for a single character with <code>ord</code>) to Unicode ordinals. If you want to delete characters, you map to <code>None</code>.</p> <p>I changed your function to build a dict mapping the ordinal of every character t...
44
2009-08-24T19:02:57Z
[ "python", "unicode", "string" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to ...
48
2009-08-24T18:52:52Z
1,324,274
<p>I came up with the following combination of my original function and <a href="http://stackoverflow.com/users/66502/mike-boers">Mike</a>'s version that works with Unicode and ASCII strings:</p> <pre><code>def translate_non_alphanumerics(to_translate, translate_to=u'_'): not_letters_or_digits = u'!"#%\'()*+,-./:;...
4
2009-08-24T19:33:25Z
[ "python", "unicode", "string" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to ...
48
2009-08-24T18:52:52Z
1,324,461
<p>For a simple hack that will work on both str and unicode objects, convert the translation table to unicode before running translate():</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_tabl...
3
2009-08-24T20:07:33Z
[ "python", "unicode", "string" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to ...
48
2009-08-24T18:52:52Z
13,179,797
<p>Instead of having to specify all the characters that need to be replaced, you could also view it the other way around and, instead, specify only the valid characters, like so:</p> <pre><code>import re def replace_non_alphanumerics(source, replacement_character='_'): result = re.sub("[^_a-zA-Z0-9]", replacement...
0
2012-11-01T15:00:31Z
[ "python", "unicode", "string" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to ...
48
2009-08-24T18:52:52Z
19,113,364
<p>In this version you can relatively make one's letters to other </p> <pre><code>def trans(to_translate): tabin = u'привет' tabout = u'тевирп' tabin = [ord(char) for char in tabin] translate_table = dict(zip(tabin, tabout)) return to_translate.translate(translate_table) </code></pre>...
6
2013-10-01T10:04:15Z
[ "python", "unicode", "string" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,324,258
<p>From the <a href="http://jinja.pocoo.org/2/documentation/faq">jinja2 docs</a>, it seems that string.Template is the fastest if that's all you need.</p> <blockquote> <p>Without a doubt you should try to remove as much logic from templates as possible. But templates without any logic mean that you have to do ...
7
2009-08-24T19:30:46Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,324,515
<p>In general you will have to do profiling to answer that question, as it depends on how you use the templates and what for.</p> <p>string.Template is the fastest, but so primitive it can hardly be called a template in the same breath as the other templating systems, as it only does string replacements, and has no co...
1
2009-08-24T20:19:22Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,325,478
<p>I think Cheetah might be the fastest, as it's implemented in C.</p>
-1
2009-08-25T00:29:17Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,326,219
<p>Here are the results of the popular template engines for rendering a 10x1000 HTML table.</p> <pre><code>Python 2.6.2 on a 3GHz Intel Core 2 Kid template 696.89 ms Kid template + cElementTree 649.88 ms Genshi template + tag builder 431.01 ms Genshi tag builder ...
87
2009-08-25T05:28:48Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,698,458
<p>If you can throw caching in the mix (like memcached) then choose based on features and ease of use rather than optimization.</p> <p>I use Mako because I like the syntax and features. Fortunately it is one of the fastest as well.</p>
3
2009-11-09T00:16:00Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
How to alphabetically sort the values in a many-to-many django-admin box?
1,324,602
<p>I have a simple model like this one:</p> <pre><code>class Artist(models.Model): surname = models.CharField(max_length=200) name = models.CharField(max_length=200, blank=True) slug = models.SlugField(unique=True) photo = models.ImageField(upload_to='artists', blank=True) bio = models.TextField(blank=T...
7
2009-08-24T20:35:58Z
1,324,649
<p>Set <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#ordering"><code>ordering</code></a> on the Article's inner <code>Meta</code> class.</p> <pre><code>class Article(models.Model): .... class Meta: ordering = ['surname', 'name'] </code></pre>
7
2009-08-24T20:43:49Z
[ "python", "django", "sorting", "django-admin", "many-to-many" ]
What python modules are available to assist in daemonization in the standard library?
1,324,651
<p>I have a simple python program that I'd like to daemonize. </p> <p>Since the point of my doing this is not to demonstrate mastery over the spawn, fork, disconnect , etc, I'd like to find a module that would make it quick and simple for me. I've been looking in the std lib, but can not seem to find anything. </p> ...
3
2009-08-24T20:43:59Z
1,324,692
<p>Here's a library for making well behaved unix daemons: <a href="http://pypi.python.org/pypi/python-daemon/" rel="nofollow">http://pypi.python.org/pypi/python-daemon/</a></p> <p>And another one that appears more lightweight: <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">http://code.activestate...
4
2009-08-24T20:49:20Z
[ "python", "daemon" ]
What python modules are available to assist in daemonization in the standard library?
1,324,651
<p>I have a simple python program that I'd like to daemonize. </p> <p>Since the point of my doing this is not to demonstrate mastery over the spawn, fork, disconnect , etc, I'd like to find a module that would make it quick and simple for me. I've been looking in the std lib, but can not seem to find anything. </p> ...
3
2009-08-24T20:43:59Z
1,324,709
<pre><code>subprocess </code></pre> <p>is an (almost) platform-independent module to work with processes.</p>
-1
2009-08-24T20:53:01Z
[ "python", "daemon" ]
python time interval algorithm sum
1,324,748
<p>Hello Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval insid...
2
2009-08-24T20:59:25Z
1,324,813
<p>I'll assume you can do the conversion to something like <a href="http://docs.python.org/library/datetime.html" rel="nofollow">datetime</a> on your own.</p> <p>Sum the two intervals, then subtract any overlap. You can get the overlap by comparing the min and max of each of the two ranges.</p>
0
2009-08-24T21:12:39Z
[ "python", "time", "intervals" ]
python time interval algorithm sum
1,324,748
<p>Hello Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval insid...
2
2009-08-24T20:59:25Z
1,324,848
<pre><code>from datetime import datetime, timedelta START, END = xrange(2) def tparse(timestring): return datetime.strptime(timestring, '%H:%M') def sum_intervals(intervals): times = [] for interval in intervals: times.append((tparse(interval[START]), START)) times.append((tparse(interval[...
3
2009-08-24T21:20:39Z
[ "python", "time", "intervals" ]
python time interval algorithm sum
1,324,748
<p>Hello Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval insid...
2
2009-08-24T20:59:25Z
1,324,880
<p>Code for when there is an overlap, please add it to one of your solutions:</p> <pre><code>def interval(i1, i2): minstart, minend = [min(*e) for e in zip(i1, i2)] maxstart, maxend = [max(*e) for e in zip(i1, i2)] if minend &lt; maxstart: # no overlap return minend-minstart + maxend-maxstart ...
0
2009-08-24T21:30:44Z
[ "python", "time", "intervals" ]
python time interval algorithm sum
1,324,748
<p>Hello Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval insid...
2
2009-08-24T20:59:25Z
1,325,221
<p>You'll want to convert your strings into datetimes. You can do this with <code>datetime.datetime.strptime</code>.</p> <p>Given intervals of <code>datetime.datetime</code> objects, if the intervals are:</p> <pre><code>int1 = (start1, end1) int2 = (start2, end2) </code></pre> <p>Then isn't it just:</p> <pre><code...
0
2009-08-24T22:55:39Z
[ "python", "time", "intervals" ]
Match database output (balanced parentheses, table & rows structure) and output as a list?
1,324,949
<p>How would I parse the following input (either going line by line or via regex... or combination of both):</p> <pre><code>Table[ Row[ C_ID[Data:12345.0][Sec:12345.0][Type:Double] F_ID[Data:17660][Sec:17660][Type:Long] NAME[Data:Mike Jones][Sec:Mike Jones][Type:String] ] Row[ C_ID[...
0
2009-08-24T21:45:27Z
1,324,992
<p>Parsing recursive structures with regex is a pain because you have to keep state.</p> <p>Instead, use <a href="http://pyparsing.wikispaces.com" rel="nofollow">pyparsing</a> or some other real parser.</p> <p>Some folks like <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a> because it follows the tradition...
3
2009-08-24T21:56:58Z
[ "python", "regex", "parsing" ]
Match database output (balanced parentheses, table & rows structure) and output as a list?
1,324,949
<p>How would I parse the following input (either going line by line or via regex... or combination of both):</p> <pre><code>Table[ Row[ C_ID[Data:12345.0][Sec:12345.0][Type:Double] F_ID[Data:17660][Sec:17660][Type:Long] NAME[Data:Mike Jones][Sec:Mike Jones][Type:String] ] Row[ C_ID[...
0
2009-08-24T21:45:27Z
1,325,165
<p>This excellent <a href="http://nedbatchelder.com/text/python-parsers.html" rel="nofollow">page</a> lists many parsers available to Python programmers. Regexes are unsuitable for "balanced parentheses" matching, but any of the third party packages reviewed on that page will serve you well.</p>
0
2009-08-24T22:40:29Z
[ "python", "regex", "parsing" ]
Match database output (balanced parentheses, table & rows structure) and output as a list?
1,324,949
<p>How would I parse the following input (either going line by line or via regex... or combination of both):</p> <pre><code>Table[ Row[ C_ID[Data:12345.0][Sec:12345.0][Type:Double] F_ID[Data:17660][Sec:17660][Type:Long] NAME[Data:Mike Jones][Sec:Mike Jones][Type:String] ] Row[ C_ID[...
0
2009-08-24T21:45:27Z
1,325,382
<p>This regex:</p> <pre><code>Row\[[\s]*C_ID\[[\W]*Data:([0-9.]*)[\S\W]*F_ID\[[\S\W]*Data:([0-9.]*)[\S\W]*NAME\[[\S\W]*Data:([\w ]*)[\S ]* </code></pre> <p>for the first row will match:</p> <p>$1=12345.0 $2=17660 $3=Mike Jones</p> <p>Then you can use something like this:</p> <pre><code>{'C_ID': $1, 'F_ID': $2, 'NA...
-1
2009-08-24T23:57:05Z
[ "python", "regex", "parsing" ]
Match database output (balanced parentheses, table & rows structure) and output as a list?
1,324,949
<p>How would I parse the following input (either going line by line or via regex... or combination of both):</p> <pre><code>Table[ Row[ C_ID[Data:12345.0][Sec:12345.0][Type:Double] F_ID[Data:17660][Sec:17660][Type:Long] NAME[Data:Mike Jones][Sec:Mike Jones][Type:String] ] Row[ C_ID[...
0
2009-08-24T21:45:27Z
1,390,191
<p>There really isn't a lot of unpredictable nesting going on here, so you could do this with regex's. But pyparsing is my tool of choice, so here is my solution:</p> <pre><code>from pyparsing import * LBRACK,RBRACK,COLON = map(Suppress,"[]:") ident = Word(alphas, alphanums+"_") datatype = oneOf("Double Long String ...
1
2009-09-07T16:57:32Z
[ "python", "regex", "parsing" ]
What order does SQLAlchemy use for primary key columns?
1,325,018
<p>Let's say I create a table like this:</p> <pre><code>table = Table('mytable', metadata, Column('a', Integer, primary_key=True), Column('b', Integer, primary_key=True), ) table.create() </code></pre> <p>Is it guaranteed that the primary key will be (a,b) and not (b,a)?</p>
0
2009-08-24T22:01:47Z
1,325,106
<p>Yes. It will be a really bad thing if resulting DDL wasn't giving consistent results.</p>
0
2009-08-24T22:24:18Z
[ "python", "sqlalchemy" ]
What order does SQLAlchemy use for primary key columns?
1,325,018
<p>Let's say I create a table like this:</p> <pre><code>table = Table('mytable', metadata, Column('a', Integer, primary_key=True), Column('b', Integer, primary_key=True), ) table.create() </code></pre> <p>Is it guaranteed that the primary key will be (a,b) and not (b,a)?</p>
0
2009-08-24T22:01:47Z
1,325,318
<p>USe echo=True and compare yours with a swapped version? That should give the answer.</p>
1
2009-08-24T23:29:28Z
[ "python", "sqlalchemy" ]
What order does SQLAlchemy use for primary key columns?
1,325,018
<p>Let's say I create a table like this:</p> <pre><code>table = Table('mytable', metadata, Column('a', Integer, primary_key=True), Column('b', Integer, primary_key=True), ) table.create() </code></pre> <p>Is it guaranteed that the primary key will be (a,b) and not (b,a)?</p>
0
2009-08-24T22:01:47Z
1,325,548
<p>its guaranteed, yes, since <code>Column</code> objects in <code>Table</code> are ordered. or if you really want to be explicit, use <code>PrimaryKeyContraint()</code>.</p>
3
2009-08-25T01:00:34Z
[ "python", "sqlalchemy" ]
Generate unique ID for python object based on its attributes
1,325,195
<p>Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, </p> <pre><code>class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) </code></pre>...
9
2009-08-24T22:47:22Z
1,325,216
<p>You mean something like this? Using the special method <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fhash%5F%5F" rel="nofollow"><code>__hash__</code></a></p> <pre><code>class test: def __init__(self, name): self.name = name def __hash__(self): return hash(self.nam...
6
2009-08-24T22:54:21Z
[ "python", "object", "attributes" ]
Generate unique ID for python object based on its attributes
1,325,195
<p>Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, </p> <pre><code>class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) </code></pre>...
9
2009-08-24T22:47:22Z
1,325,231
<p>Have a lool at the <a href="http://docs.python.org/library/functions.html#hash" rel="nofollow">hash() build in function</a> and the <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fhash%5F%5F" rel="nofollow"><code>__hash__()</code> object method</a>. These may be just what you are looking for. Y...
2
2009-08-24T22:56:48Z
[ "python", "object", "attributes" ]
Generate unique ID for python object based on its attributes
1,325,195
<p>Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, </p> <pre><code>class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) </code></pre>...
9
2009-08-24T22:47:22Z
1,325,234
<p><strong>To get a unique comparison:</strong></p> <p>To be unique you could serialize the data and then compare the serialized value to ensure it matches exactly.</p> <p>Example:</p> <pre><code>import pickle class C: i = 1 j = 2 c1 = C() c2 = C() c3 = C() c1.i = 99 unique_hash1 = pickle.dumps(c1) unique_ha...
3
2009-08-24T22:57:31Z
[ "python", "object", "attributes" ]
Generate unique ID for python object based on its attributes
1,325,195
<p>Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, </p> <pre><code>class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) </code></pre>...
9
2009-08-24T22:47:22Z
1,325,275
<p>I guess</p> <pre><code>def hash_attr(ins): return hash(tuple(ins.__dict__.items())) </code></pre> <p>hashes anything instance based on its attributes.</p>
2
2009-08-24T23:16:18Z
[ "python", "object", "attributes" ]
Importing a text file into SQL Server in Python
1,325,481
<p>I am writing a python script that will be doing some processing on text files. As part of that process, i need to import each line of the tab-separated file into a local MS SQL Server (2008) table. I am using pyodbc and I know how to do this. However, I have a question about the best way to execute it.</p> <p>I ...
1
2009-08-25T00:30:51Z
1,325,524
<p>If I understand what you are doing, Python is not going to be a problem. Executing a statement inside a transaction does not create cumulative state in Python. It will do so only at the database server itself.</p> <p>When you commit you will need to make sure the commit occurred, since having a large batch commit...
0
2009-08-25T00:47:19Z
[ "python", "database", "odbc", "commit", "bulkinsert" ]
Importing a text file into SQL Server in Python
1,325,481
<p>I am writing a python script that will be doing some processing on text files. As part of that process, i need to import each line of the tab-separated file into a local MS SQL Server (2008) table. I am using pyodbc and I know how to do this. However, I have a question about the best way to execute it.</p> <p>I ...
1
2009-08-25T00:30:51Z
1,325,882
<p>Create a file and use <a href="http://msdn.microsoft.com/en-us/library/ms188365.aspx" rel="nofollow">BULK INSER</a>T. It will be faster.</p>
0
2009-08-25T03:16:43Z
[ "python", "database", "odbc", "commit", "bulkinsert" ]
Mutate an integer array using ctypes
1,325,518
<p>Currently I'm in the process of moving a performance bottleneck in my python code to c, to investigate peformance effects. This code will run a simulation, and report back the results to python via ctypes. However, I'm having problems getting my types to match up correctly.</p> <p>Although I'm looking to solve this...
4
2009-08-25T00:44:01Z
1,325,533
<p>Looks like you want <a href="http://docs.python.org/library/ctypes.html#type-conversions" rel="nofollow">the cast function</a>:</p> <blockquote> <p>The cast function can be used to cast a ctypes instance into a pointer to a different ctypes data type. cast takes two parameters, a ctypes object that is or can be c...
4
2009-08-25T00:53:16Z
[ "python", "ctypes" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored rem...
9
2009-08-25T01:10:19Z
1,325,652
<p>If you are trying to write a virtual file system (I may misunderstand you) - I would look at a container file format. VHD is well documented along with HDI and (embedded) OSQ. There are basically two things you need to do. One is you need to decide on a file/container format. After that it is as simple as writing th...
1
2009-08-25T01:45:31Z
[ "python", "windows", "filesystems" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored rem...
9
2009-08-25T01:10:19Z
1,325,685
<p>Does it need to be Windows-native? There is at least one protocol which can be both browsed by Windows Explorer, and served by free Python libraries: FTP. Stick your program behind pyftpdlib and you're done.</p>
2
2009-08-25T01:58:36Z
[ "python", "windows", "filesystems" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored rem...
9
2009-08-25T01:10:19Z
1,325,941
<p>While perhaps not quite ripe yet (unfortunately I have no first-hand experience with it), <a href="http://code.google.com/p/pywinfuse/">pywinfuse</a> looks <em>exactly</em> like what you're looking for.</p>
8
2009-08-25T03:40:39Z
[ "python", "windows", "filesystems" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored rem...
9
2009-08-25T01:10:19Z
5,072,466
<p>Have a look at <a href="https://dokan-dev.github.io/" rel="nofollow">Dokan</a> a User mode filesystem for Windows. There are Ruby, .NET (and Java by 3rd party) bindings available, and I don't think it'll be difficult to write python bindings either.</p>
3
2011-02-21T23:27:44Z
[ "python", "windows", "filesystems" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored rem...
9
2009-08-25T01:10:19Z
34,673,049
<p>You might be interested in <a href="http://pyfilesystem.org" rel="nofollow">PyFilesystem</a>;</p> <blockquote> <p><em>A filesystem abstraction layer for Python</em></p> <p>PyFilesystem is an abstraction layer for filesystems. In the same way that Python's file-like objects provide a common way of accessing f...
1
2016-01-08T09:02:20Z
[ "python", "windows", "filesystems" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> ...
96
2009-08-25T01:53:33Z
1,325,736
<p>Not sure if I completely understand the question, but you can modify instance properties at runtime with the built-in <code>__dict__</code> of your class:</p> <pre><code>class C(object): def __init__(self, ks, vs): self.__dict__ = dict(zip(ks, vs)) if __name__ == "__main__": ks = ['ab', 'cd'] ...
2
2009-08-25T02:19:32Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> ...
96
2009-08-25T01:53:33Z
1,325,756
<p>You cannot add a new property() to an instance at runtime, because properties are data descriptors. Instead you must dynamically create a new class, or over <code>__getattribute__</code> in order to process data descriptors on instances.</p>
4
2009-08-25T02:23:36Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> ...
96
2009-08-25T01:53:33Z
1,325,768
<p>It seems you could solve this problem much more simply with a <a href="http://docs.python.org/library/collections.html#collections.namedtuple"><code>namedtuple</code></a>, since you know the entire list of fields ahead of time.</p> <pre><code>from collections import namedtuple Foo = namedtuple('Foo', ['bar', 'quux...
25
2009-08-25T02:28:05Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> ...
96
2009-08-25T01:53:33Z
1,325,772
<p>Only way to dynamically attach a property is to create a new class and its instance with your new property. </p> <pre><code>class Holder: p = property(lambda x: vs[i], self.fn_readonly) setattr(self, k, Holder().p) </code></pre>
0
2009-08-25T02:29:19Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> ...
96
2009-08-25T01:53:33Z
1,325,798
<p>You don't need to use a property for that. Just override <code>__setattr__</code> to make them read only.</p> <pre><code>class C(object): def __init__(self, keys, values): for (key, value) in zip(keys, values): self.__dict__[key] = value def __setattr__(self, name, value): raise...
20
2009-08-25T02:41:46Z
[ "python", "properties", "runtime", "monkeypatching" ]