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
sequence
Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?
345,401
<p>I've got a couple django models that look like this:</p> <pre><code>from django.contrib.sites.models import Site class Photo(models.Model): title = models.CharField(max_length=100) site = models.ForeignKey(Site) file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=40) site = models.ForeignKey(Site) photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} ) def __unicode__(self): return self.name </code></pre> <p>I'm having all kinds of <em>fun</em> trying to get the <code>limit_choices_to</code> working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible?</p>
5
2008-12-05T22:32:52Z
345,419
<p>According to the <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield" rel="nofollow">docs</a>, "limit_choices_to has no effect when used on a ManyToManyField with an intermediate table". By my reading, that means it has no effect at all, because ManyToManyFields use intermediate tables...</p> <p>I haven't tried to make it work in the Admin site, but from your own views, you can create a form and <a href="http://stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform">override the queryset</a> used to populate the list of choices:</p> <pre><code>form.fields["photos"].queryset = request.user.photo_set.all() </code></pre>
0
2008-12-05T22:41:04Z
[ "python", "django", "foreign-keys", "manytomanyfield", "limit-choices-to" ]
Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?
345,401
<p>I've got a couple django models that look like this:</p> <pre><code>from django.contrib.sites.models import Site class Photo(models.Model): title = models.CharField(max_length=100) site = models.ForeignKey(Site) file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=40) site = models.ForeignKey(Site) photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} ) def __unicode__(self): return self.name </code></pre> <p>I'm having all kinds of <em>fun</em> trying to get the <code>limit_choices_to</code> working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible?</p>
5
2008-12-05T22:32:52Z
345,529
<p>I would delete <code>site</code> field on my <code>Photo</code> model and add a <code>ForeignKey</code> to <code>Gallery</code>. I would remove <code>limit_choices_to</code> from <code>photos</code> fields on <code>Gallery</code> model.</p> <p>Because you are using <code>ForeignKey</code>s to <code>Site</code>s, that means sites don't share galleries and photos. Therefore having those I mentioned above is already useless.</p> <pre><code>class Photo(models.Model): title = models.CharField(max_length=100) gallery = models.ForeignKey(Gallery, related_name='photos') file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=40) site = models.ForeignKey(Site) def __unicode__(self): return self.name </code></pre> <p>Once you set the <code>site</code> on a gallery all its photos will inherit this property. And the site will be accessible as <code>photo_instance.gallery.site</code>:</p> <pre><code>@property def site(self): return self.gallery.site </code></pre> <p>This should work as if you had a <code>site</code> field. But I haven't tested it.</p> <p>Things change or course, if you decide that a gallery or a photo can appear in multiple sites.</p>
1
2008-12-05T23:41:56Z
[ "python", "django", "foreign-keys", "manytomanyfield", "limit-choices-to" ]
Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?
345,401
<p>I've got a couple django models that look like this:</p> <pre><code>from django.contrib.sites.models import Site class Photo(models.Model): title = models.CharField(max_length=100) site = models.ForeignKey(Site) file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=40) site = models.ForeignKey(Site) photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} ) def __unicode__(self): return self.name </code></pre> <p>I'm having all kinds of <em>fun</em> trying to get the <code>limit_choices_to</code> working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible?</p>
5
2008-12-05T22:32:52Z
1,881,187
<p>Yes. You need to override the form that admin uses for the <code>Gallery</code> model, then limit the queryset of the <code>photos</code> field in that form:</p> <pre><code>class GalleryAdminForm(django.forms.ModelForm): class Meta: model = Gallery def __init__(self, *args, **kwargs): super(GalleryAdminForm, self).__init__(*args, **kwargs) self.fields['segments'].queryset = Photo.objects.filter(site=self.instance.site) class GalleryAdmin(django.contrib.admin.ModelAdmin): form = GalleryAdminForm django.contrib.admin.site.register(Gallery, GalleryAdmin) </code></pre>
3
2009-12-10T14:03:46Z
[ "python", "django", "foreign-keys", "manytomanyfield", "limit-choices-to" ]
Is this idiom pythonic? (someBool and "True Result" or "False Result")
345,745
<p>I just came across this idiom in some open-source Python, and I choked on my drink.</p> <p>Rather than:</p> <pre><code>if isUp: return "Up" else: return "Down" </code></pre> <p>or even:</p> <pre><code>return "Up" if isUp else "Down" </code></pre> <p>the code read:</p> <pre><code>return isUp and "Up" or "Down" </code></pre> <p>I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?</p>
7
2008-12-06T01:57:04Z
345,752
<p>That code is a big fugly and clever for my tastes, but I suppose there's not anything wrong with it per se. I think this is really just a case of "make it all fit in one line" syndrome.</p> <p>I personally would have opted for the first form though.</p>
0
2008-12-06T02:03:13Z
[ "coding-style", "python" ]
Is this idiom pythonic? (someBool and "True Result" or "False Result")
345,745
<p>I just came across this idiom in some open-source Python, and I choked on my drink.</p> <p>Rather than:</p> <pre><code>if isUp: return "Up" else: return "Down" </code></pre> <p>or even:</p> <pre><code>return "Up" if isUp else "Down" </code></pre> <p>the code read:</p> <pre><code>return isUp and "Up" or "Down" </code></pre> <p>I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?</p>
7
2008-12-06T01:57:04Z
345,764
<p>No, it is not.</p> <p>I had a somehow <a href="http://stackoverflow.com/questions/331767">similar question</a> the other day. </p> <p>if the construct </p> <pre><code>val if cond else alt </code></pre> <p>Was not very welcome ( at least by the SO community ) and the preferred one was:</p> <pre><code>if cond: val else: alt </code></pre> <p>You can get your own conclusion. :) </p>
-1
2008-12-06T02:10:02Z
[ "coding-style", "python" ]
Is this idiom pythonic? (someBool and "True Result" or "False Result")
345,745
<p>I just came across this idiom in some open-source Python, and I choked on my drink.</p> <p>Rather than:</p> <pre><code>if isUp: return "Up" else: return "Down" </code></pre> <p>or even:</p> <pre><code>return "Up" if isUp else "Down" </code></pre> <p>the code read:</p> <pre><code>return isUp and "Up" or "Down" </code></pre> <p>I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?</p>
7
2008-12-06T01:57:04Z
345,773
<p>The "a and b or c" idiom was the canonical way to express the ternary arithmetic if in Python, before <a href="http://www.python.org/dev/peps/pep-0308/" rel="nofollow">PEP 308</a> was written and implemented. This idiom fails the "b" answer is false itself; to support the general case, you could write</p> <pre><code> return (a and [b] or [c])[0] </code></pre> <p>An alternative way of spelling it was</p> <pre><code> return (b,c)[not a] </code></pre> <p>which, with the introduction of the bool type, could be rewritten as</p> <pre><code> return (c,b)[bool(a)] </code></pre> <p>(in case it isn't clear: the conversion to bool, and the not operator, is necessary if a is not known to be bool already)</p> <p>Today, the conditional expression syntax should be used if the thing must be an expression; else I recommend to use the if statement.</p>
17
2008-12-06T02:14:46Z
[ "coding-style", "python" ]
Is this idiom pythonic? (someBool and "True Result" or "False Result")
345,745
<p>I just came across this idiom in some open-source Python, and I choked on my drink.</p> <p>Rather than:</p> <pre><code>if isUp: return "Up" else: return "Down" </code></pre> <p>or even:</p> <pre><code>return "Up" if isUp else "Down" </code></pre> <p>the code read:</p> <pre><code>return isUp and "Up" or "Down" </code></pre> <p>I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?</p>
7
2008-12-06T01:57:04Z
345,774
<p>Yikes. Not readable at all. For me pythonic means easy to read.</p> <pre><code>return isUp and "Up" or "Down" </code></pre> <p>Sounds something you would do in perl.</p>
-1
2008-12-06T02:15:53Z
[ "coding-style", "python" ]
Is this idiom pythonic? (someBool and "True Result" or "False Result")
345,745
<p>I just came across this idiom in some open-source Python, and I choked on my drink.</p> <p>Rather than:</p> <pre><code>if isUp: return "Up" else: return "Down" </code></pre> <p>or even:</p> <pre><code>return "Up" if isUp else "Down" </code></pre> <p>the code read:</p> <pre><code>return isUp and "Up" or "Down" </code></pre> <p>I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?</p>
7
2008-12-06T01:57:04Z
345,775
<p>You should read <a href="http://www.diveintopython.net/power_of_introspection/and_or.html" rel="nofollow">Using the and-or trick</a> (section 4.6.1) of <i>Dive Into Python</i> by Mark Pilgrim. It turns out that the and-or trick has major pitfalls you should be aware of.</p>
9
2008-12-06T02:20:46Z
[ "coding-style", "python" ]
Refactoring python module configuration to avoid relative imports
345,746
<p>This is related to a <a href="http://stackoverflow.com/questions/343517/how-do-i-work-with-multiple-git-branches-of-a-python-module">previous question</a> of mine.</p> <p>I understand how to store and read configuration files. There are choices such as <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html" rel="nofollow">ConfigParser</a> and <a href="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow">ConfigObj</a>.</p> <p>Consider this structure for a hypothetical 'eggs' module:</p> <pre> eggs/ common/ __init__.py config.py foo/ __init__.py a.py </pre> <p>'eggs.foo.a' needs some configuration information. What I am currently doing is, in 'a', <pre>import eggs.common.config</pre>. One problem with this is that if 'a' is moved to a deeper level in the module tree, the relative imports break. Absolute imports don't, but they require your module to be on your PYTHONPATH.</p> <p>A possible alternative to the above absolute import is a relative import. Thus, in 'a',</p> <pre>import .common.config</pre> <p>Without debating the merits of relative vs absolute imports, I was wondering about other possible solutions?</p> <p>edit- Removed the VCS context</p>
3
2008-12-06T01:57:34Z
345,790
<p>require statement from <a href="http://peak.telecommunity.com/DevCenter/PkgResources#basic-workingset-methods" rel="nofollow">pkg_resources</a> maybe what you need. </p>
0
2008-12-06T02:35:54Z
[ "python", "configuration", "module" ]
Refactoring python module configuration to avoid relative imports
345,746
<p>This is related to a <a href="http://stackoverflow.com/questions/343517/how-do-i-work-with-multiple-git-branches-of-a-python-module">previous question</a> of mine.</p> <p>I understand how to store and read configuration files. There are choices such as <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html" rel="nofollow">ConfigParser</a> and <a href="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow">ConfigObj</a>.</p> <p>Consider this structure for a hypothetical 'eggs' module:</p> <pre> eggs/ common/ __init__.py config.py foo/ __init__.py a.py </pre> <p>'eggs.foo.a' needs some configuration information. What I am currently doing is, in 'a', <pre>import eggs.common.config</pre>. One problem with this is that if 'a' is moved to a deeper level in the module tree, the relative imports break. Absolute imports don't, but they require your module to be on your PYTHONPATH.</p> <p>A possible alternative to the above absolute import is a relative import. Thus, in 'a',</p> <pre>import .common.config</pre> <p>Without debating the merits of relative vs absolute imports, I was wondering about other possible solutions?</p> <p>edit- Removed the VCS context</p>
3
2008-12-06T01:57:34Z
345,799
<p>As I understand it from this and previous questions you only need one path to be in <code>sys.path</code>. If we are talking about <code>git</code> as VCS (mentioned in previous question) when only one branch is checked out at any time (single working directory). You can switch, merge branches as frequently as you like.</p>
0
2008-12-06T02:41:41Z
[ "python", "configuration", "module" ]
Refactoring python module configuration to avoid relative imports
345,746
<p>This is related to a <a href="http://stackoverflow.com/questions/343517/how-do-i-work-with-multiple-git-branches-of-a-python-module">previous question</a> of mine.</p> <p>I understand how to store and read configuration files. There are choices such as <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html" rel="nofollow">ConfigParser</a> and <a href="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow">ConfigObj</a>.</p> <p>Consider this structure for a hypothetical 'eggs' module:</p> <pre> eggs/ common/ __init__.py config.py foo/ __init__.py a.py </pre> <p>'eggs.foo.a' needs some configuration information. What I am currently doing is, in 'a', <pre>import eggs.common.config</pre>. One problem with this is that if 'a' is moved to a deeper level in the module tree, the relative imports break. Absolute imports don't, but they require your module to be on your PYTHONPATH.</p> <p>A possible alternative to the above absolute import is a relative import. Thus, in 'a',</p> <pre>import .common.config</pre> <p>Without debating the merits of relative vs absolute imports, I was wondering about other possible solutions?</p> <p>edit- Removed the VCS context</p>
3
2008-12-06T01:57:34Z
345,921
<p>I'm thinking of something along the lines of a more 'push-based' kind of solution. Instead of importing the shared objects (be they for configuration, or utility functions of some sort), have the top-level <strong>init</strong> export it, and each intermediate <strong>init</strong> import it from the layer above, and immediately re-export it. </p> <p>I'm not sure if I've got the python terminology right, please correct me if I'm wrong. </p> <p>Like this, any module that needs to use the shared object(which in the context of this example represents configuration information) simply imports it from the <strong>init</strong> at its own level.</p> <p>Does this sound sensible/feasible?</p>
0
2008-12-06T04:38:19Z
[ "python", "configuration", "module" ]
Refactoring python module configuration to avoid relative imports
345,746
<p>This is related to a <a href="http://stackoverflow.com/questions/343517/how-do-i-work-with-multiple-git-branches-of-a-python-module">previous question</a> of mine.</p> <p>I understand how to store and read configuration files. There are choices such as <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html" rel="nofollow">ConfigParser</a> and <a href="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow">ConfigObj</a>.</p> <p>Consider this structure for a hypothetical 'eggs' module:</p> <pre> eggs/ common/ __init__.py config.py foo/ __init__.py a.py </pre> <p>'eggs.foo.a' needs some configuration information. What I am currently doing is, in 'a', <pre>import eggs.common.config</pre>. One problem with this is that if 'a' is moved to a deeper level in the module tree, the relative imports break. Absolute imports don't, but they require your module to be on your PYTHONPATH.</p> <p>A possible alternative to the above absolute import is a relative import. Thus, in 'a',</p> <pre>import .common.config</pre> <p>Without debating the merits of relative vs absolute imports, I was wondering about other possible solutions?</p> <p>edit- Removed the VCS context</p>
3
2008-12-06T01:57:34Z
346,330
<p>"imports ... require your module to be on your PYTHONPATH"</p> <p>Right. </p> <p>So, what's wrong with setting <code>PYTHONPATH</code>?</p>
2
2008-12-06T14:41:43Z
[ "python", "configuration", "module" ]
Refactoring python module configuration to avoid relative imports
345,746
<p>This is related to a <a href="http://stackoverflow.com/questions/343517/how-do-i-work-with-multiple-git-branches-of-a-python-module">previous question</a> of mine.</p> <p>I understand how to store and read configuration files. There are choices such as <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html" rel="nofollow">ConfigParser</a> and <a href="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow">ConfigObj</a>.</p> <p>Consider this structure for a hypothetical 'eggs' module:</p> <pre> eggs/ common/ __init__.py config.py foo/ __init__.py a.py </pre> <p>'eggs.foo.a' needs some configuration information. What I am currently doing is, in 'a', <pre>import eggs.common.config</pre>. One problem with this is that if 'a' is moved to a deeper level in the module tree, the relative imports break. Absolute imports don't, but they require your module to be on your PYTHONPATH.</p> <p>A possible alternative to the above absolute import is a relative import. Thus, in 'a',</p> <pre>import .common.config</pre> <p>Without debating the merits of relative vs absolute imports, I was wondering about other possible solutions?</p> <p>edit- Removed the VCS context</p>
3
2008-12-06T01:57:34Z
347,027
<p>You can trick the import mechanism, by adding each subdirectory to <code>egg/__init__.py</code>:</p> <pre><code>__path__.append(__path__[0]+"\\common") __path__.append(__path__[0]+"\\foo") </code></pre> <p>then, you simply import all modules from the egg namespace; e.g. <code>import egg.bar</code> (provided you have file egg/foo/bar.py).<br> Note that foo and common should not be a package - in other words, they should not contain <code>__init__.py</code> file.</p> <p>This solution completely solves the issue of eventually moving files around; however it flattens the namespace and therefore it may not be as good, especially in big projects - personally, I prefer full name resolution.</p>
0
2008-12-07T00:19:24Z
[ "python", "configuration", "module" ]
Python - No handlers could be found for logger "OpenGL.error"
345,991
<p>Okay, what is it, and why does it occur on Win2003 server, but not on WinXP.</p> <p>It doesn't seem to affect my application at all, but I get this error message when I close the application. And it's annoying (as errors messages should be).</p> <p>I am using pyOpenGl and wxPython to do the graphics stuff. Unfortunately, I'm a C# programmer that has taken over this Python app, and I had to learn Python to do it.</p> <p>I can supply code and version numbers etc, but I'm still learning the technical stuff, so any help would be appreciated.</p> <p>Python 2.5, wxPython and pyOpenGL</p>
64
2008-12-06T05:59:43Z
346,501
<p>Looks like OpenGL is trying to report some error on Win2003, however you've not configured your system where to output logging info.</p> <p>You can add the following to the beginning of your program and you'll see details of the error in stderr.</p> <pre><code>import logging logging.basicConfig() </code></pre> <p>Checkout documentation on <a href="https://docs.python.org/2/library/logging.html">logging</a> module to get more config info, conceptually it's similar to log4J.</p>
156
2008-12-06T17:18:34Z
[ "python", "logging", "opengl", "wxpython", "pyopengl" ]
Python - No handlers could be found for logger "OpenGL.error"
345,991
<p>Okay, what is it, and why does it occur on Win2003 server, but not on WinXP.</p> <p>It doesn't seem to affect my application at all, but I get this error message when I close the application. And it's annoying (as errors messages should be).</p> <p>I am using pyOpenGl and wxPython to do the graphics stuff. Unfortunately, I'm a C# programmer that has taken over this Python app, and I had to learn Python to do it.</p> <p>I can supply code and version numbers etc, but I'm still learning the technical stuff, so any help would be appreciated.</p> <p>Python 2.5, wxPython and pyOpenGL</p>
64
2008-12-06T05:59:43Z
369,184
<p>After adding the Logging above, I was able to see that the problem was caused by missing TConstants class, which I was excluding in the py2exe setup.py file. </p> <p>After removing the "Tconstants" from the excluded list, I no longer had problems.</p>
2
2008-12-15T17:52:46Z
[ "python", "logging", "opengl", "wxpython", "pyopengl" ]
Python - No handlers could be found for logger "OpenGL.error"
345,991
<p>Okay, what is it, and why does it occur on Win2003 server, but not on WinXP.</p> <p>It doesn't seem to affect my application at all, but I get this error message when I close the application. And it's annoying (as errors messages should be).</p> <p>I am using pyOpenGl and wxPython to do the graphics stuff. Unfortunately, I'm a C# programmer that has taken over this Python app, and I had to learn Python to do it.</p> <p>I can supply code and version numbers etc, but I'm still learning the technical stuff, so any help would be appreciated.</p> <p>Python 2.5, wxPython and pyOpenGL</p>
64
2008-12-06T05:59:43Z
19,071,788
<p>The <a href="https://code.google.com/p/rainforce/wiki/WartsOfPython#Logging_hidden_magic_%282.x_tested,_3.x_unknown%29" rel="nofollow">proper way</a> to get rid of this message is to configure NullHandler for the root level logger of your library (OpenGL).</p>
3
2013-09-28T21:19:40Z
[ "python", "logging", "opengl", "wxpython", "pyopengl" ]
Postgres - how to return rows with 0 count for missing data?
346,132
<p>I have unevenly distributed data(wrt date) for a few years (2003-2008). I want to query data for a given set of start and end date, grouping the data by any of the supported intervals (day, week, month, quarter, year) in PostgreSQL 8.3 (<a href="http://www.postgresql.org/docs/8.3/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC">http://www.postgresql.org/docs/8.3/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC</a>).</p> <p>The problem is that some of the queries give results continuous over the required period, as this one:</p> <pre><code>select to_char(date_trunc('month',date), 'YYYY-MM-DD'),count(distinct post_id) from some_table where category_id=1 and entity_id = 77 and entity2_id = 115 and date &lt;= '2008-12-06' and date &gt;= '2007-12-01' group by date_trunc('month',date) order by date_trunc('month',date); to_char | count ------------+------- 2007-12-01 | 64 2008-01-01 | 31 2008-02-01 | 14 2008-03-01 | 21 2008-04-01 | 28 2008-05-01 | 44 2008-06-01 | 100 2008-07-01 | 72 2008-08-01 | 91 2008-09-01 | 92 2008-10-01 | 79 2008-11-01 | 65 (12 rows) </code></pre> <p>but some of them miss some intervals because there is no data present, as this one:</p> <pre><code>select to_char(date_trunc('month',date), 'YYYY-MM-DD'),count(distinct post_id) from some_table where category_id=1 and entity_id = 75 and entity2_id = 115 and date &lt;= '2008-12-06' and date &gt;= '2007-12-01' group by date_trunc('month',date) order by date_trunc('month',date); to_char | count ------------+------- 2007-12-01 | 2 2008-01-01 | 2 2008-03-01 | 1 2008-04-01 | 2 2008-06-01 | 1 2008-08-01 | 3 2008-10-01 | 2 (7 rows) </code></pre> <p>where the required resultset is:</p> <pre><code> to_char | count ------------+------- 2007-12-01 | 2 2008-01-01 | 2 2008-02-01 | 0 2008-03-01 | 1 2008-04-01 | 2 2008-05-01 | 0 2008-06-01 | 1 2008-07-01 | 0 2008-08-01 | 3 2008-09-01 | 0 2008-10-01 | 2 2008-11-01 | 0 (12 rows) </code></pre> <p>A count of 0 for missing entries.</p> <p>I have seen earlier discussions on Stack Overflow but they don't solve my problem it seems, since my grouping period is one of (day, week, month, quarter, year) and decided on runtime by the application. So an approach like left join with a calendar table or sequence table will not help I guess.</p> <p>My current solution to this is to fill in these gaps in Python (in a Turbogears App) using the calendar module.</p> <p>Is there a better way to do this.</p>
9
2008-12-06T09:32:04Z
346,187
<p>You could create a temporary table at runtime and left join on that. That seems to make the most sense.</p>
0
2008-12-06T10:54:50Z
[ "python", "database", "postgresql" ]
Postgres - how to return rows with 0 count for missing data?
346,132
<p>I have unevenly distributed data(wrt date) for a few years (2003-2008). I want to query data for a given set of start and end date, grouping the data by any of the supported intervals (day, week, month, quarter, year) in PostgreSQL 8.3 (<a href="http://www.postgresql.org/docs/8.3/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC">http://www.postgresql.org/docs/8.3/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC</a>).</p> <p>The problem is that some of the queries give results continuous over the required period, as this one:</p> <pre><code>select to_char(date_trunc('month',date), 'YYYY-MM-DD'),count(distinct post_id) from some_table where category_id=1 and entity_id = 77 and entity2_id = 115 and date &lt;= '2008-12-06' and date &gt;= '2007-12-01' group by date_trunc('month',date) order by date_trunc('month',date); to_char | count ------------+------- 2007-12-01 | 64 2008-01-01 | 31 2008-02-01 | 14 2008-03-01 | 21 2008-04-01 | 28 2008-05-01 | 44 2008-06-01 | 100 2008-07-01 | 72 2008-08-01 | 91 2008-09-01 | 92 2008-10-01 | 79 2008-11-01 | 65 (12 rows) </code></pre> <p>but some of them miss some intervals because there is no data present, as this one:</p> <pre><code>select to_char(date_trunc('month',date), 'YYYY-MM-DD'),count(distinct post_id) from some_table where category_id=1 and entity_id = 75 and entity2_id = 115 and date &lt;= '2008-12-06' and date &gt;= '2007-12-01' group by date_trunc('month',date) order by date_trunc('month',date); to_char | count ------------+------- 2007-12-01 | 2 2008-01-01 | 2 2008-03-01 | 1 2008-04-01 | 2 2008-06-01 | 1 2008-08-01 | 3 2008-10-01 | 2 (7 rows) </code></pre> <p>where the required resultset is:</p> <pre><code> to_char | count ------------+------- 2007-12-01 | 2 2008-01-01 | 2 2008-02-01 | 0 2008-03-01 | 1 2008-04-01 | 2 2008-05-01 | 0 2008-06-01 | 1 2008-07-01 | 0 2008-08-01 | 3 2008-09-01 | 0 2008-10-01 | 2 2008-11-01 | 0 (12 rows) </code></pre> <p>A count of 0 for missing entries.</p> <p>I have seen earlier discussions on Stack Overflow but they don't solve my problem it seems, since my grouping period is one of (day, week, month, quarter, year) and decided on runtime by the application. So an approach like left join with a calendar table or sequence table will not help I guess.</p> <p>My current solution to this is to fill in these gaps in Python (in a Turbogears App) using the calendar module.</p> <p>Is there a better way to do this.</p>
9
2008-12-06T09:32:04Z
346,195
<p>You can create the list of all first days of the last year (say) with</p> <pre><code>select distinct date_trunc('month', (current_date - offs)) as date from generate_series(0,365,28) as offs; date ------------------------ 2007-12-01 00:00:00+01 2008-01-01 00:00:00+01 2008-02-01 00:00:00+01 2008-03-01 00:00:00+01 2008-04-01 00:00:00+02 2008-05-01 00:00:00+02 2008-06-01 00:00:00+02 2008-07-01 00:00:00+02 2008-08-01 00:00:00+02 2008-09-01 00:00:00+02 2008-10-01 00:00:00+02 2008-11-01 00:00:00+01 2008-12-01 00:00:00+01 </code></pre> <p>Then you can join with that series.</p>
16
2008-12-06T11:30:40Z
[ "python", "database", "postgresql" ]
Postgres - how to return rows with 0 count for missing data?
346,132
<p>I have unevenly distributed data(wrt date) for a few years (2003-2008). I want to query data for a given set of start and end date, grouping the data by any of the supported intervals (day, week, month, quarter, year) in PostgreSQL 8.3 (<a href="http://www.postgresql.org/docs/8.3/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC">http://www.postgresql.org/docs/8.3/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC</a>).</p> <p>The problem is that some of the queries give results continuous over the required period, as this one:</p> <pre><code>select to_char(date_trunc('month',date), 'YYYY-MM-DD'),count(distinct post_id) from some_table where category_id=1 and entity_id = 77 and entity2_id = 115 and date &lt;= '2008-12-06' and date &gt;= '2007-12-01' group by date_trunc('month',date) order by date_trunc('month',date); to_char | count ------------+------- 2007-12-01 | 64 2008-01-01 | 31 2008-02-01 | 14 2008-03-01 | 21 2008-04-01 | 28 2008-05-01 | 44 2008-06-01 | 100 2008-07-01 | 72 2008-08-01 | 91 2008-09-01 | 92 2008-10-01 | 79 2008-11-01 | 65 (12 rows) </code></pre> <p>but some of them miss some intervals because there is no data present, as this one:</p> <pre><code>select to_char(date_trunc('month',date), 'YYYY-MM-DD'),count(distinct post_id) from some_table where category_id=1 and entity_id = 75 and entity2_id = 115 and date &lt;= '2008-12-06' and date &gt;= '2007-12-01' group by date_trunc('month',date) order by date_trunc('month',date); to_char | count ------------+------- 2007-12-01 | 2 2008-01-01 | 2 2008-03-01 | 1 2008-04-01 | 2 2008-06-01 | 1 2008-08-01 | 3 2008-10-01 | 2 (7 rows) </code></pre> <p>where the required resultset is:</p> <pre><code> to_char | count ------------+------- 2007-12-01 | 2 2008-01-01 | 2 2008-02-01 | 0 2008-03-01 | 1 2008-04-01 | 2 2008-05-01 | 0 2008-06-01 | 1 2008-07-01 | 0 2008-08-01 | 3 2008-09-01 | 0 2008-10-01 | 2 2008-11-01 | 0 (12 rows) </code></pre> <p>A count of 0 for missing entries.</p> <p>I have seen earlier discussions on Stack Overflow but they don't solve my problem it seems, since my grouping period is one of (day, week, month, quarter, year) and decided on runtime by the application. So an approach like left join with a calendar table or sequence table will not help I guess.</p> <p>My current solution to this is to fill in these gaps in Python (in a Turbogears App) using the calendar module.</p> <p>Is there a better way to do this.</p>
9
2008-12-06T09:32:04Z
15,733,103
<p><sup>This question is old. But since fellow users picked it as master for a new duplicate I am adding a proper answer.</sup></p> <h3>Proper solution</h3> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM ( SELECT day::date FROM generate_series(timestamp '2007-12-01' , timestamp '2008-12-01' , interval '1 month') day ) d LEFT JOIN ( SELECT date_trunc('month', date_col)::date AS day , count(*) AS some_count FROM tbl WHERE date_col &gt;= date '2007-12-01' AND date_col &lt;= date '2008-12-06' -- AND ... more conditions GROUP BY 1 ) t USING (day) ORDER BY day; </code></pre> <ul> <li><p>Use <code>LEFT JOIN</code>, of course.</p></li> <li><p><a href="http://www.postgresql.org/docs/current/interactive/functions-srf.html" rel="nofollow"><code>generate_series()</code></a> can produce a table of timestamps on the fly, and very fast.</p></li> <li><p>It's generally faster to aggregate <em>before</em> you join. I recently provided a test case on sqlfiddle.com in this related answer:</p> <ul> <li><a href="http://stackoverflow.com/questions/15664373/postgresql-order-by-an-array/15674585#15674585">PostgreSQL - order by an array</a></li> </ul></li> <li><p>Cast the <code>timestamp</code> to <code>date</code> (<code>::date</code>) for a basic format. For more use <a href="http://www.postgresql.org/docs/current/interactive/functions-formatting.html" rel="nofollow"><code>to_char()</code></a>.</p></li> <li><p><code>GROUP BY 1</code> is syntax shorthand to reference the first output column. Could be <code>GROUP BY day</code> as well, but that might conflict with an existing column of the same name. Or <code>GROUP BY date_trunc('month', date_col)::date</code> but that's too long for my taste.</p></li> <li><p>Works with the available interval arguments for <a href="http://www.postgresql.org/docs/current/interactive/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC" rel="nofollow"><code>date_trunc()</code></a>.</p></li> <li><p>For a <strong>more generic solution or arbitrary time intervals</strong> consider this closely related answer:</p> <ul> <li><a href="http://stackoverflow.com/questions/15576794/best-way-to-count-records-by-arbitrary-time-intervals-in-railspostgres/15577413#15577413">Best way to count records by arbitrary time intervals in Rails+Postgres</a></li> </ul></li> </ul>
9
2013-03-31T18:44:22Z
[ "python", "database", "postgresql" ]
Read file object as string in python
346,230
<p>I'm using <code>urllib2</code> to read in a page. I need to do a quick regex on the source and pull out a few variables but <code>urllib2</code> presents as a file object rather than a string.</p> <p>I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string?</p>
26
2008-12-06T12:41:36Z
346,237
<p>You can use Python in interactive mode to search for solutions.</p> <p>if <code>f</code> is your object, you can enter <code>dir(f)</code> to see all methods and attributes. There's one called <code>read</code>. Enter <code>help(f.read)</code> and it tells you that <code>f.read()</code> is the way to retrieve a string from an file object.</p>
73
2008-12-06T12:47:18Z
[ "python", "file", "urllib2" ]
Read file object as string in python
346,230
<p>I'm using <code>urllib2</code> to read in a page. I need to do a quick regex on the source and pull out a few variables but <code>urllib2</code> presents as a file object rather than a string.</p> <p>I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string?</p>
26
2008-12-06T12:41:36Z
346,255
<p>From the doc <a href="http://docs.python.org/library/stdtypes.html#file.read">file.read()</a> (my emphasis):</p> <blockquote> <p>file.read([size])</p> <p>Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. <strong>The bytes are returned as a string object</strong>. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.</p> </blockquote> <p>Be aware that a regexp search on a large string object may not be efficient, and consider doing the search line-by-line, using <a href="http://docs.python.org/library/stdtypes.html#file.next">file.next()</a> (a file object is its own iterator).</p>
12
2008-12-06T13:07:39Z
[ "python", "file", "urllib2" ]
Read file object as string in python
346,230
<p>I'm using <code>urllib2</code> to read in a page. I need to do a quick regex on the source and pull out a few variables but <code>urllib2</code> presents as a file object rather than a string.</p> <p>I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string?</p>
26
2008-12-06T12:41:36Z
346,260
<p>Michael Foord, aka Voidspace has an excellent tutorial on urllib2 which you can find here: <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml">urllib2 - The Missing Manual</a></p> <p>What you are doing should be pretty straightforward, observe this sample code:</p> <pre><code>import urllib2 import re response = urllib2.urlopen("http://www.voidspace.org.uk/python/articles/urllib2.shtml") html = response.read() pattern = '(V.+space)' wordPattern = re.compile(pattern, re.IGNORECASE) results = wordPattern.search(html) print results.groups() </code></pre>
5
2008-12-06T13:17:59Z
[ "python", "file", "urllib2" ]
Python regex
346,267
<p>I have a string like this that I need to parse into a 2D array:</p> <pre><code> str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" </code></pre> <p>the array equiv would be:</p> <pre><code>arr[0][0] = 813702104 arr[0][1] = 813702106 arr[1][0] = 813702141 arr[1][1] = 813702143 #... etc ... </code></pre> <p>I'm trying to do this by REGEX. The string above is buried in an HTML page but I can be certain it's the only string in that pattern on the page. I'm not sure if this is the best way, but it's all I've got right now.</p> <pre><code>imgRegex = re.compile(r"(?:'(?P&lt;main&gt;\d+)\[(?P&lt;thumb&gt;\d+)\]',?)+") </code></pre> <p>If I run <code>imgRegex.match(str).groups()</code> I only get one result (the first couplet). How do I either get multiple matches back or a 2d match object (if such a thing exists!)?</p> <p><em>Note: Contrary to how it might look, this is <strong>not</strong> homework</em></p> <h1>Note <em>part deux</em>: The real string is embedded in a <em>large</em> HTML file and therefore splitting does not appear to be an option.</h1> <p>I'm still getting answers for this, so I thought I better edit it to show why I'm not changing the accepted answer. Splitting, though more efficient on this test string, isn't going to extract the parts from a whole HTML file. I <em>could</em> combine a regex and splitting but that seems silly.</p> <p>If you do have a better way to find the parts from a load of HTML (the pattern <code>\d+\[\d+\]</code> is unique to this string in the source), I'll happily change accepted answers. Anything else is academic.</p>
3
2008-12-06T13:31:05Z
346,276
<p>I would try <code>findall</code> or <code>finditer</code> instead of <code>match</code>.</p> <p>Edit by Oli: Yeah <code>findall</code> work brilliantly but I had to simplify the regex to:</p> <pre><code>r"'(?P&lt;main&gt;\d+)\[(?P&lt;thumb&gt;\d+)\]',?" </code></pre>
5
2008-12-06T13:38:54Z
[ "python", "regex" ]
Python regex
346,267
<p>I have a string like this that I need to parse into a 2D array:</p> <pre><code> str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" </code></pre> <p>the array equiv would be:</p> <pre><code>arr[0][0] = 813702104 arr[0][1] = 813702106 arr[1][0] = 813702141 arr[1][1] = 813702143 #... etc ... </code></pre> <p>I'm trying to do this by REGEX. The string above is buried in an HTML page but I can be certain it's the only string in that pattern on the page. I'm not sure if this is the best way, but it's all I've got right now.</p> <pre><code>imgRegex = re.compile(r"(?:'(?P&lt;main&gt;\d+)\[(?P&lt;thumb&gt;\d+)\]',?)+") </code></pre> <p>If I run <code>imgRegex.match(str).groups()</code> I only get one result (the first couplet). How do I either get multiple matches back or a 2d match object (if such a thing exists!)?</p> <p><em>Note: Contrary to how it might look, this is <strong>not</strong> homework</em></p> <h1>Note <em>part deux</em>: The real string is embedded in a <em>large</em> HTML file and therefore splitting does not appear to be an option.</h1> <p>I'm still getting answers for this, so I thought I better edit it to show why I'm not changing the accepted answer. Splitting, though more efficient on this test string, isn't going to extract the parts from a whole HTML file. I <em>could</em> combine a regex and splitting but that seems silly.</p> <p>If you do have a better way to find the parts from a load of HTML (the pattern <code>\d+\[\d+\]</code> is unique to this string in the source), I'll happily change accepted answers. Anything else is academic.</p>
3
2008-12-06T13:31:05Z
346,281
<p>Modifying your regexp a little,</p> <pre><code>&gt;&gt;&gt; str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]" &gt;&gt;&gt; imgRegex = re.compile(r"'(?P&lt;main&gt;\d+)\[(?P&lt;thumb&gt;\d+)\]',?") &gt;&gt;&gt; print imgRegex.findall(str) [('813702104', '813702106'), ('813702141', '813702143')] </code></pre> <p>Which is a "2 dimensional array" - in Python, "a list of 2-tuples".</p>
1
2008-12-06T13:44:13Z
[ "python", "regex" ]
Python regex
346,267
<p>I have a string like this that I need to parse into a 2D array:</p> <pre><code> str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" </code></pre> <p>the array equiv would be:</p> <pre><code>arr[0][0] = 813702104 arr[0][1] = 813702106 arr[1][0] = 813702141 arr[1][1] = 813702143 #... etc ... </code></pre> <p>I'm trying to do this by REGEX. The string above is buried in an HTML page but I can be certain it's the only string in that pattern on the page. I'm not sure if this is the best way, but it's all I've got right now.</p> <pre><code>imgRegex = re.compile(r"(?:'(?P&lt;main&gt;\d+)\[(?P&lt;thumb&gt;\d+)\]',?)+") </code></pre> <p>If I run <code>imgRegex.match(str).groups()</code> I only get one result (the first couplet). How do I either get multiple matches back or a 2d match object (if such a thing exists!)?</p> <p><em>Note: Contrary to how it might look, this is <strong>not</strong> homework</em></p> <h1>Note <em>part deux</em>: The real string is embedded in a <em>large</em> HTML file and therefore splitting does not appear to be an option.</h1> <p>I'm still getting answers for this, so I thought I better edit it to show why I'm not changing the accepted answer. Splitting, though more efficient on this test string, isn't going to extract the parts from a whole HTML file. I <em>could</em> combine a regex and splitting but that seems silly.</p> <p>If you do have a better way to find the parts from a load of HTML (the pattern <code>\d+\[\d+\]</code> is unique to this string in the source), I'll happily change accepted answers. Anything else is academic.</p>
3
2008-12-06T13:31:05Z
346,284
<p>I've got something that seems to work on your data set:</p> <pre><code>In [19]: str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" In [20]: ptr = re.compile( r"'(?P&lt;one&gt;\d+)\[(?P&lt;two&gt;\d+)\]'" ) In [21]: ptr.findall( str ) Out [23]: [('813702104', '813702106'), ('813702141', '813702143'), ('813702172', '813702174')] </code></pre>
1
2008-12-06T13:50:55Z
[ "python", "regex" ]
Python regex
346,267
<p>I have a string like this that I need to parse into a 2D array:</p> <pre><code> str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" </code></pre> <p>the array equiv would be:</p> <pre><code>arr[0][0] = 813702104 arr[0][1] = 813702106 arr[1][0] = 813702141 arr[1][1] = 813702143 #... etc ... </code></pre> <p>I'm trying to do this by REGEX. The string above is buried in an HTML page but I can be certain it's the only string in that pattern on the page. I'm not sure if this is the best way, but it's all I've got right now.</p> <pre><code>imgRegex = re.compile(r"(?:'(?P&lt;main&gt;\d+)\[(?P&lt;thumb&gt;\d+)\]',?)+") </code></pre> <p>If I run <code>imgRegex.match(str).groups()</code> I only get one result (the first couplet). How do I either get multiple matches back or a 2d match object (if such a thing exists!)?</p> <p><em>Note: Contrary to how it might look, this is <strong>not</strong> homework</em></p> <h1>Note <em>part deux</em>: The real string is embedded in a <em>large</em> HTML file and therefore splitting does not appear to be an option.</h1> <p>I'm still getting answers for this, so I thought I better edit it to show why I'm not changing the accepted answer. Splitting, though more efficient on this test string, isn't going to extract the parts from a whole HTML file. I <em>could</em> combine a regex and splitting but that seems silly.</p> <p>If you do have a better way to find the parts from a load of HTML (the pattern <code>\d+\[\d+\]</code> is unique to this string in the source), I'll happily change accepted answers. Anything else is academic.</p>
3
2008-12-06T13:31:05Z
346,292
<p>I think I will not go for regex for this task. Python list comprehension is quite powerful for this</p> <pre><code>In [27]: s = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" In [28]: d=[[int(each1.strip(']\'')) for each1 in each.split('[')] for each in s.split(',')] In [29]: d[0][1] Out[29]: 813702106 In [30]: d[1][0] Out[30]: 813702141 In [31]: d Out[31]: [[813702104, 813702106], [813702141, 813702143], [813702172, 813702174]] </code></pre>
3
2008-12-06T13:54:34Z
[ "python", "regex" ]
Python regex
346,267
<p>I have a string like this that I need to parse into a 2D array:</p> <pre><code> str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" </code></pre> <p>the array equiv would be:</p> <pre><code>arr[0][0] = 813702104 arr[0][1] = 813702106 arr[1][0] = 813702141 arr[1][1] = 813702143 #... etc ... </code></pre> <p>I'm trying to do this by REGEX. The string above is buried in an HTML page but I can be certain it's the only string in that pattern on the page. I'm not sure if this is the best way, but it's all I've got right now.</p> <pre><code>imgRegex = re.compile(r"(?:'(?P&lt;main&gt;\d+)\[(?P&lt;thumb&gt;\d+)\]',?)+") </code></pre> <p>If I run <code>imgRegex.match(str).groups()</code> I only get one result (the first couplet). How do I either get multiple matches back or a 2d match object (if such a thing exists!)?</p> <p><em>Note: Contrary to how it might look, this is <strong>not</strong> homework</em></p> <h1>Note <em>part deux</em>: The real string is embedded in a <em>large</em> HTML file and therefore splitting does not appear to be an option.</h1> <p>I'm still getting answers for this, so I thought I better edit it to show why I'm not changing the accepted answer. Splitting, though more efficient on this test string, isn't going to extract the parts from a whole HTML file. I <em>could</em> combine a regex and splitting but that seems silly.</p> <p>If you do have a better way to find the parts from a load of HTML (the pattern <code>\d+\[\d+\]</code> is unique to this string in the source), I'll happily change accepted answers. Anything else is academic.</p>
3
2008-12-06T13:31:05Z
369,036
<p>Alternatively, you could use Python's [<em>statement</em> for <em>item</em> in <em>list</em>] syntax for building lists. You should find this to be considerably faster than a regex, particularly for small data sets. Larger data sets will show a less marked difference (it only has to load the regular expressions engine once no matter the size), but the listmaker should always be faster.</p> <p>Start by splitting the string on commas:</p> <pre><code>&gt;&gt;&gt; str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" &gt;&gt;&gt; arr = [pair for pair in str.split(",")] &gt;&gt;&gt; arr ["'813702104[813702106]'", "'813702141[813702143]'", "'813702172[813702174]'"] </code></pre> <p>Right now, this returns the same thing as just str.split(","), so isn't very useful, but you should be able to see how the listmaker works — it iterates through list, assigning each value to item, executing statement, and appending the resulting value to the newly-built list.</p> <p>In order to get something useful accomplished, we need to put a real statement in, so we get a slice of each pair which removes the single quotes and closing square bracket, then further split on that conveniently-placed opening square bracket:</p> <pre><code>&gt;&gt;&gt; arr = [pair[1:-2].split("[") for pair in str.split(",")] &gt;&gt;&gt; arr &gt;&gt;&gt; [['813702104', '813702106'], ['813702141', '813702143'], ['813702172', '813702174']] </code></pre> <p>This returns a two-dimensional array like you describe, but the items are all strings rather than integers. If you're simply going to use them as strings, that's far enough. If you need them to be actual integers, you simply use an "inner" listmaker as the statement for the "outer" listmaker:</p> <pre><code>&gt;&gt;&gt; arr = [[int(x) for x in pair[1:-2].split("[")] for pair in str.split(",")] &gt;&gt;&gt; arr &gt;&gt;&gt; [[813702104, 813702106], [813702141, 813702143], [813702172, 813702174]] </code></pre> <p>This returns a two-dimensional array of the integers representing in a string like the one you provided, without ever needing to load the regular expressions engine.</p>
1
2008-12-15T17:04:40Z
[ "python", "regex" ]
Installation problems with django-tagging
346,426
<p>I am having problems using <a href="http://code.google.com/p/django-tagging/" rel="nofollow">django-tagging</a>. I try to follow the <a href="http://code.google.com/p/django-tagging/source/browse/trunk/docs/overview.txt" rel="nofollow">documentation</a> but it fails at the second step</p> <blockquote> <p>Once you've installed Django Tagging and want to use it in your Django applications, do the following:</p> <ol> <li>Put <code>'tagging'</code> in your <code>INSTALLED_APPS</code> setting.</li> <li>Run the command <code>manage.py syncdb</code>.</li> </ol> <p>The <code>syncdb</code> command creates the necessary database tables and creates permission objects for all installed apps that need them.</p> </blockquote> <p>I get a python Traceback with the following error:</p> <pre><code>ImportError: cannot import name parse_lookup </code></pre> <p>The following works, so I think it is correctly installed:</p> <pre><code>&gt;&gt; import tagging &gt;&gt; tagging.VERSION (0, 2.1000000000000001, None) </code></pre> <p>What am I missing?</p>
1
2008-12-06T16:06:42Z
346,435
<p><a href="http://code.djangoproject.com/ticket/7680" rel="nofollow">http://code.djangoproject.com/ticket/7680</a></p> <p>parse_lookup has been removed. Not sure how this will affect tagging. Might want to do some searching. </p> <p>Update: apparently it's been fixed in the trunk version of tagging. Download the latest SVN build of tagging.</p>
4
2008-12-06T16:16:15Z
[ "python", "django", "django-tagging" ]
Installation problems with django-tagging
346,426
<p>I am having problems using <a href="http://code.google.com/p/django-tagging/" rel="nofollow">django-tagging</a>. I try to follow the <a href="http://code.google.com/p/django-tagging/source/browse/trunk/docs/overview.txt" rel="nofollow">documentation</a> but it fails at the second step</p> <blockquote> <p>Once you've installed Django Tagging and want to use it in your Django applications, do the following:</p> <ol> <li>Put <code>'tagging'</code> in your <code>INSTALLED_APPS</code> setting.</li> <li>Run the command <code>manage.py syncdb</code>.</li> </ol> <p>The <code>syncdb</code> command creates the necessary database tables and creates permission objects for all installed apps that need them.</p> </blockquote> <p>I get a python Traceback with the following error:</p> <pre><code>ImportError: cannot import name parse_lookup </code></pre> <p>The following works, so I think it is correctly installed:</p> <pre><code>&gt;&gt; import tagging &gt;&gt; tagging.VERSION (0, 2.1000000000000001, None) </code></pre> <p>What am I missing?</p>
1
2008-12-06T16:06:42Z
346,441
<p>I had the same bug me recently. I checked out the trunk release which seems to work fine. </p> <pre><code>In [1]: import tagging; tagging.VERSION Out[1]: (0, 3, 'pre') </code></pre>
0
2008-12-06T16:22:13Z
[ "python", "django", "django-tagging" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
346,476
<p>Well I couldn't find a Django way, but I did find a python way from inside my model:</p> <pre><code>def format_price(self): import locale locale.setlocale(locale.LC_ALL, '') return locale.format('%d', self.price, True) </code></pre>
2
2008-12-06T16:56:39Z
[ "python", "django" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
346,633
<p>If you don't want to get involved with locales here is a function that formats numbers:</p> <pre><code>def int_format(value, decimal_points=3, seperator=u'.'): value = str(value) if len(value) &lt;= decimal_points: return value # say here we have value = '12345' and the default params above parts = [] while value: parts.append(value[-decimal_points:]) value = value[:-decimal_points] # now we should have parts = ['345', '12'] parts.reverse() # and the return value should be u'12.345' return seperator.join(parts) </code></pre> <p>Creating a <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters">custom template filter</a> from this function is trivial.</p>
11
2008-12-06T19:21:33Z
[ "python", "django" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
347,560
<p>Django's contributed <a href="http://docs.djangoproject.com/en/dev/ref/contrib/humanize/#ref-contrib-humanize">humanize</a> application does this:</p> <pre><code>{% load humanize %} {{ my_num|intcomma }} </code></pre> <p>Be sure to add <code>'django.contrib.humanize'</code> to your <code>INSTALLED_APPS</code> list in the <code>settings.py</code> file.</p>
162
2008-12-07T13:10:22Z
[ "python", "django" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
350,896
<p>Be aware that changing locale is process-wide and not thread safe (iow., can have side effects or can affect other code executed within the same process).</p> <p>My proposition: check out the <a href="http://babel.edgewall.org/" rel="nofollow">Babel</a> package. Some means of integrating with Django templates are available.</p>
1
2008-12-08T21:07:53Z
[ "python", "django" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
2,180,209
<p>Regarding Ned Batchelder's solution, here it is with 2 decimal points and a dollar sign.</p> <pre><code>from django.contrib.humanize.templatetags.humanize import intcomma def currency(dollars): dollars = round(float(dollars), 2) return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:]) </code></pre> <p>Then you can</p> <pre><code>{{my_dollars | currency}} </code></pre>
47
2010-02-01T21:26:44Z
[ "python", "django" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
9,015,743
<p>The <a href="http://docs.djangoproject.com/en/dev/ref/contrib/humanize/#ref-contrib-humanize" rel="nofollow">humanize app</a> offers a nice and a quick way of formatting a number but if you need to use a separator different from the comma, it's simple to just reuse <a href="https://code.djangoproject.com/browser/django/trunk/django/contrib/humanize/templatetags/humanize.py" rel="nofollow">the code from the humanize app</a>, replace the separator char, and <a href="https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters" rel="nofollow">create a custom filter</a>. For example, use <em>space</em> as a separator:</p> <pre><code>@register.filter('intspace') def intspace(value): """ Converts an integer to a string containing spaces every three digits. For example, 3000 becomes '3 000' and 45000 becomes '45 000'. See django.contrib.humanize app """ orig = force_unicode(value) new = re.sub("^(-?\d+)(\d{3})", '\g&lt;1&gt; \g&lt;2&gt;', orig) if orig == new: return new else: return intspace(new) </code></pre>
2
2012-01-26T08:57:42Z
[ "python", "django" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
10,859,264
<p>Building on other answers, to extend this to floats, you can do:</p> <pre><code>{% load humanize %} {{ floatvalue|floatformat:2|intcomma }} </code></pre>
54
2012-06-02T02:02:31Z
[ "python", "django" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
15,121,424
<p>The <a href="https://docs.djangoproject.com/en/dev/ref/contrib/humanize/">humanize</a> solution is fine if your website is in English. For other languages, you need another solution: I recommend using <a href="http://babel.edgewall.org/">Babel</a>. One solution is to create a custom template tag to display numbers properly. Here's how: just create the following file in <code>your_project/your_app/templatetags/sexify.py</code>:</p> <pre><code># -*- coding: utf-8 -*- from django import template from django.utils.translation import to_locale, get_language from babel.numbers import format_number register = template.Library() def sexy_number(context, number, locale = None): if locale is None: locale = to_locale(get_language()) return format_number(number, locale = locale) register.simple_tag(takes_context=True)(sexy_number) </code></pre> <p>Then you can use this template tag in your templates like this:</p> <pre><code>{% load sexy_number from sexify %} {% sexy_number 1234.56 %} </code></pre> <ul> <li>For an american user (locale en_US) this displays 1,234.56.</li> <li>For a french user (locale fr_FR), this displays 1 234,56.</li> <li>...</li> </ul> <p>Of course you can use variables instead:</p> <pre><code>{% sexy_number some_variable %} </code></pre> <p><strong>Note:</strong> the <code>context</code> parameter is currently not used in my example, but I put it there to show that you can easily tweak this template tag to make it use anything that's in the template context.</p>
5
2013-02-27T20:11:20Z
[ "python", "django" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
21,868,438
<p><em>Slightly off topic:</em></p> <p>I found this question while looking for a way to format a number as currency, like so:</p> <pre><code>$100 ($50) # negative numbers without '-' and in parens </code></pre> <p>I ended up doing:</p> <pre><code>{% if var &gt;= 0 %} ${{ var|stringformat:"d" }} {% elif var &lt; 0 %} $({{ var|stringformat:"d"|cut:"-" }}) {% endif %} </code></pre> <p>You could also do, e.g. <code>{{ var|stringformat:"1.2f"|cut:"-" }}</code> to display as <code>$50.00</code> (with 2 decimal places if that's what you want.</p> <p>Perhaps slightly on the hacky side, but maybe someone else will find it useful.</p>
2
2014-02-19T00:21:20Z
[ "python", "django" ]
Format numbers in django templates
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
83
2008-12-06T16:46:49Z
37,607,860
<p>Try adding the following line in settings.py:</p> <pre><code>USE_THOUSAND_SEPARATOR = True </code></pre> <p>This should work.</p> <p>Refer to <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-THOUSAND_SEPARATOR" rel="nofollow">documentation</a>.</p>
2
2016-06-03T06:56:37Z
[ "python", "django" ]
Is it more efficient to use "import <module>" or "from <module> import <func>"?
346,723
<p>Say I only needed to use findall() from the re module, is it more efficient to do:</p> <pre><code>from re import findall </code></pre> <p>or </p> <pre><code>import re </code></pre> <p>Is there actually any difference in speed/memory usage etc?</p>
3
2008-12-06T20:25:05Z
346,741
<p>There is no difference, except for what names from re are visible in you local namespace after the import.</p>
3
2008-12-06T20:35:50Z
[ "python", "import" ]
Is it more efficient to use "import <module>" or "from <module> import <func>"?
346,723
<p>Say I only needed to use findall() from the re module, is it more efficient to do:</p> <pre><code>from re import findall </code></pre> <p>or </p> <pre><code>import re </code></pre> <p>Is there actually any difference in speed/memory usage etc?</p>
3
2008-12-06T20:25:05Z
346,753
<p>There is no difference on the import, however there is a small difference on access.</p> <p>When you access the function as</p> <pre><code>re.findall() </code></pre> <p>python will need to first find the module in the global scope and then find findall in modules dict. May make a difference if you are calling it inside a loop thousands of times.</p>
10
2008-12-06T20:45:37Z
[ "python", "import" ]
Is it more efficient to use "import <module>" or "from <module> import <func>"?
346,723
<p>Say I only needed to use findall() from the re module, is it more efficient to do:</p> <pre><code>from re import findall </code></pre> <p>or </p> <pre><code>import re </code></pre> <p>Is there actually any difference in speed/memory usage etc?</p>
3
2008-12-06T20:25:05Z
346,967
<p>When in doubt, time it:</p> <pre><code>from timeit import Timer print Timer("""re.findall(r"\d+", "fg12f 1414 21af 144")""", "import re").timeit() print Timer("""findall(r"\d+", "fg12f 1414 21af 144")""", "from re import findall").timeit() </code></pre> <p>I get the following results, using the minimum of 5 repetitions of 10,000,000 calls:</p> <pre><code>re.findall(): 123.444600105 findall(): 122.056155205 </code></pre> <p>There appears to be a very slight usage advantage to using <code>findall()</code> directly, rather than <code>re.findall()</code>.</p> <p>However, the actual import statements differ in their speed by a significant amount. On my computer, I get the following results:</p> <pre><code>&gt;&gt;&gt; Timer("import re").timeit() 2.39156508446 &gt;&gt;&gt; Timer("from re import findall").timeit() 4.41387701035 </code></pre> <p>So <code>import re</code> appears to be approximately twice as fast to execute. Presumably, though, execution of the imported code is your bottleneck, rather than the actual import.</p>
8
2008-12-06T23:20:18Z
[ "python", "import" ]
Ticking function grapher
346,823
<p>I am trying to figure out the following problem. I am building Yet another math function grapher, The function is drawn on its predefined x,y range, that's all good.</p> <p>Now I am working on the background and the ticking of X, Y axes (if any axes are shown).</p> <p>I worked out the following. I have a fixed width of 250 p The tick gap should be between 12.5 and 50p.</p> <p>The ticks should indicate either unit or half unit range, by that i mean the following.</p> <p>x range (-5, 5): one tick = 1</p> <p>x range (-1, 1): one tick = 0.5 or 0.1 depending on the gap that each of this option would generate. </p> <p>x range (0.1, 0.3): 0.05 </p> <p>Given a Xrange How would you get the number of ticks between either full or half unit range ?</p> <p>Or maybe there are other way to approach this type of problems.</p>
2
2008-12-06T21:40:27Z
346,873
<p>Using deltaX</p> <p>if deltax between 2 and 10 half increment if deltax between 10 and 20 unit increment if smaller than 2 we multiply by 10 and test again if larger than 20 we divide Then we get the position of the first unit or half increment on the width using xmin.</p> <p>I still need to test this solution.</p>
0
2008-12-06T22:08:20Z
[ "python", "algorithm", "math" ]
Ticking function grapher
346,823
<p>I am trying to figure out the following problem. I am building Yet another math function grapher, The function is drawn on its predefined x,y range, that's all good.</p> <p>Now I am working on the background and the ticking of X, Y axes (if any axes are shown).</p> <p>I worked out the following. I have a fixed width of 250 p The tick gap should be between 12.5 and 50p.</p> <p>The ticks should indicate either unit or half unit range, by that i mean the following.</p> <p>x range (-5, 5): one tick = 1</p> <p>x range (-1, 1): one tick = 0.5 or 0.1 depending on the gap that each of this option would generate. </p> <p>x range (0.1, 0.3): 0.05 </p> <p>Given a Xrange How would you get the number of ticks between either full or half unit range ?</p> <p>Or maybe there are other way to approach this type of problems.</p>
2
2008-12-06T21:40:27Z
347,271
<p>One way to do this would be to "normalise" the difference between the minimum and maximum and do a case distinction on that value. In python:</p> <pre><code>delta = maximum - minimum factor = 10**math.ceil(math.log(delta,10)) # smallest power of 10 greater than delta normalised_delta = delta / factor # 0.1 &lt;= normalised_delta &lt; 1 if normalised_delta/5 &gt;= 0.1: step_size = 0.1 elif normalised_delta/5 &gt;= 0.05: step_size = 0.05 elif normalised_delta/20 &lt;= 0.01: step_size = 0.01 step_size = step_size * factor </code></pre> <p>The above code assumes you want the biggest possible gap. For the smallest you would use the following if:</p> <pre><code>if normalised_delta/20 == 0.005: step_size = 0.005 elif normalised_delta/20 &lt;= 0.01: step_size = 0.01 elif normalised_delta/5 &gt;= 0.05: step_size = 0.05 </code></pre> <p>Besides the possibility that there are more than one suitable values, there is also the somewhat worrisome possibility that there are none. Take for example the range [0,24] where a gap of 12.5p would give a step size of 1.2 and a gap of 50p would give step size 4.8. There is no "unit" or "half unit" in between. The problem is that the difference between a gap of 12.5p and one of 50p is a factor 4 while the difference between 0.01 and 0.05 is a factor 5. So you will have to widen the range of allowable gaps a bit and adjust the code accordingly.</p> <p>Clarification of some of the magic numbers: divisions by 20 and 5 correspond to the number of segments with the minimal and maximal gap size, respectively (ie. 250/12.5 and 250/50). As the normalised delta is in the range [0.1,1), you get that dividing it by 20 and 5 gives you [0.005,0.05) and [0.02,0.2), respectively. These ranges result in the possible (normalised) step sizes of 0.005 and 0.01 for the first range and 0.05 and 0.1 for the second.</p>
4
2008-12-07T05:17:48Z
[ "python", "algorithm", "math" ]
Ticking function grapher
346,823
<p>I am trying to figure out the following problem. I am building Yet another math function grapher, The function is drawn on its predefined x,y range, that's all good.</p> <p>Now I am working on the background and the ticking of X, Y axes (if any axes are shown).</p> <p>I worked out the following. I have a fixed width of 250 p The tick gap should be between 12.5 and 50p.</p> <p>The ticks should indicate either unit or half unit range, by that i mean the following.</p> <p>x range (-5, 5): one tick = 1</p> <p>x range (-1, 1): one tick = 0.5 or 0.1 depending on the gap that each of this option would generate. </p> <p>x range (0.1, 0.3): 0.05 </p> <p>Given a Xrange How would you get the number of ticks between either full or half unit range ?</p> <p>Or maybe there are other way to approach this type of problems.</p>
2
2008-12-06T21:40:27Z
347,367
<p>You might want to take a look at <a href="http://www.cs.utk.edu/~plank/plank/jgraph/jgraph.html" rel="nofollow">Jgraph</a>, which solves a complementary problem: it is a data grapher rather than a function grapher. But there are a lot of things in common such as dealing with major and minor tick marks, axis labels, and so on and so forth. I find the input language a little verbose for my taste, but Jgraph produces really nice technical graphs. There are a lot of examples on the web site and probably some good ideas you could steal. </p> <p>And you know what they say: talent imitates, but genius steals :-)</p>
0
2008-12-07T07:55:15Z
[ "python", "algorithm", "math" ]
Ticking function grapher
346,823
<p>I am trying to figure out the following problem. I am building Yet another math function grapher, The function is drawn on its predefined x,y range, that's all good.</p> <p>Now I am working on the background and the ticking of X, Y axes (if any axes are shown).</p> <p>I worked out the following. I have a fixed width of 250 p The tick gap should be between 12.5 and 50p.</p> <p>The ticks should indicate either unit or half unit range, by that i mean the following.</p> <p>x range (-5, 5): one tick = 1</p> <p>x range (-1, 1): one tick = 0.5 or 0.1 depending on the gap that each of this option would generate. </p> <p>x range (0.1, 0.3): 0.05 </p> <p>Given a Xrange How would you get the number of ticks between either full or half unit range ?</p> <p>Or maybe there are other way to approach this type of problems.</p>
2
2008-12-06T21:40:27Z
347,579
<p>This seems to do what i was expecting.</p> <p>import math</p> <p>def main(): getTickGap(-1,1.5)</p> <p>def next_multiple(x, y): return math.ceil(x/y)*y</p> <p>def getTickGap(xmin, xmax): xdelta = xmax -xmin width = 250 # smallest power of 10 greater than delta factor = 10**math.ceil(math.log(xdelta,10)) # 0.1 &lt;= normalised_delta &lt; 1 normalised_delta = xdelta / factor print("normalised_delta", normalised_delta)</p> <pre><code># we want largest gap if normalised_delta/4 &gt;= 0.1: step_size = 0.1 elif normalised_delta/4 &gt;= 0.05: step_size = 0.05 elif normalised_delta/20 &lt;= 0.01: step_size = 0.01 step_size = step_size * factor ## if normalised_delta/20 == 0.005: ## step_size = 0.005 ## elif normalised_delta/20 &lt;= 0.01: ## step_size = 0.01 ## elif normalised_delta/4 &gt;= 0.05: ## step_size = 0.05 ## step_size = step_size * factor print("step_size", step_size) totalsteps = xdelta/step_size print("Total steps", totalsteps) print("Range [", xmin, ",", xmax, "]") firstInc = next_multiple(xmin, step_size) count = (250/xdelta)*(firstInc - xmin) print("firstInc ", firstInc, 'tick at ', count) print("start at ", firstInc - xmin, (width/totalsteps)*(firstInc - xmin)) inc = firstInc while (inc &lt;xmax): inc += step_size count += (width/totalsteps) print(" inc", inc, "tick at ", count) </code></pre> <p>if <strong>name</strong> == "<strong>main</strong>": main()</p>
0
2008-12-07T13:33:36Z
[ "python", "algorithm", "math" ]
Ticking function grapher
346,823
<p>I am trying to figure out the following problem. I am building Yet another math function grapher, The function is drawn on its predefined x,y range, that's all good.</p> <p>Now I am working on the background and the ticking of X, Y axes (if any axes are shown).</p> <p>I worked out the following. I have a fixed width of 250 p The tick gap should be between 12.5 and 50p.</p> <p>The ticks should indicate either unit or half unit range, by that i mean the following.</p> <p>x range (-5, 5): one tick = 1</p> <p>x range (-1, 1): one tick = 0.5 or 0.1 depending on the gap that each of this option would generate. </p> <p>x range (0.1, 0.3): 0.05 </p> <p>Given a Xrange How would you get the number of ticks between either full or half unit range ?</p> <p>Or maybe there are other way to approach this type of problems.</p>
2
2008-12-06T21:40:27Z
347,771
<p>On range -1, 0</p> <p>i get </p> <pre><code>normalised_delta 1.0 step_size 0.1 Total steps 10.0 Range [ -1 , 0 ] firstInc -1.0 tick at 0.0 start at 0.0 0.0 inc -0.9 tick at 25.0 inc -0.8 tick at 50.0 inc -0.7 tick at 75.0 inc -0.6 tick at 100.0 inc -0.5 tick at 125.0 inc -0.4 tick at 150.0 inc -0.3 tick at 175.0 inc -0.2 tick at 200.0 inc -0.1 tick at 225.0 inc -1.38777878078e-16 tick at 250.0 inc 0.1 tick at 275.0 </code></pre> <p>How come the second line from bottom get this number ????</p>
0
2008-12-07T16:48:50Z
[ "python", "algorithm", "math" ]
Django.contrib.flatpages without models
346,840
<p>I have some flatpages with empty <code>content</code> field and their content inside the template (given with <code>template_name</code> field).</p> <h3>Why I am using <code>django.contrib.flatpages</code></h3> <ul> <li>It allows me to serve (mostly) static pages with minimal URL configuration.</li> <li>I don't have to write views for each of them.</li> </ul> <h3>Why I don't need the model <code>FlatPage</code></h3> <ul> <li>I leave the content empty and just supply a template path. Therefore I can take advantage of having the source in a file; <ul> <li>I can edit the source directly from the file system, without the help of a server (such as admin).</li> <li>I can take advantage of syntax highlightning and other editor features.</li> </ul></li> <li>With the model I have to maintain fixtures for flatpages. <ul> <li>So the data for the same entity is in two seperate places.</li> <li>If I move the content inside the fixture it'll be more difficult to edit. <ul> <li>Even if fixture maintenance was a non-issue I'd still need to dump and load these fixtures again and again during development.</li> </ul></li> </ul></li> </ul> <h3>What I am looking for</h3> <p>Basically; getting rid of <code>FlatPage</code> model while maintaining <code>contrib.flatpages</code> functionality. I don't have a clear idea how this should be solved. If there's a clean way of modifying (like <code>add_to_class</code>) <code>FlatPages</code> to get the information somewhere other than the database I'd prefer that. Maybe the metadata can be inserted to the templates and then a special manager that reads this data would replace the default manager of <code>FlatPages</code>.</p> <p>If I don't prefer manual editing over admin functionality for flatpages, how can take the database out of the equation?</p>
6
2008-12-06T21:48:55Z
346,877
<p>Using the <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-simple-direct-to-template" rel="nofollow"><code>direct_to_template</code></a> generic view would be a lot simpler. You could use the passed in parameters on one view to specify the actual template in urls.py, if you don't want to add an entry for each page:</p> <pre><code>r'^foo/(?P&lt;template_name&gt;.+)/$','direct_to_template', {'template': 'foo_index.html'}), </code></pre> <p>Then import the template in your <code>foo_index.html</code>:</p> <pre><code>{% include template_name %} </code></pre>
9
2008-12-06T22:08:59Z
[ "python", "django", "templates", "django-flatpages" ]
Questions for python->scheme conversion
347,010
<p>I currently am trying to write a Python program using scheme semantics so I can later translate it into Scheme without relying on a lot of Pythonic stuff.</p> <p>I'm trying solve the sliding puzzle problem (where you have 9 slots and 8 tiles arranged in a square) using a*, depth first, and breadth first search algorithm. I did this ~11 years ago in some AI class in Lisp, but basically at the time I had no idea about lisp, I hated it with all my heart, and only in retrospect do I realize I was programming "C" in Lisp. The prof didn't help in this matter.</p> <p>I have a python function which can swap two tiles easily: </p> <pre><code>def swap(p, (r1, c1), (r2, c2)): # Swaps *any* two locations and returns new configuration # Does not concern itself with zero location, etc # Not sure how to do this functionally p_p = p[:] temp = p_p[r1][c1] p_p[r1][c1] = p_p[r2][c2] p_p[r2][c2] = temp return p_p </code></pre> <p>I'd like to turn this into something you might find in SICP, avoiding side effects, etc. </p> <p>But this brings up a question. Everything I read in SICP is loops via recursion. I didn't see anything in accessing arrays/vectors/lists in constant time. I can imagine a loopish/recursive way to read an element, but I find it harder to imagine a way to create a new list with a certain element changed, without invoking side-effect producing things like set!, and without resorting to crazy if/then/else clauses concerning which element should be changed. This of course gets more confusing when considering a 2d array. In this case the solution with python is obvious because of its native support for multidimensional arrays.</p> <p>In C/C++/Python/Matlab/Lua/anything else, accessing lists/arrays via the [i] syntax is easy, and directly translates to a hardware-oriented pointer lookup somewhere underneath. I don't understand how scheme does this, given the atomic operations defined in the SICP version of scheme, which all seem very loop-and-search oriented. How do the vector and list array access functions work to get constant time access? (I'm a total newbie here, so I'm not ever sure what functions I'd be talking about). Is there a C or Assembly library someplace which is secretly being accessed? Are there any inherent constant-time semantics in scheme which could be used for list/array/vector access, and which would allow me a guilt-free way of using that idiom in Python for the moment? </p> <p>How would can I rewrite the above function in python using Schemish semantics? How would I rewrite the above function in Scheme?</p>
4
2008-12-06T23:58:08Z
347,059
<p>I wrote an 8-puzzle solver in Lisp about a year ago. I just used a list of 3 lists, each sublist with 3 elements being the numbers. It's not constant time, but it is portable.</p> <p>Anyways, if you are really interested in doing this functionally (Scheme doesn't require you to) what is easiest to do is to create some helper functions that will get a specific value given row/col and 'set' a value given row/col. Instead of modifying the original data structure, the set operation will construct the new state based on the old state.</p> <p>Then you can write a swap operation based on these get and set operations. Here's what I wrote about a year ago in Common Lisp, but it's easily convertible to Scheme:</p> <pre><code>; getval ; ; This function takes a position (r . c) where and returns the corresponding ; number in the 8-puzzle state. For example, if you wanted (1 . 2) from ; ((1 2 3) (4 5 6) (7 8 9)), the value would be 6. The r and c values begin ; at 0. ; ; parameters: pos The position to get ; state The 8-puzzle state ; returns: The value at pos in state (defun getval (pos state) (if (null state) 'no-value (if (= 0 (car pos)) (if (= 0 (cdr pos)) (caar state) (getval (cons (car pos) (- (cdr pos) 1)) (list (cdar state)))) (getval (cons (- (car pos) 1) (cdr pos)) (cdr state))))) ; setval ; ; This function returns a state where the value at pos is replaced by val. ; Like getval, this function is zero-based. Accessing beyond the size of ; the state is undefined (and probably broken) ; ; parameters: pos Position to set ; val Value to set ; state State to modify ; returns: New state where pos is val (defun setval (pos val state) (if (null state) '() (if (= 0 (car pos)) (if (= 0 (cdr pos)) (cons (cons val (cdar state)) (cdr state)) (let ((temp (setval (cons (car pos) (- (cdr pos) 1)) val (cons (cdar state) (cdr state))))) (cons (cons (caar state) (car temp)) (cdr temp)))) (cons (car state) (setval (cons (- (car pos) 1) (cdr pos)) val (cdr state)))))) ; state-swap ; ; This function takes a state and two positions and returns a new state with ; the values in those two positions swapped. ; ; parameters: state State to swap within ; a Position to swap with b ; b Position to swap with a ; return: State with a swapped with b (defun state-swap (state a b) (let ((olda (getval a state)) (oldb (getval b state))) (setval a oldb (setval b olda state)))) </code></pre>
2
2008-12-07T00:56:32Z
[ "python", "arrays", "scheme" ]
Questions for python->scheme conversion
347,010
<p>I currently am trying to write a Python program using scheme semantics so I can later translate it into Scheme without relying on a lot of Pythonic stuff.</p> <p>I'm trying solve the sliding puzzle problem (where you have 9 slots and 8 tiles arranged in a square) using a*, depth first, and breadth first search algorithm. I did this ~11 years ago in some AI class in Lisp, but basically at the time I had no idea about lisp, I hated it with all my heart, and only in retrospect do I realize I was programming "C" in Lisp. The prof didn't help in this matter.</p> <p>I have a python function which can swap two tiles easily: </p> <pre><code>def swap(p, (r1, c1), (r2, c2)): # Swaps *any* two locations and returns new configuration # Does not concern itself with zero location, etc # Not sure how to do this functionally p_p = p[:] temp = p_p[r1][c1] p_p[r1][c1] = p_p[r2][c2] p_p[r2][c2] = temp return p_p </code></pre> <p>I'd like to turn this into something you might find in SICP, avoiding side effects, etc. </p> <p>But this brings up a question. Everything I read in SICP is loops via recursion. I didn't see anything in accessing arrays/vectors/lists in constant time. I can imagine a loopish/recursive way to read an element, but I find it harder to imagine a way to create a new list with a certain element changed, without invoking side-effect producing things like set!, and without resorting to crazy if/then/else clauses concerning which element should be changed. This of course gets more confusing when considering a 2d array. In this case the solution with python is obvious because of its native support for multidimensional arrays.</p> <p>In C/C++/Python/Matlab/Lua/anything else, accessing lists/arrays via the [i] syntax is easy, and directly translates to a hardware-oriented pointer lookup somewhere underneath. I don't understand how scheme does this, given the atomic operations defined in the SICP version of scheme, which all seem very loop-and-search oriented. How do the vector and list array access functions work to get constant time access? (I'm a total newbie here, so I'm not ever sure what functions I'd be talking about). Is there a C or Assembly library someplace which is secretly being accessed? Are there any inherent constant-time semantics in scheme which could be used for list/array/vector access, and which would allow me a guilt-free way of using that idiom in Python for the moment? </p> <p>How would can I rewrite the above function in python using Schemish semantics? How would I rewrite the above function in Scheme?</p>
4
2008-12-06T23:58:08Z
347,181
<p>You identified that your initial problem was trying to write C semantics in Lisp. Is it not repeating the mistake to try to write scheme semantics in python? I always try to learn language X as a paradigm as much as a language and write in the most x-ish way.</p> <p>It might be justifiable if this was a business app you knew was going to be migrated, but otherwise I'd just write it in scheme to begin with.</p>
4
2008-12-07T03:25:05Z
[ "python", "arrays", "scheme" ]
Questions for python->scheme conversion
347,010
<p>I currently am trying to write a Python program using scheme semantics so I can later translate it into Scheme without relying on a lot of Pythonic stuff.</p> <p>I'm trying solve the sliding puzzle problem (where you have 9 slots and 8 tiles arranged in a square) using a*, depth first, and breadth first search algorithm. I did this ~11 years ago in some AI class in Lisp, but basically at the time I had no idea about lisp, I hated it with all my heart, and only in retrospect do I realize I was programming "C" in Lisp. The prof didn't help in this matter.</p> <p>I have a python function which can swap two tiles easily: </p> <pre><code>def swap(p, (r1, c1), (r2, c2)): # Swaps *any* two locations and returns new configuration # Does not concern itself with zero location, etc # Not sure how to do this functionally p_p = p[:] temp = p_p[r1][c1] p_p[r1][c1] = p_p[r2][c2] p_p[r2][c2] = temp return p_p </code></pre> <p>I'd like to turn this into something you might find in SICP, avoiding side effects, etc. </p> <p>But this brings up a question. Everything I read in SICP is loops via recursion. I didn't see anything in accessing arrays/vectors/lists in constant time. I can imagine a loopish/recursive way to read an element, but I find it harder to imagine a way to create a new list with a certain element changed, without invoking side-effect producing things like set!, and without resorting to crazy if/then/else clauses concerning which element should be changed. This of course gets more confusing when considering a 2d array. In this case the solution with python is obvious because of its native support for multidimensional arrays.</p> <p>In C/C++/Python/Matlab/Lua/anything else, accessing lists/arrays via the [i] syntax is easy, and directly translates to a hardware-oriented pointer lookup somewhere underneath. I don't understand how scheme does this, given the atomic operations defined in the SICP version of scheme, which all seem very loop-and-search oriented. How do the vector and list array access functions work to get constant time access? (I'm a total newbie here, so I'm not ever sure what functions I'd be talking about). Is there a C or Assembly library someplace which is secretly being accessed? Are there any inherent constant-time semantics in scheme which could be used for list/array/vector access, and which would allow me a guilt-free way of using that idiom in Python for the moment? </p> <p>How would can I rewrite the above function in python using Schemish semantics? How would I rewrite the above function in Scheme?</p>
4
2008-12-06T23:58:08Z
347,357
<p>Cool, thanks for the lisp code. I'll need to study it to make sure I get it.</p> <p>As for the first answer, the first time I was "writing c" in lisp because that's the only way I knew how to program and didn't have a clue why anyone would use lisp. This time around, I've been playing around with scheme, but wanted to use python so if I got stuck on something I could "cheat" and use something pythonish, then while waiting for usenet answers go on to the next part of the problem.</p>
0
2008-12-07T07:40:26Z
[ "python", "arrays", "scheme" ]
Questions for python->scheme conversion
347,010
<p>I currently am trying to write a Python program using scheme semantics so I can later translate it into Scheme without relying on a lot of Pythonic stuff.</p> <p>I'm trying solve the sliding puzzle problem (where you have 9 slots and 8 tiles arranged in a square) using a*, depth first, and breadth first search algorithm. I did this ~11 years ago in some AI class in Lisp, but basically at the time I had no idea about lisp, I hated it with all my heart, and only in retrospect do I realize I was programming "C" in Lisp. The prof didn't help in this matter.</p> <p>I have a python function which can swap two tiles easily: </p> <pre><code>def swap(p, (r1, c1), (r2, c2)): # Swaps *any* two locations and returns new configuration # Does not concern itself with zero location, etc # Not sure how to do this functionally p_p = p[:] temp = p_p[r1][c1] p_p[r1][c1] = p_p[r2][c2] p_p[r2][c2] = temp return p_p </code></pre> <p>I'd like to turn this into something you might find in SICP, avoiding side effects, etc. </p> <p>But this brings up a question. Everything I read in SICP is loops via recursion. I didn't see anything in accessing arrays/vectors/lists in constant time. I can imagine a loopish/recursive way to read an element, but I find it harder to imagine a way to create a new list with a certain element changed, without invoking side-effect producing things like set!, and without resorting to crazy if/then/else clauses concerning which element should be changed. This of course gets more confusing when considering a 2d array. In this case the solution with python is obvious because of its native support for multidimensional arrays.</p> <p>In C/C++/Python/Matlab/Lua/anything else, accessing lists/arrays via the [i] syntax is easy, and directly translates to a hardware-oriented pointer lookup somewhere underneath. I don't understand how scheme does this, given the atomic operations defined in the SICP version of scheme, which all seem very loop-and-search oriented. How do the vector and list array access functions work to get constant time access? (I'm a total newbie here, so I'm not ever sure what functions I'd be talking about). Is there a C or Assembly library someplace which is secretly being accessed? Are there any inherent constant-time semantics in scheme which could be used for list/array/vector access, and which would allow me a guilt-free way of using that idiom in Python for the moment? </p> <p>How would can I rewrite the above function in python using Schemish semantics? How would I rewrite the above function in Scheme?</p>
4
2008-12-06T23:58:08Z
348,367
<p>Here's one way to achieve it. Recreate the list using a function which will apply the appropriate mapping.</p> <pre><code>def swap(p, (r1,c1), (r2,c2)): def getitem(r,c): if (r,c) == (r1,c1): return p[r2][c2] elif (r,c) == (r2,c2): return p[r1][c1] return p[r][c] return [ [getitem(r,c) for c in range(len(p[0]))] for r in range(len(p)) ] </code></pre> <p>You could even take this a step further and make the function be the actual interface, where each swap merely returns a function that does the appropriate conversions before passing through to the function below. Not particularly performant, but a fairly simple functional approach that dispenses with nasty mutable datastructures:</p> <pre><code>def swap(f, (r1,c1), (r2,c2)): def getitem(r,c): if (r,c) == (r1,c1): return f(r2,c2) elif (r,c) == (r2,c2): return f(r1,c1) return f(r,c) return getitem l=[ [1,2,3], [4,5,6], [7,8,0]] f=lambda r,c: l[r][c] # Initial accessor function f=swap(f, (2,1), (2,2)) # 8 right f=swap(f, (1,1), (2,1)) # 5 down print [[f(x,y) for y in range(3)] for x in range(3)] # Gives: [[1, 2, 3], [4, 0, 6], [7, 5, 8]] </code></pre>
1
2008-12-07T23:59:49Z
[ "python", "arrays", "scheme" ]
Where do I go from here -- regarding programming?
347,054
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
3
2008-12-07T00:49:52Z
347,065
<p>You will only have a first language for a little while. Pick any direction that interests you, and follow it. There is no way around the introduction "Drink from the Firehose" experience.</p> <p>Keep early project simple, and tangible. Build useful things and the motivation will be there.</p> <p>Web / desktop / mobile / etc, its all good. Find the one that gets you thinking about code when your not coding, and you'll know your going in the right direction.</p>
7
2008-12-07T00:58:04Z
[ "php", "asp.net", "python", "linux" ]
Where do I go from here -- regarding programming?
347,054
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
3
2008-12-07T00:49:52Z
347,066
<blockquote> <blockquote> <p>The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> </blockquote> </blockquote> <p>This is exactly the course to follow. I think most of us get into programming the same way. Find a problem and work out its solution in whatever technology is appropriate. Keep looking for problems that are interesting to you, and you'll find your own answer (which is probably different than my own answer) to this question.</p>
2
2008-12-07T00:58:23Z
[ "php", "asp.net", "python", "linux" ]
Where do I go from here -- regarding programming?
347,054
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
3
2008-12-07T00:49:52Z
347,074
<p>One of pragmatic programmer's advice is to learn a new language per year. Possibly, a completely different one each time (see <a href="http://martinfowler.com/bliki/OneLanguage.html" rel="nofollow">Martin Fowler's opinion</a> on this matter).</p> <p>Back to your specifics, you have chosen the way of programming because you enjoyed it (I hope :-)); if you are not satisfied by your current environment, go and change it.</p>
2
2008-12-07T01:03:37Z
[ "php", "asp.net", "python", "linux" ]
Where do I go from here -- regarding programming?
347,054
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
3
2008-12-07T00:49:52Z
347,076
<p>Don't worry so much about the direction you're going, just make sure that:</p> <p>a) You are enjoying it, and are understanding what you are doing. You don't have to initially understand concepts like polymorphism for example, but you should be understanding the basics of what you are doing. Just can't wrap your mind around Tuples and Dictionaries in Python after awhile? Then it's probably not for you. Of course, that's a very low level example as if you don't get Dictionaries, then there's a problem in general :-)</p> <p>b) You are working on things that you want to solve, not just because you think you NEED to learn this. You used the phrase "Windows is a necessary evil" No, it isn't. Many companies (big and small) do not use the .NET platform for development. Your approach to Linux was interesting as you could not achieve something you wanted on it and your result was "it's clunky" which seems kind of awkward.</p> <p>Either way, this isn't about Linux vs. Windows, but I hope that helps. Just go with the flow, and don't worry about what way you're going as long as you're enjoying and learning! :)</p>
0
2008-12-07T01:09:04Z
[ "php", "asp.net", "python", "linux" ]
Where do I go from here -- regarding programming?
347,054
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
3
2008-12-07T00:49:52Z
347,120
<p>I find some of my junior colleagues (atleast the ones that are very passionate about CS) asking similar questions (sometimes I find myself asking this too, even though I am now 12+ yrs into the industry). One advice I give them (and to myself too), which helped me, is - </p> <ul> <li><p>Focus on the job that is already assigned to you. As part of that task, make sure you dont just "get the job done", but also make sure that you understand the fundamentals behind the same. If you want to be a good programmer, you need to understand the underlying principles of "how things work". Using an API to do matrix multiplication is easy, but if you dont really know what is matrix multiplication and how to do it by hand, you are actually losing out. So in your chosen web programming domain, make sure you go beyond the surface. Understand what is really happening behind your back, when you click that button.</p></li> <li><p>As part of "doing the job" you typically can figure out what is your interest area. If you are more passionate about how things are implemented, and keep figuring it out, then you are, IMO, a systems guy. If you are more passionate about finding out all the new tools and the newer features and seem to be keen in putting things together to create newer and cooler outputs, then you are an application programmer. Both are interesting areas in their own ways and as people adviced above, realize what you like and see if you can stick with it.</p></li> <li><p>And I like one of the advices above. If you are still confused, try doing this "rotation" thingie. There are lots of scope in just about every domain/field and so keep rotating (but give each rotation due time), until you find what you like.</p></li> </ul> <p>All the best.</p> <p>:-)</p>
0
2008-12-07T02:13:31Z
[ "php", "asp.net", "python", "linux" ]
Where do I go from here -- regarding programming?
347,054
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
3
2008-12-07T00:49:52Z
347,121
<p>Thanks for the thoughtful responses</p> <p>That seemed to be another distraction from learning programming for me anyway. I spent more time chasing apparent fixes for upgraded packages and such. Mostly things that were already working and it just seemed to not make much sense to spend time recreating the wheel so to speak. Believe me the jury is still out for ma as to whether it makes good sense to chase the dream of Linux as a real alternative to a usable desktop. Now remember ex-Windows users will always have to compare their experience with Linux to how they were previously able to work before trying Windows.</p> <p>Just my two cents </p>
0
2008-12-07T02:13:51Z
[ "php", "asp.net", "python", "linux" ]
Where do I go from here -- regarding programming?
347,054
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
3
2008-12-07T00:49:52Z
347,129
<p>This is a ruff business. Technology churn keeps everyone busy and workers who want to excel at their craft can become constantly busy in a sea of new technology. But, in the end all of these technologies follow the same patterns and practices to one degree or another. Becoming an expert in the fundamentals will go a long way to forwarding a career in this business. The <a href="http://rads.stackoverflow.com/amzn/click/020161622X" rel="nofollow">Pragamatic Programmer</a> is a classic source for direction. </p> <p>Also, what you can or should do (Windows vs. Linux) may depend greatly on Geography. I follow the job market in my area. Spend a little time finding out what business are looking for and what contractors are doing and choose technologies to learn based on this information. User groups, conferences, and code camps are also a good source. </p> <p>If the real problem here is that you are on your own building your first web app and find what you see on channel 9 is more compelling then maybe you should follow your instincts! BTW, I think you will find "clunkiness" everywhere, might as well get used to it.</p>
0
2008-12-07T02:22:41Z
[ "php", "asp.net", "python", "linux" ]
Where do I go from here -- regarding programming?
347,054
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
3
2008-12-07T00:49:52Z
347,348
<p>Really all you need to do is make sure you take baby steps and are doing something you are enjoying.</p> <p>I started off programming in visual basic on a little game. Not the best language, but it was a good starting point for me at the time. My point is, you don't need to pick the best language/operating system/anything from the start, just iterate. It is the programming way.</p> <p>By the way, just because you use windows as your OS doesn't mean you have to do everything .NET I use windows and then have a server for all my web hosting that I SSH into.</p>
0
2008-12-07T07:20:41Z
[ "php", "asp.net", "python", "linux" ]
Where do I go from here -- regarding programming?
347,054
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
3
2008-12-07T00:49:52Z
347,353
<p>I had the same issue for a little while myself. I was getting bored of just being in PHP and wanted to be able to do more. I ended up settling on C# since it not only fulfilled the 'necessary evil' argument, but allows me to do anything I want in the MS realm, and is the closest syntax wise to another language (Java).</p> <p>Thinking about all the different types of projects this opened me up to made me choose this direction. Both languages can be used for web development, mobile devices, and desktop applications.</p>
0
2008-12-07T07:27:35Z
[ "php", "asp.net", "python", "linux" ]
How do I concisely implement multiple similar unit tests in the Python unittest framework?
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
14
2008-12-07T01:59:49Z
347,175
<p>You could use a metaclass to dynamically insert the tests. This works fine for me:</p> <pre><code>import unittest class UnderTest(object): def f1(self, i): return i + 1 def f2(self, i): return i + 2 class TestMeta(type): def __new__(cls, name, bases, attrs): funcs = [t for t in dir(UnderTest) if t[0] == 'f'] def doTest(t): def f(slf): ut=UnderTest() getattr(ut, t)(3) return f for f in funcs: attrs['test_gen_' + f] = doTest(f) return type.__new__(cls, name, bases, attrs) class T(unittest.TestCase): __metaclass__ = TestMeta def testOne(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() </code></pre>
4
2008-12-07T03:17:47Z
[ "python", "unit-testing" ]
How do I concisely implement multiple similar unit tests in the Python unittest framework?
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
14
2008-12-07T01:59:49Z
347,499
<p>Metaclasses is one option. Another option is to use a <code>TestSuite</code>:</p> <pre><code>import unittest import numpy import funcs # get references to functions # only the functions and if their names start with "matrixOp" functions_to_test = [v for k,v in funcs.__dict__ if v.func_name.startswith('matrixOp')] # suplly an optional setup function def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) # create tests from functions directly and store those TestCases in a TestSuite test_suite = unittest.TestSuite([unittest.FunctionTestCase(f, setUp=setUp) for f in functions_to_test]) if __name__ == "__main__": unittest.main() </code></pre> <p>Haven't tested. But it should work fine.</p>
1
2008-12-07T11:43:39Z
[ "python", "unit-testing" ]
How do I concisely implement multiple similar unit tests in the Python unittest framework?
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
14
2008-12-07T01:59:49Z
347,607
<p>Here's my favorite approach to the "family of related tests". I like explicit subclasses of a TestCase that expresses the common features.</p> <pre><code>class MyTestF1( unittest.TestCase ): theFunction= staticmethod( f1 ) def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape( self ): """Output of functions be of a certain shape""" output = self.theFunction(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % (self.theFunction.__name__,) self.assertEqual(self.matrix1.shape, output.shape, fail_message) class TestF2( MyTestF1 ): """Includes ALL of TestF1 tests, plus a new test.""" theFunction= staticmethod( f2 ) def testUniqueFeature( self ): # blah blah blah pass class TestF3( MyTestF1 ): """Includes ALL of TestF1 tests with no additional code.""" theFunction= staticmethod( f3 ) </code></pre> <p>Add a function, add a subclass of <code>MyTestF1</code>. Each subclass of MyTestF1 includes all of the tests in MyTestF1 with no duplicated code of any kind.</p> <p>Unique features are handled in an obvious way. New methods are added to the subclass.</p> <p>It's completely compatible with <code>unittest.main()</code></p>
11
2008-12-07T14:07:12Z
[ "python", "unit-testing" ]
How do I concisely implement multiple similar unit tests in the Python unittest framework?
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
14
2008-12-07T01:59:49Z
373,107
<blockquote> <p>The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> </blockquote> <p>If you look at it from the point of view that, if a test fails, that is critical and your entire package is invalid, then it doesn't matter that other elements won't get tested, because 'hey, you have an error to fix'.</p> <p>Once that test passes, the other tests will then run.</p> <p>Admittedly there is information to be gained from knowledge of which other tests are failing, and that can help with debugging, but apart from that, assume any test failure is an entire application failure.</p>
-1
2008-12-16T23:13:24Z
[ "python", "unit-testing" ]
How do I concisely implement multiple similar unit tests in the Python unittest framework?
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
14
2008-12-07T01:59:49Z
373,625
<p>If you're already using nose (and some of your comments suggest you are), why don't you just use <a href="http://somethingaboutorange.com/mrl/projects/nose/#test-generators">Test Generators</a>, which are the most straightforward way to implement parametric tests I've come across:</p> <p>For example:</p> <pre><code>from binary_search import search1 as search def test_binary_search(): data = ( (-1, 3, []), (-1, 3, [1]), (0, 1, [1]), (0, 1, [1, 3, 5]), (1, 3, [1, 3, 5]), (2, 5, [1, 3, 5]), (-1, 0, [1, 3, 5]), (-1, 2, [1, 3, 5]), (-1, 4, [1, 3, 5]), (-1, 6, [1, 3, 5]), (0, 1, [1, 3, 5, 7]), (1, 3, [1, 3, 5, 7]), (2, 5, [1, 3, 5, 7]), (3, 7, [1, 3, 5, 7]), (-1, 0, [1, 3, 5, 7]), (-1, 2, [1, 3, 5, 7]), (-1, 4, [1, 3, 5, 7]), (-1, 6, [1, 3, 5, 7]), (-1, 8, [1, 3, 5, 7]), ) for result, n, ns in data: yield check_binary_search, result, n, ns def check_binary_search(expected, n, ns): actual = search(n, ns) assert expected == actual </code></pre> <p>Produces:</p> <pre><code>$ nosetests -d ................... ---------------------------------------------------------------------- Ran 19 tests in 0.009s OK </code></pre>
5
2008-12-17T04:05:43Z
[ "python", "unit-testing" ]
How do I concisely implement multiple similar unit tests in the Python unittest framework?
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
14
2008-12-07T01:59:49Z
1,320,299
<p>The above metaclass code has trouble with nose because nose's wantMethod in its selector.py is looking at a given test method's <code>__name__</code>, not the attribute dict key.</p> <p>To use a metaclass defined test method with nose, the method name and dictionary key must be the same, and prefixed to be detected by nose (ie with 'test_').</p> <pre><code># test class that uses a metaclass class TCType(type): def __new__(cls, name, bases, dct): def generate_test_method(): def test_method(self): pass return test_method dct['test_method'] = generate_test_method() return type.__new__(cls, name, bases, dct) class TestMetaclassed(object): __metaclass__ = TCType def test_one(self): pass def test_two(self): pass </code></pre>
1
2009-08-24T02:59:01Z
[ "python", "unit-testing" ]
How do I concisely implement multiple similar unit tests in the Python unittest framework?
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
14
2008-12-07T01:59:49Z
1,974,927
<p>You don't have to use Meta Classes here. A simple loop fits just fine. Take a look at the example below:</p> <pre><code>import unittest class TestCase1(unittest.TestCase): def check_something(self, param1): self.assertTrue(param1) def _add_test(name, param1): def test_method(self): self.check_something(param1) setattr(TestCase1, 'test_'+name, test_method) test_method.__name__ = 'test_'+name for i in range(0, 3): _add_test(str(i), False) </code></pre> <p>Once the for is executed the TestCase1 has 3 test methods that are supported by both the nose and the unittest.</p>
5
2009-12-29T14:37:07Z
[ "python", "unit-testing" ]
How do I concisely implement multiple similar unit tests in the Python unittest framework?
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
14
2008-12-07T01:59:49Z
5,026,270
<p>I've read the above metaclass example, and I liked it, but it was missing two things:</p> <ol> <li>How to drive it with a data structure?</li> <li>How to make sure that the test function is written correctly?</li> </ol> <p>I wrote this more complete example, which is data-driven, and in which the test function is itself unit-tested.</p> <pre><code>import unittest TEST_DATA = ( (0, 1), (1, 2), (2, 3), (3, 5), # This intentionally written to fail ) class Foo(object): def f(self, n): return n + 1 class FooTestBase(object): """Base class, defines a function which performs assertions. It defines a value-driven check, which is written as a typical function, and can be tested. """ def setUp(self): self.obj = Foo() def value_driven_test(self, number, expected): self.assertEquals(expected, self.obj.f(number)) class FooTestBaseTest(unittest.TestCase): """FooTestBase has a potentially complicated, data-driven function. It needs to be tested. """ class FooTestExample(FooTestBase, unittest.TestCase): def runTest(self): return self.value_driven_test def test_value_driven_test_pass(self): test_base = self.FooTestExample() test_base.setUp() test_base.value_driven_test(1, 2) def test_value_driven_test_fail(self): test_base = self.FooTestExample() test_base.setUp() self.assertRaises( AssertionError, test_base.value_driven_test, 1, 3) class DynamicTestMethodGenerator(type): """Class responsible for generating dynamic test functions. It only wraps parameters for specific calls of value_driven_test. It could be called a form of currying. """ def __new__(cls, name, bases, dct): def generate_test_method(number, expected): def test_method(self): self.value_driven_test(number, expected) return test_method for number, expected in TEST_DATA: method_name = "testNumbers_%s_and_%s" % (number, expected) dct[method_name] = generate_test_method(number, expected) return type.__new__(cls, name, bases, dct) class FooUnitTest(FooTestBase, unittest.TestCase): """Combines generated and hand-written functions.""" __metaclass__ = DynamicTestMethodGenerator if __name__ == '__main__': unittest.main() </code></pre> <p>When running the above example, if there's a bug in the code (or wrong test data), the error message will contain function name, which should help in debugging.</p> <pre><code>.....F ====================================================================== FAIL: testNumbers_3_and_5 (__main__.FooUnitTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "dyn_unittest.py", line 65, in test_method self.value_driven_test(number, expected) File "dyn_unittest.py", line 30, in value_driven_test self.assertEquals(expected, self.obj.f(number)) AssertionError: 5 != 4 ---------------------------------------------------------------------- Ran 6 tests in 0.002s FAILED (failures=1) </code></pre>
0
2011-02-17T07:42:46Z
[ "python", "unit-testing" ]
How do I concisely implement multiple similar unit tests in the Python unittest framework?
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
14
2008-12-07T01:59:49Z
30,290,106
<p>I see that this question is old. I'm not sure about back then, but today maybe you could use some "data-driven testing" packages:</p> <ul> <li><a href="https://github.com/wolever/nose-parameterized" rel="nofollow">https://github.com/wolever/nose-parameterized</a></li> <li><a href="http://ddt.readthedocs.org/en/latest/example.html" rel="nofollow">http://ddt.readthedocs.org/en/latest/example.html</a></li> </ul>
2
2015-05-17T17:51:22Z
[ "python", "unit-testing" ]
Can I use Python to intercept global keystrokes in KDE?
347,475
<p>I want to make a simple app, ideally in Python, that would run in the background on KDE, listening to all keystrokes being done by the user, so that the app goes to the foreground if a specific combination of keys is pressed. Is that doable? Can anyone point me to such resource?</p>
0
2008-12-07T11:03:17Z
348,676
<p>A quick google found this:</p> <p><a href="http://sourceforge.net/projects/pykeylogger/" rel="nofollow">http://sourceforge.net/projects/pykeylogger/</a></p> <p>You might be able to use some of the source code.</p>
1
2008-12-08T04:50:24Z
[ "python", "kde" ]
Emitting headers from a tiny Python web-framework
347,497
<p>I am writing a web-framework for Python, of which the goal is to be as "small" as possible (currently under 100 lines of code).. You can see the current code <a href="http://github.com/dbr/pyerweb/tree/master" rel="nofollow">on github</a></p> <p>Basically it's written to be as simple to use as possible. An example "Hello World" like site:</p> <pre><code>from pyerweb import GET, runner @GET("/") def index(): return "&lt;strong&gt;This&lt;/strong&gt; would be the output HTML for the URL / " @GET("/view/([0-9]+?)$") def view_something(id): return "Viewing id %s" % (id) # URL /view/123 would output "Viewing id 123" runner(url = "/", # url would be from a web server, in actual use output_helper = "html_tidy" # run returned HTML though "HTML tidy" </code></pre> <p>Basically you have a function that returns HTML, and the GET decorator maps this to a URL.</p> <p>When <code>runner()</code> is called, each decorated function is checked, if the URL regex matches the request URL, the function is run, and the output is sent to the browser.</p> <p>Now, the problem - outputting headers. Currently for development I've just put a line before the <code>runner()</code> call which does <code>print Content-type:text/html\n</code> - this is obviously a bit limiting..</p> <p>My first ideas was to have the functions return a dict, something like..</p> <pre><code>@GET("/") def index(): return { "html": "&lt;html&gt;&lt;body&gt;...&lt;/body&gt;&lt;/html&gt;", "headers": {"Location":"http://google.com"} } </code></pre> <p>I really don't like this - having to return a dict with a specifically named key isn't nearly as nice as just returning a string..</p> <p>I could check if the returned data is a dict, if so use <code>returned_data['html']</code> as the output, if it's a string, there is no custom headers to be sent... but this means to go from no headers (which would be the case a huge majority of the time) to headers, you'd have to change the return function from <code>return my_html</code> to <code>return {'html':my_html}</code> which isn't very elegant either..</p> <p>After writing this, I discovered "Sinatra" - a similar-in-use Ruby library, and looked at how it dealt with headers:</p> <pre><code>get "/" do content_type 'text/css', :charset =&gt; 'utf-8' end </code></pre> <p>This seems like it could be nice enough in Python:</p> <pre><code>@GET("/") def index(): header("location", "http://google.com") </code></pre> <p>To implement this, I was considering changing how the functions are executed - instead of simply using the return value, I would change <code>sys.stdout</code> to a StringIO, so you could do..</p> <pre><code>def index(): print "&lt;html&gt;" print "&lt;head&gt;&lt;title&gt;Something&lt;/title&gt;&lt;/head&gt;" print "&lt;body&gt;...&lt;/body&gt;" print "&lt;/html&gt; </code></pre> <p>..without having to worry about concatenating a bunch of strings together. The upshot of this is I could have a separate stream for headers, so the above <code>header()</code> function would write to this.. Something like:</p> <pre><code>def header(name, value): pyerweb.header_stream.write("%s: %s" % (name, value)) </code></pre> <p>Basically, the question is, how would you output headers from this web-framework (mostly in terms of <em>use</em>, but to a lesser extent implementation)?</p>
3
2008-12-07T11:41:34Z
347,509
<p>You should reconsider the notion of returning <a href="http://en.wikipedia.org/wiki/Html" rel="nofollow">HTML</a> - headers are part of <a href="http://en.wikipedia.org/wiki/Http" rel="nofollow">HTTP</a>. If you build your framework around an HTTP stream, the headers are simply lines that precede the HTML payload.</p> <p>A headers example from the above link:</p> <pre><code>HTTP/1.1 200 OK Date: Mon, 23 May 2005 22:38:34 GMT Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux) Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT Etag: "3f80f-1b6-3e1cb03b" Accept-Ranges: bytes Content-Length: 438 Connection: close Content-Type: text/html; charset=UTF-8 </code></pre> <p>For a Python example, see the implementaion of <a href="http://docs.python.org/library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.send_header" rel="nofollow"><code>BaseHTTPRequestHandler.send_header(keyword, value</code>)</a>.</p>
1
2008-12-07T12:04:44Z
[ "python", "frameworks" ]
Emitting headers from a tiny Python web-framework
347,497
<p>I am writing a web-framework for Python, of which the goal is to be as "small" as possible (currently under 100 lines of code).. You can see the current code <a href="http://github.com/dbr/pyerweb/tree/master" rel="nofollow">on github</a></p> <p>Basically it's written to be as simple to use as possible. An example "Hello World" like site:</p> <pre><code>from pyerweb import GET, runner @GET("/") def index(): return "&lt;strong&gt;This&lt;/strong&gt; would be the output HTML for the URL / " @GET("/view/([0-9]+?)$") def view_something(id): return "Viewing id %s" % (id) # URL /view/123 would output "Viewing id 123" runner(url = "/", # url would be from a web server, in actual use output_helper = "html_tidy" # run returned HTML though "HTML tidy" </code></pre> <p>Basically you have a function that returns HTML, and the GET decorator maps this to a URL.</p> <p>When <code>runner()</code> is called, each decorated function is checked, if the URL regex matches the request URL, the function is run, and the output is sent to the browser.</p> <p>Now, the problem - outputting headers. Currently for development I've just put a line before the <code>runner()</code> call which does <code>print Content-type:text/html\n</code> - this is obviously a bit limiting..</p> <p>My first ideas was to have the functions return a dict, something like..</p> <pre><code>@GET("/") def index(): return { "html": "&lt;html&gt;&lt;body&gt;...&lt;/body&gt;&lt;/html&gt;", "headers": {"Location":"http://google.com"} } </code></pre> <p>I really don't like this - having to return a dict with a specifically named key isn't nearly as nice as just returning a string..</p> <p>I could check if the returned data is a dict, if so use <code>returned_data['html']</code> as the output, if it's a string, there is no custom headers to be sent... but this means to go from no headers (which would be the case a huge majority of the time) to headers, you'd have to change the return function from <code>return my_html</code> to <code>return {'html':my_html}</code> which isn't very elegant either..</p> <p>After writing this, I discovered "Sinatra" - a similar-in-use Ruby library, and looked at how it dealt with headers:</p> <pre><code>get "/" do content_type 'text/css', :charset =&gt; 'utf-8' end </code></pre> <p>This seems like it could be nice enough in Python:</p> <pre><code>@GET("/") def index(): header("location", "http://google.com") </code></pre> <p>To implement this, I was considering changing how the functions are executed - instead of simply using the return value, I would change <code>sys.stdout</code> to a StringIO, so you could do..</p> <pre><code>def index(): print "&lt;html&gt;" print "&lt;head&gt;&lt;title&gt;Something&lt;/title&gt;&lt;/head&gt;" print "&lt;body&gt;...&lt;/body&gt;" print "&lt;/html&gt; </code></pre> <p>..without having to worry about concatenating a bunch of strings together. The upshot of this is I could have a separate stream for headers, so the above <code>header()</code> function would write to this.. Something like:</p> <pre><code>def header(name, value): pyerweb.header_stream.write("%s: %s" % (name, value)) </code></pre> <p>Basically, the question is, how would you output headers from this web-framework (mostly in terms of <em>use</em>, but to a lesser extent implementation)?</p>
3
2008-12-07T11:41:34Z
347,545
<p>you could use that idea of returning a dict or a string, but add a new decorator, so the 'evolution' for a user would be:</p> <p>simple html:</p> <pre><code>@GET("/") def index(): return "&lt;html&gt;&lt;body&gt;...&lt;/body&gt;&lt;/html&gt;" </code></pre> <p>with constant headers (one @HEADER for each one, or a dict with all of them):</p> <pre><code>@GET("/") @HEADER("Location","http://google.com") def index(): return "&lt;html&gt;&lt;body&gt;...&lt;/body&gt;&lt;/html&gt;" </code></pre> <p>with complex, maybe calculated headers:</p> <pre><code>@GET("/") def index(): return { "html": "&lt;html&gt;&lt;body&gt;...&lt;/body&gt;&lt;/html&gt;", "headers": {"Location":"http://google.com"} } </code></pre> <p>the @HEADER() decorator would simply change the returned value, so the 'framework' code would stay simple.</p>
3
2008-12-07T12:53:39Z
[ "python", "frameworks" ]
Emitting headers from a tiny Python web-framework
347,497
<p>I am writing a web-framework for Python, of which the goal is to be as "small" as possible (currently under 100 lines of code).. You can see the current code <a href="http://github.com/dbr/pyerweb/tree/master" rel="nofollow">on github</a></p> <p>Basically it's written to be as simple to use as possible. An example "Hello World" like site:</p> <pre><code>from pyerweb import GET, runner @GET("/") def index(): return "&lt;strong&gt;This&lt;/strong&gt; would be the output HTML for the URL / " @GET("/view/([0-9]+?)$") def view_something(id): return "Viewing id %s" % (id) # URL /view/123 would output "Viewing id 123" runner(url = "/", # url would be from a web server, in actual use output_helper = "html_tidy" # run returned HTML though "HTML tidy" </code></pre> <p>Basically you have a function that returns HTML, and the GET decorator maps this to a URL.</p> <p>When <code>runner()</code> is called, each decorated function is checked, if the URL regex matches the request URL, the function is run, and the output is sent to the browser.</p> <p>Now, the problem - outputting headers. Currently for development I've just put a line before the <code>runner()</code> call which does <code>print Content-type:text/html\n</code> - this is obviously a bit limiting..</p> <p>My first ideas was to have the functions return a dict, something like..</p> <pre><code>@GET("/") def index(): return { "html": "&lt;html&gt;&lt;body&gt;...&lt;/body&gt;&lt;/html&gt;", "headers": {"Location":"http://google.com"} } </code></pre> <p>I really don't like this - having to return a dict with a specifically named key isn't nearly as nice as just returning a string..</p> <p>I could check if the returned data is a dict, if so use <code>returned_data['html']</code> as the output, if it's a string, there is no custom headers to be sent... but this means to go from no headers (which would be the case a huge majority of the time) to headers, you'd have to change the return function from <code>return my_html</code> to <code>return {'html':my_html}</code> which isn't very elegant either..</p> <p>After writing this, I discovered "Sinatra" - a similar-in-use Ruby library, and looked at how it dealt with headers:</p> <pre><code>get "/" do content_type 'text/css', :charset =&gt; 'utf-8' end </code></pre> <p>This seems like it could be nice enough in Python:</p> <pre><code>@GET("/") def index(): header("location", "http://google.com") </code></pre> <p>To implement this, I was considering changing how the functions are executed - instead of simply using the return value, I would change <code>sys.stdout</code> to a StringIO, so you could do..</p> <pre><code>def index(): print "&lt;html&gt;" print "&lt;head&gt;&lt;title&gt;Something&lt;/title&gt;&lt;/head&gt;" print "&lt;body&gt;...&lt;/body&gt;" print "&lt;/html&gt; </code></pre> <p>..without having to worry about concatenating a bunch of strings together. The upshot of this is I could have a separate stream for headers, so the above <code>header()</code> function would write to this.. Something like:</p> <pre><code>def header(name, value): pyerweb.header_stream.write("%s: %s" % (name, value)) </code></pre> <p>Basically, the question is, how would you output headers from this web-framework (mostly in terms of <em>use</em>, but to a lesser extent implementation)?</p>
3
2008-12-07T11:41:34Z
347,588
<p>Look at <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">PEP 333</a> for an excellent design pattern for a very lightweight web server. If your server has this exact API, you can reuse it in a lot of context with a lot of other products.</p> <p>PEP 333 (WSGI) suggests that you don't directly return the page, but you provide the HTML page to a "start_response" callable object, which wraps your HTML in the proper HTTP response, with the proper headers.</p>
5
2008-12-07T13:43:28Z
[ "python", "frameworks" ]
Rounding float to the nearest factor?
347,538
<p>I have a small math problem I am trying to solve</p> <p>Given a number x and resolution y, I need to find the next x' with the required resolution.</p> <p>e.g.</p> <pre><code>x = 1.002 y = 0.1 x'= 1.1 x = 0.348 y = 0.1 x'= 0.4 x = 0.50 y = 1 x'= 1 x = 0.32 y = 0.05 x'= 0.35 </code></pre> <p>Is there any smart way of doing this in Python?</p>
6
2008-12-07T12:45:15Z
347,549
<pre><code>import math def next_multiple(x, y): return math.ceil(x/y)*y def try_it(x, y): print x, y, next_multiple(x, y) for x, y in [ (1.002, 0.1), (0.348, 0.1), (0.50, 1), (0.32, 0.05) ]: try_it(x, y) </code></pre> <p>produces:</p> <pre><code>1.002 0.1 1.1 0.348 0.1 0.4 0.5 1 1.0 0.32 0.05 0.35 </code></pre> <p>I think your first example output is wrong, The correct answer for x' is 1.1, right?</p>
11
2008-12-07T13:00:28Z
[ "python", "algorithm", "math" ]
How do I get nose to discover dynamically-generated testcases?
347,574
<p>This is a follow-up to a <a href="http://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest">previous question</a> of mine.</p> <p>In the previous question, methods were explored to implement what was essentially the same test over an entire family of functions, ensuring testing did not stop at the first function that failed.</p> <p>My preferred solution used a metaclass to dynamically insert the tests into a unittest.TestCase. Unfortunately, nose does not pick this up because nose statically scans for test cases.</p> <p>How do I get nose to discover and run such a TestCase? Please refer <a href="http://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest#347175">here</a> for an example of the TestCase in question.</p>
6
2008-12-07T13:30:45Z
366,620
<p>You could try to generate the testcase classes with type()</p> <pre><code>class UnderTest_MixIn(object): def f1(self, i): return i + 1 def f2(self, i): return i + 2 SomeDynamicTestcase = type( "SomeDynamicTestcase", (UnderTest_MixIn, unittest.TestCase), {"even_more_dynamic":"attributes .."} ) # or even: name = 'SomeDynamicTestcase' globals()[name] = type( name, (UnderTest_MixIn, unittest.TestCase), {"even_more_dynamic":"attributes .."} ) </code></pre> <p>This should be created when nose tries to import your test_module so it should work.</p> <p>The advantage of this approach is that you can create many combinations of tests dynamically.</p>
0
2008-12-14T14:54:30Z
[ "python", "unit-testing", "nose" ]
How do I get nose to discover dynamically-generated testcases?
347,574
<p>This is a follow-up to a <a href="http://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest">previous question</a> of mine.</p> <p>In the previous question, methods were explored to implement what was essentially the same test over an entire family of functions, ensuring testing did not stop at the first function that failed.</p> <p>My preferred solution used a metaclass to dynamically insert the tests into a unittest.TestCase. Unfortunately, nose does not pick this up because nose statically scans for test cases.</p> <p>How do I get nose to discover and run such a TestCase? Please refer <a href="http://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest#347175">here</a> for an example of the TestCase in question.</p>
6
2008-12-07T13:30:45Z
676,420
<p>Nose has a "test generator" feature for stuff like this. You write a generator function that yields each "test case" function you want it to run, along with its args. Following your previous example, this could check each of the functions in a separate test:</p> <pre><code>import unittest import numpy from somewhere import the_functions def test_matrix_functions(): for function in the_functions: yield check_matrix_function, function def check_matrix_function(function) matrix1 = numpy.ones((5,10)) matrix2 = numpy.identity(5) output = function(matrix1, matrix2) assert matrix1.shape == output.shape, \ "%s produces output of the wrong shape" % str(function) </code></pre>
7
2009-03-24T07:19:15Z
[ "python", "unit-testing", "nose" ]
How do I get nose to discover dynamically-generated testcases?
347,574
<p>This is a follow-up to a <a href="http://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest">previous question</a> of mine.</p> <p>In the previous question, methods were explored to implement what was essentially the same test over an entire family of functions, ensuring testing did not stop at the first function that failed.</p> <p>My preferred solution used a metaclass to dynamically insert the tests into a unittest.TestCase. Unfortunately, nose does not pick this up because nose statically scans for test cases.</p> <p>How do I get nose to discover and run such a TestCase? Please refer <a href="http://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest#347175">here</a> for an example of the TestCase in question.</p>
6
2008-12-07T13:30:45Z
13,579,703
<p>Nose does not scan for tests statically, so you <em>can</em> use metaclass magic to make tests that Nose finds.</p> <p>The hard part is that standard metaclass techniques don't set the func_name attribute correctly, which is what Nose looks for when checking whether methods on your class are tests.</p> <p>Here's a simple metaclass. It looks through the func dict and adds a new method for every method it finds, asserting that the method it found has a docstring. These new synthetic methods are given the names <code>"test_%d" %i</code>.</p> <pre><code>import new from inspect import isfunction, getdoc class Meta(type): def __new__(cls, name, bases, dct): newdct = dct.copy() for i, (k, v) in enumerate(filter(lambda e: isfunction(e[1]), dct.items())): def m(self, func): assert getdoc(func) is not None fname = 'test_%d' % i newdct[fname] = new.function(m.func_code, globals(), fname, (v,), m.func_closure) return super(Meta, cls).__new__(cls, 'Test_'+name, bases, newdct) </code></pre> <p>Now, let's create a new class that uses this metaclass</p> <pre><code>class Foo(object): __metaclass__ = Meta def greeter(self): "sdf" print 'Hello World' def greeter_no_docstring(self): pass </code></pre> <p>At runtime, <code>Foo</code> will actually be named <code>Test_Foo</code> and will have <code>greeter</code>, <code>greeter_no_docstring</code>, <code>test_1</code> and <code>test_2</code> as its methods. When I run <code>nosetests</code> on this file, here's the output:</p> <pre><code>$ nosetests -v test.py test.Test_Foo.test_0 ... FAIL test.Test_Foo.test_1 ... ok ====================================================================== FAIL: test.Test_Foo.test_0 ---------------------------------------------------------------------- Traceback (most recent call last): File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/Users/rmcgibbo/Desktop/test.py", line 10, in m assert getdoc(func) is not None AssertionError ---------------------------------------------------------------------- Ran 2 tests in 0.002s FAILED (failures=1) </code></pre> <p>This metaclass isn't really useful as is, but if you instead use the <code>Meta</code> not as a proper metaclass, but as more of a functional metaclass (i.e. takes a class as an argument and returns a new class, one that's renamed so that nose will find it), then it <em>is</em> useful. I've used this approach to automatically test that the docstrings adhere to the Numpy standard as part of a nose test suite.</p> <p>Also, I've had a lot of trouble getting proper closure working with new.function, which is why this code uses <code>m(self, func)</code> where <code>func</code> is made to be a default argument. It would be more natural to use a closure over <code>value</code>, but that doesn't seem to work.</p>
2
2012-11-27T08:00:07Z
[ "python", "unit-testing", "nose" ]
mod_python.publisher always gives content type 'text/plain'
347,632
<p>I've just set up mod python with apache and I'm trying to get a simple script to work, but what happens is it publishes all my html as plain text when I load the page. I figured this is a problem with mod_python.publisher, The handler I set it too. I searched through the source of it and found the line where it differentiates between 'text/plain' and 'text/html' and it searches the last hundred characters of the file it's outputting for ' in my script, so I put it in, and then it still didn't work. I even tried commenting out some of the code so that publisher would set everything as 'text/html' but it still did the same thing when I refreshed the page. Maybe I've set up something wrong.</p> <p>Heres my configuration in the httpd.conf</p> <blockquote> <p>&lt; Directory "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs"><br /> SetHandler mod_python<br /> PythonHandler mod_python.publisher<br /> PythonDebug On<br /> &lt; /Directory ></p> </blockquote>
0
2008-12-07T14:27:09Z
347,733
<p>Your configuration looks okay: I've got a working mod_python.publisher script with essentially the same settings.</p> <p>A few other thoughts:</p> <ul> <li><p>When you tried editing the publisher source code, did you restart your web server? It only loads Python libraries once, when the server is first started.</p></li> <li><p>Publisher's autodetection looks for a closing HTML tag: &lt;/html&gt;. Is that what you added? (I can't see it in your question, but possibly it just got stripped out when you posted it.)</p></li> <li><p>If nothing else works, you can always set the content type explicitly. It's more code, but it's guaranteed to work consistently. Set the content_type field on your request to 'text/html'. </p></li> </ul> <p>For example, if your script looks like this right now:</p> <pre><code>def index(req, an_arg='default'): return some_html </code></pre> <p>it would become:</p> <pre><code>def index(req, an_arg='default'): req.content_type = 'text/html' return some_html </code></pre>
3
2008-12-07T16:15:26Z
[ "python", "content-type", "mod-python" ]
Gauss-Legendre Algorithm in python
347,734
<p>I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use. I have read about the <a href="http://en.wikipedia.org/wiki/Gauss-Legendre_algorithm">Gauss-Legendre Algorithm</a>, and I have tried porting it to Python with no success.</p> <p>I am reading from <a href="http://www.geocities.com/hjsmithh/Pi/Gauss_L.html">Here</a>, and I would appreciate any input as to where I am going wrong!</p> <p>It outputs: 0.163991276262</p> <pre><code>from __future__ import division import math def square(x):return x*x a = 1 b = 1/math.sqrt(2) t = 1/4 x = 1 for i in range(1000): y = a a = (a+b)/2 b = math.sqrt(b*y) t = t - x * square((y-a)) x = 2* x pi = (square((a+b)))/4*t print pi raw_input() </code></pre>
12
2008-12-07T16:15:40Z
347,749
<ol> <li><p>You forgot parentheses around <code>4*t</code>:</p> <pre><code>pi = (a+b)**2 / (4*t) </code></pre></li> <li><p>You can use <code>decimal</code> to perform calculation with higher precision.</p> <pre><code>#!/usr/bin/env python from __future__ import with_statement import decimal def pi_gauss_legendre(): D = decimal.Decimal with decimal.localcontext() as ctx: ctx.prec += 2 a, b, t, p = 1, 1/D(2).sqrt(), 1/D(4), 1 pi = None while 1: an = (a + b) / 2 b = (a * b).sqrt() t -= p * (a - an) * (a - an) a, p = an, 2*p piold = pi pi = (a + b) * (a + b) / (4 * t) if pi == piold: # equal within given precision break return +pi decimal.getcontext().prec = 100 print pi_gauss_legendre() </code></pre></li> </ol> <p>Output:</p> <pre><code>3.141592653589793238462643383279502884197169399375105820974944592307816406286208\ 998628034825342117068 </code></pre>
24
2008-12-07T16:29:55Z
[ "python", "algorithm", "pi" ]
Gauss-Legendre Algorithm in python
347,734
<p>I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use. I have read about the <a href="http://en.wikipedia.org/wiki/Gauss-Legendre_algorithm">Gauss-Legendre Algorithm</a>, and I have tried porting it to Python with no success.</p> <p>I am reading from <a href="http://www.geocities.com/hjsmithh/Pi/Gauss_L.html">Here</a>, and I would appreciate any input as to where I am going wrong!</p> <p>It outputs: 0.163991276262</p> <pre><code>from __future__ import division import math def square(x):return x*x a = 1 b = 1/math.sqrt(2) t = 1/4 x = 1 for i in range(1000): y = a a = (a+b)/2 b = math.sqrt(b*y) t = t - x * square((y-a)) x = 2* x pi = (square((a+b)))/4*t print pi raw_input() </code></pre>
12
2008-12-07T16:15:40Z
347,758
<pre><code>pi = (square((a+b)))/4*t </code></pre> <p>should be</p> <pre><code>pi = (square((a+b)))/(4*t) </code></pre>
3
2008-12-07T16:37:09Z
[ "python", "algorithm", "pi" ]
Gauss-Legendre Algorithm in python
347,734
<p>I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use. I have read about the <a href="http://en.wikipedia.org/wiki/Gauss-Legendre_algorithm">Gauss-Legendre Algorithm</a>, and I have tried porting it to Python with no success.</p> <p>I am reading from <a href="http://www.geocities.com/hjsmithh/Pi/Gauss_L.html">Here</a>, and I would appreciate any input as to where I am going wrong!</p> <p>It outputs: 0.163991276262</p> <pre><code>from __future__ import division import math def square(x):return x*x a = 1 b = 1/math.sqrt(2) t = 1/4 x = 1 for i in range(1000): y = a a = (a+b)/2 b = math.sqrt(b*y) t = t - x * square((y-a)) x = 2* x pi = (square((a+b)))/4*t print pi raw_input() </code></pre>
12
2008-12-07T16:15:40Z
347,760
<ol> <li>If you want to calculate PI to 1000 digits you need to use a data type that supports 1000 digits of precision (e.g., <a href="http://www.egenix.com/products/python/mxExperimental/mxNumber/" rel="nofollow">mxNumber</a>)</li> <li>You need to calculate a,b,t, and x until |a-b| &lt; 10**-digits, not iterate digits times.</li> <li>Calculate square and pi as @J.F. suggests.</li> </ol>
3
2008-12-07T16:38:24Z
[ "python", "algorithm", "pi" ]
AKS Primes algorithm in Python
347,811
<p>A few years ago, it was proven that <a href="http://www.cse.iitk.ac.in/~manindra/algebra/primality_v6.pdf">PRIMES is in P</a>. Are there any algorithms implementing <a href="http://en.wikipedia.org/wiki/AKS_primality_test">their primality test</a> in Python? I wanted to run some benchmarks with a naive generator and see for myself how fast it is. I'd implement it myself, but I don't understand the paper enough yet to do that.</p>
23
2008-12-07T17:41:10Z
347,840
<p>Quick answer: no, the AKS test is not the fastest way to test primality. There are much <em>much</em> faster primality tests that either assume the (generalized) Riemann hypothesis and/or are randomized. (E.g. <a href="http://en.wikipedia.org/wiki/Miller-Rabin_primality_test">Miller-Rabin</a> is fast and simple to implement.) The real breakthrough of the paper was theoretical, proving that a <em>deterministic</em> polynomial-time algorithm exists for testing primality, without assuming the GRH or other unproved conjectures.</p> <p>That said, if you want to understand and implement it, <a href="http://www.scottaaronson.com/writings/prime.pdf">Scott Aaronson's short article</a> might help. It doesn't go into all the details, but you can start at page 10 of 12, and it gives enough. :-) There is also a <a href="http://fatphil.org/maths/AKS/#Implementations">list of implementations</a> (mostly in C++) here.</p> <p>Also, for optimization and improvements (by several orders of magnitude), you might want to look at <a href="http://www.southerington.com/souther/projects/aks/RP-3_report.pdf">this report</a>, or (older) <a href="http://developer.apple.com/hardware/ve/pdf/aks3.pdf">Crandall and Papadopoulos's report</a>, or (older still) <a href="http://cr.yp.to/papers/aks.pdf">Daniel J Bernstein's report</a>. All of them have fairly detailed pseudo-code that lends itself well to implementation.</p>
42
2008-12-07T18:02:27Z
[ "python", "algorithm", "primes" ]
AKS Primes algorithm in Python
347,811
<p>A few years ago, it was proven that <a href="http://www.cse.iitk.ac.in/~manindra/algebra/primality_v6.pdf">PRIMES is in P</a>. Are there any algorithms implementing <a href="http://en.wikipedia.org/wiki/AKS_primality_test">their primality test</a> in Python? I wanted to run some benchmarks with a naive generator and see for myself how fast it is. I'd implement it myself, but I don't understand the paper enough yet to do that.</p>
23
2008-12-07T17:41:10Z
29,834,291
<p>Yes, go look at <a href="http://rosettacode.org/wiki/AKS_test_for_primes#Python" rel="nofollow">AKS test for primes</a> page on rosettacode.org</p> <pre><code>def expand_x_1(p): ex = [1] for i in range(p): ex.append(ex[-1] * -(p-i) / (i+1)) return ex[::-1] def aks_test(p): if p &lt; 2: return False ex = expand_x_1(p) ex[0] += 1 return not any(mult % p for mult in ex[0:-1]) print('# p: (x-1)^p for small p') for p in range(12): print('%3i: %s' % (p, ' '.join('%+i%s' % (e, ('x^%i' % n) if n else '') for n,e in enumerate(expand_x_1(p))))) print('\n# small primes using the aks test') print([p for p in range(101) if aks_test(p)]) </code></pre> <p>and the output is:</p> <pre><code># p: (x-1)^p for small p 0: +1 1: -1 +1x^1 2: +1 -2x^1 +1x^2 3: -1 +3x^1 -3x^2 +1x^3 4: +1 -4x^1 +6x^2 -4x^3 +1x^4 5: -1 +5x^1 -10x^2 +10x^3 -5x^4 +1x^5 6: +1 -6x^1 +15x^2 -20x^3 +15x^4 -6x^5 +1x^6 7: -1 +7x^1 -21x^2 +35x^3 -35x^4 +21x^5 -7x^6 +1x^7 8: +1 -8x^1 +28x^2 -56x^3 +70x^4 -56x^5 +28x^6 -8x^7 +1x^8 9: -1 +9x^1 -36x^2 +84x^3 -126x^4 +126x^5 -84x^6 +36x^7 -9x^8 +1x^9 10: +1 -10x^1 +45x^2 -120x^3 +210x^4 -252x^5 +210x^6 -120x^7 +45x^8 -10x^9 +1x^10 11: -1 +11x^1 -55x^2 +165x^3 -330x^4 +462x^5 -462x^6 +330x^7 -165x^8 +55x^9 -11x^10 +1x^11 # small primes using the aks test [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] </code></pre>
-3
2015-04-23T21:04:51Z
[ "python", "algorithm", "primes" ]
How to test django caching?
347,812
<p>Is there a way to be <strong>sure</strong> that a page is coming from cache on a production server and on the development server as well?</p> <p>The solution <strong>shouldn't</strong> involve caching middleware because not every project uses them. Though the solution itself might <strong>be</strong> a middleware.</p> <p>Just checking if the data is stale is not a very safe testing method IMO.</p>
14
2008-12-07T17:41:34Z
348,079
<p>Mock the view, hit the page, and see if the mock was called. if it was not, the cache was used instead.</p>
7
2008-12-07T21:06:49Z
[ "python", "django", "caching", "django-cache" ]
How to test django caching?
347,812
<p>Is there a way to be <strong>sure</strong> that a page is coming from cache on a production server and on the development server as well?</p> <p>The solution <strong>shouldn't</strong> involve caching middleware because not every project uses them. Though the solution itself might <strong>be</strong> a middleware.</p> <p>Just checking if the data is stale is not a very safe testing method IMO.</p>
14
2008-12-07T17:41:34Z
348,192
<p>The reason you use caches is to improve performance. Test the performance by running a load test against your server. If the server's performance matches your needs, then you are all set!</p>
3
2008-12-07T22:12:02Z
[ "python", "django", "caching", "django-cache" ]
How to test django caching?
347,812
<p>Is there a way to be <strong>sure</strong> that a page is coming from cache on a production server and on the development server as well?</p> <p>The solution <strong>shouldn't</strong> involve caching middleware because not every project uses them. Though the solution itself might <strong>be</strong> a middleware.</p> <p>Just checking if the data is stale is not a very safe testing method IMO.</p>
14
2008-12-07T17:41:34Z
348,546
<p>We do a lot of component caching and not all of them are updated at the same time. So we set host and timestamp values in a universally included context processor. At the top of each template fragment we stick in:</p> <pre><code>&lt;!-- component_name {{host}} {{timestamp}} --&gt; </code></pre> <p>The component_name just makes it easy to do a View Source and search for that string.</p> <p>All of our views that are object-detail pages define a context variable "page_object" and we have this at the top of the base.html template master:</p> <pre><code>&lt;!-- {{page_object.class_id}} @ {{timestamp}} --&gt; </code></pre> <p>class_id() is a method from a super class used by all of our primary content classes. It is just:</p> <pre><code>def class_id(self): "%s.%s.%s" % (self.__class__._meta.app_label, self.__class__.__name__, self.id) </code></pre> <p>If you load a page and any of the timestamps are more than few seconds old, it's a pretty good bet that the component was cached.</p>
18
2008-12-08T02:33:16Z
[ "python", "django", "caching", "django-cache" ]
How to test django caching?
347,812
<p>Is there a way to be <strong>sure</strong> that a page is coming from cache on a production server and on the development server as well?</p> <p>The solution <strong>shouldn't</strong> involve caching middleware because not every project uses them. Though the solution itself might <strong>be</strong> a middleware.</p> <p>Just checking if the data is stale is not a very safe testing method IMO.</p>
14
2008-12-07T17:41:34Z
5,563,503
<p>Peter Rowells suggestion works well, but you don't need a custom template context processor for timestamps. You can simply use the template tag:</p> <pre><code> &lt;!-- {% now "jS F Y H:i" %} --&gt; </code></pre>
12
2011-04-06T08:32:14Z
[ "python", "django", "caching", "django-cache" ]
What could justify the complexity of Plone?
348,044
<p>Plone is very complex. <a href="http://en.wikipedia.org/wiki/Zope">Zope</a>2, <a href="http://en.wikipedia.org/wiki/Zope_3">Zope3</a>, <a href="http://codespeak.net/z3/five/">Five</a>, <a href="http://wiki.zope.org/zope3/ZCML">ZCML</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database">ZODB</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO">ZEO</a>, a whole bunch of acronyms and abbreviations.</p> <p>It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.</p> <p>Does the steep learning curve pay of? Is this complexity still justified today?</p> <p>Background: I need a platform. Customers often need a CMS. I'm currently reading "<a href="http://plone.org/news/book-professional-plone-development-now-shipping">Professional Plone Development</a>", without prior knowledge of Plone.</p> <p>The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "<a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692">If you want to see the complexity of Plone, you have to ask for it.</a>" when you don't know the system good enough to plan.</p>
12
2008-12-07T20:41:40Z
348,317
<p>I see four things that can justify an investment of time in using Plone:</p> <ul> <li>Plone has a large and helpful community. Most of the things you need, somebody else<br /> already did at some time in the past. He probably asked some questions and got helpful answers, or he wrote a tutorial. Usually that leaves traces easy to find. about how he did it.</li> <li>You won't need to understand the whole complexity for many of your customizing needs.</li> <li>Plone developers are aware of their complex stack, and are discussing how this can be reduced. Plone has proven in the past that it is able to renew itself and drop old infrastructure in a clean way with defined deprecation phases.</li> <li>There are many local user groups with helpful people.</li> </ul> <p>Oh wait, I was told the plone developer meetings are one of the best! <a href="http://plone.org/events/conferences/vienna-2004" rel="nofollow">Like that one</a></p>
7
2008-12-07T23:30:53Z
[ "python", "content-management-system", "plone", "zope" ]
What could justify the complexity of Plone?
348,044
<p>Plone is very complex. <a href="http://en.wikipedia.org/wiki/Zope">Zope</a>2, <a href="http://en.wikipedia.org/wiki/Zope_3">Zope3</a>, <a href="http://codespeak.net/z3/five/">Five</a>, <a href="http://wiki.zope.org/zope3/ZCML">ZCML</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database">ZODB</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO">ZEO</a>, a whole bunch of acronyms and abbreviations.</p> <p>It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.</p> <p>Does the steep learning curve pay of? Is this complexity still justified today?</p> <p>Background: I need a platform. Customers often need a CMS. I'm currently reading "<a href="http://plone.org/news/book-professional-plone-development-now-shipping">Professional Plone Development</a>", without prior knowledge of Plone.</p> <p>The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "<a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692">If you want to see the complexity of Plone, you have to ask for it.</a>" when you don't know the system good enough to plan.</p>
12
2008-12-07T20:41:40Z
348,508
<p>It's hard to answer your question without any background information. Is the complexity justified if you just want a blog? No. Is the complexity justified if you're building a company intranet for 400+ people? Yes. Is it a good investment if you're looking to be a consultant? Absolutely! There's a lot of Plone work out there, and it pays much better than the average PHP job.</p> <p>I'd encourage you to clarify what you're trying to build, and ask the Plone forums for advice. Plone has a very mature and friendly community — and will absolutely let you know if what you're trying to do is a poor fit for Plone. You can of course do whatever you want with Plone, but there are some areas where it's the best solution available, other areas where it'll be a lot of work to change it to do something else.</p> <p>Some background:</p> <p>The reason for the complexity of Plone at this point in time is that it's moving to a more modern architecture. It's bridging both the old and the new approach right now, which adds some complexity until the transition is mostly complete.</p> <p>Plone is doing this to avoid leaving their customers behind by breaking backwards compatibility, which they take very seriously — unlike other systems I could mention (but won't ;). </p> <p>You care about your data, the Plone community cares about their data — and we'd like you to be able to upgrade to the new and better versions even when we're transitioning to a new architecture. This is one of the Plone community's strengths, but there is of course a penalty to pay for modifying the plane while it's flying, and that's a bit of temporary, extra complexity.</p> <p>Furthermore, Plone as a community has a strong focus on security (compare it to any other system on the vulnerabilities reported), and a very professional culture that values good architecture, testing and reusability.</p> <p>As an example, consider the current version of Plone being developed (what will become 4.0):</p> <ul> <li>It starts up 3-4 times faster than the current version.</li> <li>It uses about 20% less memory than the current version.</li> <li>There's a much, much easier types system in the works (Dexterity), which will reduce the complexity and speed up the system a lot, while keeping the same level of functionality</li> <li>The code base is already 20% smaller than the current shipping version, and getting even smaller.</li> <li>Early benchmarks of the new types system show a 5&times; speedup for content editing, and we haven't really started optimizing this part yet.</li> </ul> <p>— Alexander Limi, Plone co-founder (and slightly biased ;)</p>
29
2008-12-08T01:59:39Z
[ "python", "content-management-system", "plone", "zope" ]
What could justify the complexity of Plone?
348,044
<p>Plone is very complex. <a href="http://en.wikipedia.org/wiki/Zope">Zope</a>2, <a href="http://en.wikipedia.org/wiki/Zope_3">Zope3</a>, <a href="http://codespeak.net/z3/five/">Five</a>, <a href="http://wiki.zope.org/zope3/ZCML">ZCML</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database">ZODB</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO">ZEO</a>, a whole bunch of acronyms and abbreviations.</p> <p>It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.</p> <p>Does the steep learning curve pay of? Is this complexity still justified today?</p> <p>Background: I need a platform. Customers often need a CMS. I'm currently reading "<a href="http://plone.org/news/book-professional-plone-development-now-shipping">Professional Plone Development</a>", without prior knowledge of Plone.</p> <p>The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "<a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692">If you want to see the complexity of Plone, you have to ask for it.</a>" when you don't know the system good enough to plan.</p>
12
2008-12-07T20:41:40Z
351,692
<p>If you want to see the complexity of Plone, you have to ask for it. For most people, it's just not there. It installs in a couple of minutes through a one-click installer. Then it's one click to log in, one click to create a page, use a WYSYWIG editor, and one click to save. Everything is through an intuitive web GUI. Plone is a product.</p> <p>If you want to use it as a "platform," then the platform is a stack of over one million lines of code which implements a complete content management suite. No one knows it all. However, all those "acronyms" and "files" are evidence of a software which is factored in components so that no one need know it all. You can get as deep or shallow in it as you need. If there's something you need for some aspect of content management, it's already there, you don't have to create it from scratch, and you can do it in a way that's consistent with a wide practice and review.</p>
23
2008-12-09T03:29:19Z
[ "python", "content-management-system", "plone", "zope" ]
What could justify the complexity of Plone?
348,044
<p>Plone is very complex. <a href="http://en.wikipedia.org/wiki/Zope">Zope</a>2, <a href="http://en.wikipedia.org/wiki/Zope_3">Zope3</a>, <a href="http://codespeak.net/z3/five/">Five</a>, <a href="http://wiki.zope.org/zope3/ZCML">ZCML</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database">ZODB</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO">ZEO</a>, a whole bunch of acronyms and abbreviations.</p> <p>It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.</p> <p>Does the steep learning curve pay of? Is this complexity still justified today?</p> <p>Background: I need a platform. Customers often need a CMS. I'm currently reading "<a href="http://plone.org/news/book-professional-plone-development-now-shipping">Professional Plone Development</a>", without prior knowledge of Plone.</p> <p>The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "<a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692">If you want to see the complexity of Plone, you have to ask for it.</a>" when you don't know the system good enough to plan.</p>
12
2008-12-07T20:41:40Z
446,659
<p>I found an anonymous comment <a href="http://bitubique.com/content/im-done-plone#comment-10">here</a> which is much better than that post itself, so I'm reposting it here in full, with a couple of typos corrected.</p> <p><hr /></p> <p>This summer my chess club asked me to make a new website, where the members of the board should be able to add news flashes, articles, ... Sounded like a CMS. Being a Python developer, I looked at Plone and bought the Aspeli book Professional Plone development (excellent written btw).</p> <p>I took 3 weeks of my holiday the study the book and to setup a first mock up of the site.</p> <p>After 3 weeks I realized that Plone has some very nice things but also some very frustrating things On the positivie side</p> <ul> <li>if you don't need to customize Plone, Plone is great in features and layout</li> <li>Plone has a good security model</li> <li>Plone has good off the shelf workflows</li> <li>Plone is multi language (what I needed)</li> </ul> <p>On the downside</p> <ol> <li>Plone is terrible slow. On my development platform (a 3 years old Pc with 512 MB RAM) it takes 30 seconds to launch Plone and it takes 10 to 15 seconds to reload a page</li> <li>you need a lot of different technologies to customize or develop even the simplest things</li> <li>TAL and Metal are not state of the art and not adapted to the OO design of Plone.</li> <li>Acquisition by default is wrong. Acquisation can be very useful (for e.g. security) but it should be explicitly defined where needed. This is a design flaw</li> <li>Plone does not distinguish between content and layout. This a serious design flaw. There is no reason to apply security settings and roles on e.g. cascading style sheet or the html that creates a 3 column layout and there is no reason why these elements should be in the ZODB and not on the filesystem</li> <li>Plone does not distinguish between the web designer and the content editor/publisher, again a serious flaw. The content editor/publisher add/reviews content running on the live site. The web designer adds/modifies content types, forms and layout on the test server and ports it to the live server when ready. The security restrictions Plone put in place for the content editor should not be applied for the web designer, who has access to the filesystem on the server.</li> <li>Plone does not distinguish between the graphical aspects and the programming aspects of a web designer. Graphical artists uses tools that only speak html, css and a little bit of javasccript, but no Python, adapters and other advanced programming concepts. As a consequence the complete skinning system in Plone is a nightmare</li> </ol> <p>I assume that Plone is so slow because of points 4, 5, 6 and 7.</p> <p>Points 6 and 7 made me dropping Plone. I looked around for other options and eventually decided to develop my own CMS on Pylons, which is blazingly fast compared to Plone. On the same development server I have a startup time of 1 second, and a reload page time is not measurable.</p> <p>The site www.kosk.be is running (it is in Dutch). The CMS behind it, named Red Devil, will be launched as a separate open source project beginning next year</p>
9
2009-01-15T13:08:53Z
[ "python", "content-management-system", "plone", "zope" ]
What could justify the complexity of Plone?
348,044
<p>Plone is very complex. <a href="http://en.wikipedia.org/wiki/Zope">Zope</a>2, <a href="http://en.wikipedia.org/wiki/Zope_3">Zope3</a>, <a href="http://codespeak.net/z3/five/">Five</a>, <a href="http://wiki.zope.org/zope3/ZCML">ZCML</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database">ZODB</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO">ZEO</a>, a whole bunch of acronyms and abbreviations.</p> <p>It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.</p> <p>Does the steep learning curve pay of? Is this complexity still justified today?</p> <p>Background: I need a platform. Customers often need a CMS. I'm currently reading "<a href="http://plone.org/news/book-professional-plone-development-now-shipping">Professional Plone Development</a>", without prior knowledge of Plone.</p> <p>The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "<a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692">If you want to see the complexity of Plone, you have to ask for it.</a>" when you don't know the system good enough to plan.</p>
12
2008-12-07T20:41:40Z
476,336
<p>From a system administrator standpoint, Plone is just shy of being the absolute devil. Upgrading, maintaining, and installing where you want to install things is all more painful than necessary on the Linux platform. That's just my two cents though, and why I typically prefer to avoid the Zope/Plone stack.</p> <p>Note: it's better with newer releases, but older releases.... ugh </p>
3
2009-01-24T17:04:56Z
[ "python", "content-management-system", "plone", "zope" ]
What could justify the complexity of Plone?
348,044
<p>Plone is very complex. <a href="http://en.wikipedia.org/wiki/Zope">Zope</a>2, <a href="http://en.wikipedia.org/wiki/Zope_3">Zope3</a>, <a href="http://codespeak.net/z3/five/">Five</a>, <a href="http://wiki.zope.org/zope3/ZCML">ZCML</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database">ZODB</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO">ZEO</a>, a whole bunch of acronyms and abbreviations.</p> <p>It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.</p> <p>Does the steep learning curve pay of? Is this complexity still justified today?</p> <p>Background: I need a platform. Customers often need a CMS. I'm currently reading "<a href="http://plone.org/news/book-professional-plone-development-now-shipping">Professional Plone Development</a>", without prior knowledge of Plone.</p> <p>The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "<a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692">If you want to see the complexity of Plone, you have to ask for it.</a>" when you don't know the system good enough to plan.</p>
12
2008-12-07T20:41:40Z
855,005
<p>Accretion.</p>
3
2009-05-12T21:40:37Z
[ "python", "content-management-system", "plone", "zope" ]
What could justify the complexity of Plone?
348,044
<p>Plone is very complex. <a href="http://en.wikipedia.org/wiki/Zope">Zope</a>2, <a href="http://en.wikipedia.org/wiki/Zope_3">Zope3</a>, <a href="http://codespeak.net/z3/five/">Five</a>, <a href="http://wiki.zope.org/zope3/ZCML">ZCML</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database">ZODB</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO">ZEO</a>, a whole bunch of acronyms and abbreviations.</p> <p>It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.</p> <p>Does the steep learning curve pay of? Is this complexity still justified today?</p> <p>Background: I need a platform. Customers often need a CMS. I'm currently reading "<a href="http://plone.org/news/book-professional-plone-development-now-shipping">Professional Plone Development</a>", without prior knowledge of Plone.</p> <p>The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "<a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692">If you want to see the complexity of Plone, you have to ask for it.</a>" when you don't know the system good enough to plan.</p>
12
2008-12-07T20:41:40Z
5,332,436
<p>About the comment <a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/446659#446659">here</a> I think Plone doesn't work like that (at least not anymore). </p> <p>1 - Plone is somehow slower than other CMS solutions indeed, but from the out-of-the-box setup to a Apache-Varnish-Zope-Relstorage solution, there is a lot of optimization space.</p> <p>2 - That is true. The answer <a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/348508#348508">here</a> kind of explains it, but indeed Plone is a complex animal.</p> <p>3 - Not sure what you mean. TAL Path expressions are based on the concept of object attribute traversal. Seems OO to me.</p> <p>4 - True. Although after you understand how Acquisition works, it stays out of your way. And in Plone not many things depend on Acquisition, I guess.</p> <p>5 - Not true. Zope Page Templates are all about separating content from presentation. The fact that content and presentation can be viewed from the ZODB (and actually most of the templates stay in the filesystem, you just see a "view" of them in the ZODB) is more related to the fact that the ZODB is a big object database - which in turn does not mean that they are all content. Everything in "pure" OO system is an object, it is just the kind of object (presentation objects, content object, etc) that matters.</p> <p>6 - Plone does distinguish between webdesigners and content creators. The designers do all customizations (templates, CSSs, JSs,etc) and then content creators create the content using Plone UI. The point here is that Plone is mainly a CMS, which means that content creators are supposed to be laymen in terms of design.</p> <p>7 - Partially true. Considering that the UI structure won't change, all presentation specification is contained in CSS files. If the UI structure needs to change, the designer might work with a plogrammer :-) to adequate the templates.</p> <p>I guess in no system that outputs dynamic pages the designer is completely free to speak only HTML, CSS and JS, and leave out some other technology, be it PHP, Python, ASP or Java. If he does, there will be definitely a programmer that will get the HTML,CSS and JS from the designer and "dynamize it". This model definitely exists in Plone.</p>
2
2011-03-16T22:08:16Z
[ "python", "content-management-system", "plone", "zope" ]
What could justify the complexity of Plone?
348,044
<p>Plone is very complex. <a href="http://en.wikipedia.org/wiki/Zope">Zope</a>2, <a href="http://en.wikipedia.org/wiki/Zope_3">Zope3</a>, <a href="http://codespeak.net/z3/five/">Five</a>, <a href="http://wiki.zope.org/zope3/ZCML">ZCML</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database">ZODB</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO">ZEO</a>, a whole bunch of acronyms and abbreviations.</p> <p>It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.</p> <p>Does the steep learning curve pay of? Is this complexity still justified today?</p> <p>Background: I need a platform. Customers often need a CMS. I'm currently reading "<a href="http://plone.org/news/book-professional-plone-development-now-shipping">Professional Plone Development</a>", without prior knowledge of Plone.</p> <p>The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "<a href="http://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692">If you want to see the complexity of Plone, you have to ask for it.</a>" when you don't know the system good enough to plan.</p>
12
2008-12-07T20:41:40Z
34,743,241
<p>Don't use it, if you don't have to. The whole ZOPE universe is a dinosaur. Grown for ages, has collected lots of cruft and rust. Many things would be done completely different nowadays. Overly complex for most stuff, hard to handle for complex stuff. It's the opposite of slim and scalable design. And for seriously fixing this, I don't see the necessary manpower involved in the project.</p> <p>Sorry for the harsh words, I also wish it would be any better.</p>
0
2016-01-12T12:05:10Z
[ "python", "content-management-system", "plone", "zope" ]
Creating a list of objects in Python
348,196
<p>I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.</p> <p>I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...</p> <p>Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over. </p> <p>So how do you write objects to a list within a loop?</p> <p>Thanks,</p> <p>Bob J</p> <p>Here's my simplified code</p> <pre><code>class SimpleClass(object): pass x = SimpleClass # Then create an empty list simpleList = [] #Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass for count in range(0,4): # each iteration creates a slightly different attribute value, and then prints it to # prove that step is working # but the problem is, I'm always updating a reference to 'x' and what I want to add to # simplelist is a new instance of x that contains the updated attribute x.attr1= '*Bob* '* count print "Loop Count: %s Attribute Value %s" % (count, x.attr1) simpleList.append(x) print '-'*20 # And here I print out each instance of the object stored in the list 'simpleList' # and the problem surfaces. Every element of 'simpleList' contains the same attribute value y = SimpleClass print "Reading the attributes from the objects in the list" for count in range(0,4): y = simpleList[count] print y.attr1 </code></pre> <p>So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?</p>
42
2008-12-07T22:15:46Z
348,214
<p>Create a new instance each time, where each new instance has the correct state, rather than continually modifying the state of the same instance.</p> <p>Alternately, store an explicitly-made copy of the object (using the hint <a href="http://docs.python.org/library/copy.html">at this page</a>) at each step, rather than the original.</p>
5
2008-12-07T22:22:32Z
[ "python", "list", "object", "loops" ]
Creating a list of objects in Python
348,196
<p>I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.</p> <p>I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...</p> <p>Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over. </p> <p>So how do you write objects to a list within a loop?</p> <p>Thanks,</p> <p>Bob J</p> <p>Here's my simplified code</p> <pre><code>class SimpleClass(object): pass x = SimpleClass # Then create an empty list simpleList = [] #Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass for count in range(0,4): # each iteration creates a slightly different attribute value, and then prints it to # prove that step is working # but the problem is, I'm always updating a reference to 'x' and what I want to add to # simplelist is a new instance of x that contains the updated attribute x.attr1= '*Bob* '* count print "Loop Count: %s Attribute Value %s" % (count, x.attr1) simpleList.append(x) print '-'*20 # And here I print out each instance of the object stored in the list 'simpleList' # and the problem surfaces. Every element of 'simpleList' contains the same attribute value y = SimpleClass print "Reading the attributes from the objects in the list" for count in range(0,4): y = simpleList[count] print y.attr1 </code></pre> <p>So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?</p>
42
2008-12-07T22:15:46Z
348,215
<p>You demonstrate a fundamental misunderstanding.</p> <p>You never created an instance of SimpleClass at all, because you didn't call it.</p> <pre><code>for count in xrange(4): x = SimpleClass() x.attr = count simplelist.append(x) </code></pre> <p>Or, if you let the class take parameters, instead, you can use a list comprehension.</p> <pre><code>simplelist = [SimpleClass(count) for count in xrange(4)] </code></pre>
39
2008-12-07T22:22:39Z
[ "python", "list", "object", "loops" ]
Creating a list of objects in Python
348,196
<p>I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.</p> <p>I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...</p> <p>Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over. </p> <p>So how do you write objects to a list within a loop?</p> <p>Thanks,</p> <p>Bob J</p> <p>Here's my simplified code</p> <pre><code>class SimpleClass(object): pass x = SimpleClass # Then create an empty list simpleList = [] #Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass for count in range(0,4): # each iteration creates a slightly different attribute value, and then prints it to # prove that step is working # but the problem is, I'm always updating a reference to 'x' and what I want to add to # simplelist is a new instance of x that contains the updated attribute x.attr1= '*Bob* '* count print "Loop Count: %s Attribute Value %s" % (count, x.attr1) simpleList.append(x) print '-'*20 # And here I print out each instance of the object stored in the list 'simpleList' # and the problem surfaces. Every element of 'simpleList' contains the same attribute value y = SimpleClass print "Reading the attributes from the objects in the list" for count in range(0,4): y = simpleList[count] print y.attr1 </code></pre> <p>So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?</p>
42
2008-12-07T22:15:46Z
348,222
<p>If I understand correctly your question, you ask a way to execute a deep copy of an object. What about using copy.deepcopy?</p> <pre><code>import copy x = SimpleClass() for count in range(0,4): y = copy.deepcopy(x) (...) y.attr1= '*Bob* '* count </code></pre> <p>A deepcopy is a recursive copy of the entire object. For more reference, you can have a look at the python documentation: <a href="https://docs.python.org/2/library/copy.html" rel="nofollow">https://docs.python.org/2/library/copy.html</a></p>
3
2008-12-07T22:25:21Z
[ "python", "list", "object", "loops" ]
Creating a list of objects in Python
348,196
<p>I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.</p> <p>I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...</p> <p>Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over. </p> <p>So how do you write objects to a list within a loop?</p> <p>Thanks,</p> <p>Bob J</p> <p>Here's my simplified code</p> <pre><code>class SimpleClass(object): pass x = SimpleClass # Then create an empty list simpleList = [] #Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass for count in range(0,4): # each iteration creates a slightly different attribute value, and then prints it to # prove that step is working # but the problem is, I'm always updating a reference to 'x' and what I want to add to # simplelist is a new instance of x that contains the updated attribute x.attr1= '*Bob* '* count print "Loop Count: %s Attribute Value %s" % (count, x.attr1) simpleList.append(x) print '-'*20 # And here I print out each instance of the object stored in the list 'simpleList' # and the problem surfaces. Every element of 'simpleList' contains the same attribute value y = SimpleClass print "Reading the attributes from the objects in the list" for count in range(0,4): y = simpleList[count] print y.attr1 </code></pre> <p>So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?</p>
42
2008-12-07T22:15:46Z
348,284
<p>It shouldn't be necessary to recreate the SimpleClass object each time, as some are suggesting, if you're simply using it to output data based on its attributes. However, you're not actually creating an instance of the class; you're simply creating a reference to the class object itself. Therefore, you're adding a reference to the same class attribute to the list (instead of instance attribute), over and over.</p> <p>Instead of:</p> <pre><code>x = SimpleClass </code></pre> <p>you need:</p> <pre><code>x = SimpleClass() </code></pre>
7
2008-12-07T23:06:58Z
[ "python", "list", "object", "loops" ]