title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Creating a doctype with lxml's etree
991,864
<p>I want to add doctypes to my XML documents that I'm generating with LXML's etree. </p> <p>However I cannot figure out how to add a doctype. Hardcoding and concating the string is not an option. </p> <p>I was expecting something along the lines of how PI's are added in etree:</p> <pre><code>pi = etree.PI(...) doc.addprevious(pi) </code></pre> <p>But it's not working for me. How to add a to a xml document with lxml?</p>
10
2009-06-14T00:41:05Z
1,099,484
<p>You can create your document with a doctype to begin with:</p> <pre><code># Adapted from example on http://codespeak.net/lxml/tutorial.html import lxml.etree as et import StringIO s = """&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;!DOCTYPE root SYSTEM "test" [ &lt;!ENTITY tasty "cheese"&gt; &lt;!ENTITY eacute "&amp;#233;"&gt; ]&gt; &lt;root&gt; &lt;a&gt;&amp;tasty; souffl&amp;eacute;&lt;/a&gt; &lt;/root&gt; """ tree = et.parse(StringIO.StringIO(s)) print et.tostring(tree, xml_declaration=True, encoding="utf-8") </code></pre> <p>prints:</p> <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;!DOCTYPE root SYSTEM "test" [ &lt;!ENTITY tasty "cheese"&gt; &lt;!ENTITY eacute "&amp;#233;"&gt; ]&gt; &lt;root&gt; &lt;a&gt;cheese soufflé&lt;/a&gt; &lt;/root&gt; </code></pre> <p>If you want to add a doctype to some XML that wasn't created with one, you can first create one with the desired doctype (as above), then copy your doctype-less XML into it:</p> <pre><code>xml = et.XML("&lt;root&gt;&lt;test/&gt;&lt;a&gt;whatever&lt;/a&gt;&lt;end_test/&gt;&lt;/root&gt;") root = tree.getroot() root[:] = xml root.text, root.tail = xml.text, xml.tail print et.tostring(tree, xml_declaration=True, encoding="utf-8") </code></pre> <p>prints:</p> <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;!DOCTYPE root SYSTEM "test" [ &lt;!ENTITY tasty "cheese"&gt; &lt;!ENTITY eacute "&amp;#233;"&gt; ]&gt; &lt;root&gt;&lt;test/&gt;&lt;a&gt;whatever&lt;/a&gt;&lt;end_test/&gt;&lt;/root&gt; </code></pre> <p>Is that what you're looking for?</p>
9
2009-07-08T17:33:40Z
[ "python", "doctype", "lxml", "elementtree" ]
Creating a doctype with lxml's etree
991,864
<p>I want to add doctypes to my XML documents that I'm generating with LXML's etree. </p> <p>However I cannot figure out how to add a doctype. Hardcoding and concating the string is not an option. </p> <p>I was expecting something along the lines of how PI's are added in etree:</p> <pre><code>pi = etree.PI(...) doc.addprevious(pi) </code></pre> <p>But it's not working for me. How to add a to a xml document with lxml?</p>
10
2009-06-14T00:41:05Z
2,858,690
<p>The PI is actually added as a previous element from "doc". Thus, it's not a child of "doc". You must use "doc.getroottree()"</p> <p>Here is an example:</p> <pre><code>&gt;&gt;&gt; root = etree.Element("root") &gt;&gt;&gt; a = etree.SubElement(root, "a") &gt;&gt;&gt; b = etree.SubElement(root, "b") &gt;&gt;&gt; root.addprevious(etree.PI('xml-stylesheet', 'type="text/xsl" href="my.xsl"')) &gt;&gt;&gt; print etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='utf-8') &lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;root&gt; &lt;a/&gt; &lt;b/&gt; &lt;/root&gt; </code></pre> <p>with getroottree():</p> <pre><code>&gt;&gt;&gt; print etree.tostring(root.getroottree(), pretty_print=True, xml_declaration=True, encoding='utf-8') &lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;?xml-stylesheet type="text/xsl" href="my.xsl"?&gt; &lt;root&gt; &lt;a/&gt; &lt;b/&gt; &lt;/root&gt; </code></pre>
4
2010-05-18T15:28:42Z
[ "python", "doctype", "lxml", "elementtree" ]
Creating a doctype with lxml's etree
991,864
<p>I want to add doctypes to my XML documents that I'm generating with LXML's etree. </p> <p>However I cannot figure out how to add a doctype. Hardcoding and concating the string is not an option. </p> <p>I was expecting something along the lines of how PI's are added in etree:</p> <pre><code>pi = etree.PI(...) doc.addprevious(pi) </code></pre> <p>But it's not working for me. How to add a to a xml document with lxml?</p>
10
2009-06-14T00:41:05Z
11,298,809
<p>This worked for me:</p> <p><code>print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="&lt;!DOCTYPE TEST_FILE&gt;")</code></p>
20
2012-07-02T18:02:36Z
[ "python", "doctype", "lxml", "elementtree" ]
Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad?
991,904
<p>I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil.</p>
158
2009-06-14T01:12:55Z
991,917
<p>Python (the language) doesn't need a GIL (which is why it can perfectly be implemented on JVM [Jython] and .NET [IronPython], and those implementations multithread freely). CPython (the popular implementation) has always used a GIL for ease of coding (esp. the coding of the garbage collection mechanisms) and of integration of non-thread-safe C-coded libraries (there used to be a ton of those around;-).</p> <p>The <a href="http://code.google.com/p/unladen-swallow/">Unladen Swallow</a> project, among other ambitious goals, does <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">plan</a> a GIL-free virtual machine for Python -- to quote that site, "In addition, we intend to remove the GIL and fix the state of multithreading in Python. We believe this is possible through the implementation of a more sophisticated GC system, something like IBM's Recycler (Bacon et al, 2001)."</p>
212
2009-06-14T01:20:55Z
[ "java", "python", "multithreading", "jvm", "gil" ]
Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad?
991,904
<p>I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil.</p>
158
2009-06-14T01:12:55Z
1,162,596
<p>The JVM (at least hotspot) does have a similar concept to the "GIL", it's just much finer in its lock granularity, most of this comes from the GC's in hotspot which are more advanced.</p> <p>In CPython it's one big lock (probably not that true, but good enough for arguments sake), in the JVM it's more spread about with different concepts depending on where it is used.</p> <p>Take a look at, for example, vm/runtime/safepoint.hpp in the hotspot code, which is effectively a barrier. Once at a safepoint the entire VM has stopped with regard to java code, much like the python VM stops at the GIL.</p> <p>In the Java world such VM pausing events are known as "stop-the-world", at these points only native code that is bound to certain criteria is free running, the rest of the VM has been stopped.</p> <p>Also the lack of a coarse lock in java makes JNI much more difficult to write, as the JVM makes less guarantees about its environment for FFI calls, one of the things that cpython makes fairly easy (although not as easy as using ctypes).</p>
41
2009-07-22T01:27:17Z
[ "java", "python", "multithreading", "jvm", "gil" ]
Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad?
991,904
<p>I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil.</p>
158
2009-06-14T01:12:55Z
2,625,688
<p>There is a comment down below in this blog post <a href="http://www.grouplens.org/node/244">http://www.grouplens.org/node/244</a> that hints at the reason why it was so easy dispense with a GIL for IronPython or Jython, it is that CPython uses reference counting whereas the other 2 VMs have garbage collectors.</p> <p>The exact mechanics of why this is so I don't get, but it does sounds like a plausible reason.</p>
6
2010-04-12T21:45:10Z
[ "java", "python", "multithreading", "jvm", "gil" ]
Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad?
991,904
<p>I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil.</p>
158
2009-06-14T01:12:55Z
37,918,400
<p>Python lacks jit/aot and the time frame it was written at multithreaded processors didn't exist. Alternatively you could recompile everything in Julia lang which lacks GIL and gain some speed boost on your Python code. Also Jython kind of sucks it's slower than Cpython and Java. If you want to stick to Python consider using parallel plugins, you won't gain an instant speed boost but you can do parallel programming with the right plugin.</p>
0
2016-06-20T09:00:57Z
[ "java", "python", "multithreading", "jvm", "gil" ]
Custom Filter in Django Admin on Django 1.3 or below
991,926
<p>How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this:</p> <pre><code>class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=False) byline_1 = models.CharField(max_length=4096, blank=True) dateline = models.DateTimeField(help_text=_("date/time that appears on article")) body_copy = models.TextField(blank=False) when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True) # HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!! def is_live(self): if self.when_to_publish is not None: if ( self.when_to_publish &lt; datetime.now() ): return """ &lt;img alt="True" src="/media/img/admin/icon-yes.gif"/&gt; """ else: return """ &lt;img alt="False" src="/media/img/admin/icon-no.gif"/&gt; """ is_live.allow_tags = True </code></pre> <p><hr /></p> <pre><code>class NewsItemAdmin(admin.ModelAdmin): form = NewsItemAdminForm list_display = ('headline', 'id', 'is_live') list_filter = ('is_live') # how can i make this work?? </code></pre>
66
2009-06-14T01:25:39Z
992,427
<p>You can't, unfortunately. Currently non-field items can not be used as list_filter entries.</p> <p>Note that your admin class wouldn't have worked even if it was a field, as a single-item tuple needs a comma: <code>('is_live',)</code></p>
3
2009-06-14T08:17:59Z
[ "python", "django", "django-admin" ]
Custom Filter in Django Admin on Django 1.3 or below
991,926
<p>How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this:</p> <pre><code>class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=False) byline_1 = models.CharField(max_length=4096, blank=True) dateline = models.DateTimeField(help_text=_("date/time that appears on article")) body_copy = models.TextField(blank=False) when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True) # HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!! def is_live(self): if self.when_to_publish is not None: if ( self.when_to_publish &lt; datetime.now() ): return """ &lt;img alt="True" src="/media/img/admin/icon-yes.gif"/&gt; """ else: return """ &lt;img alt="False" src="/media/img/admin/icon-no.gif"/&gt; """ is_live.allow_tags = True </code></pre> <p><hr /></p> <pre><code>class NewsItemAdmin(admin.ModelAdmin): form = NewsItemAdminForm list_display = ('headline', 'id', 'is_live') list_filter = ('is_live') # how can i make this work?? </code></pre>
66
2009-06-14T01:25:39Z
1,260,346
<p>you have to write a custom FilterSpec (not documentend anywhere). Look here for an example:</p> <p><a href="http://www.djangosnippets.org/snippets/1051/">http://www.djangosnippets.org/snippets/1051/</a></p>
22
2009-08-11T13:25:48Z
[ "python", "django", "django-admin" ]
Custom Filter in Django Admin on Django 1.3 or below
991,926
<p>How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this:</p> <pre><code>class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=False) byline_1 = models.CharField(max_length=4096, blank=True) dateline = models.DateTimeField(help_text=_("date/time that appears on article")) body_copy = models.TextField(blank=False) when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True) # HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!! def is_live(self): if self.when_to_publish is not None: if ( self.when_to_publish &lt; datetime.now() ): return """ &lt;img alt="True" src="/media/img/admin/icon-yes.gif"/&gt; """ else: return """ &lt;img alt="False" src="/media/img/admin/icon-no.gif"/&gt; """ is_live.allow_tags = True </code></pre> <p><hr /></p> <pre><code>class NewsItemAdmin(admin.ModelAdmin): form = NewsItemAdminForm list_display = ('headline', 'id', 'is_live') list_filter = ('is_live') # how can i make this work?? </code></pre>
66
2009-06-14T01:25:39Z
1,294,952
<p>Thanks to gpilotino for giving me the push into the right direction for implementing this.</p> <p>I noticed the question's code is using a datetime to figure out when its live . So I used the DateFieldFilterSpec and subclassed it.</p> <pre><code>from django.db import models from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec,DateFieldFilterSpec from django.utils.encoding import smart_unicode from django.utils.translation import ugettext as _ from datetime import datetime class IsLiveFilterSpec(DateFieldFilterSpec): """ Adds filtering by future and previous values in the admin filter sidebar. Set the is_live_filter filter in the model field attribute 'is_live_filter'. my_model_field.is_live_filter = True """ def __init__(self, f, request, params, model, model_admin): super(IsLiveFilterSpec, self).__init__(f, request, params, model, model_admin) today = datetime.now() self.links = ( (_('Any'), {}), (_('Yes'), {'%s__lte' % self.field.name: str(today), }), (_('No'), {'%s__gte' % self.field.name: str(today), }), ) def title(self): return "Is Live" # registering the filter FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_live_filter', False), IsLiveFilterSpec)) </code></pre> <p>To use you can put the above code into a filters.py, and import it in the model you want to add the filter to </p>
55
2009-08-18T16:19:35Z
[ "python", "django", "django-admin" ]
Custom Filter in Django Admin on Django 1.3 or below
991,926
<p>How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this:</p> <pre><code>class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=False) byline_1 = models.CharField(max_length=4096, blank=True) dateline = models.DateTimeField(help_text=_("date/time that appears on article")) body_copy = models.TextField(blank=False) when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True) # HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!! def is_live(self): if self.when_to_publish is not None: if ( self.when_to_publish &lt; datetime.now() ): return """ &lt;img alt="True" src="/media/img/admin/icon-yes.gif"/&gt; """ else: return """ &lt;img alt="False" src="/media/img/admin/icon-no.gif"/&gt; """ is_live.allow_tags = True </code></pre> <p><hr /></p> <pre><code>class NewsItemAdmin(admin.ModelAdmin): form = NewsItemAdminForm list_display = ('headline', 'id', 'is_live') list_filter = ('is_live') # how can i make this work?? </code></pre>
66
2009-06-14T01:25:39Z
6,355,234
<p>In current django development version there is the support for custom filters: <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter</a></p>
9
2011-06-15T08:52:52Z
[ "python", "django", "django-admin" ]
Custom Filter in Django Admin on Django 1.3 or below
991,926
<p>How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this:</p> <pre><code>class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=False) byline_1 = models.CharField(max_length=4096, blank=True) dateline = models.DateTimeField(help_text=_("date/time that appears on article")) body_copy = models.TextField(blank=False) when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True) # HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!! def is_live(self): if self.when_to_publish is not None: if ( self.when_to_publish &lt; datetime.now() ): return """ &lt;img alt="True" src="/media/img/admin/icon-yes.gif"/&gt; """ else: return """ &lt;img alt="False" src="/media/img/admin/icon-no.gif"/&gt; """ is_live.allow_tags = True </code></pre> <p><hr /></p> <pre><code>class NewsItemAdmin(admin.ModelAdmin): form = NewsItemAdminForm list_display = ('headline', 'id', 'is_live') list_filter = ('is_live') # how can i make this work?? </code></pre>
66
2009-06-14T01:25:39Z
7,712,970
<p>The user supplies goods to some countries postage free. I wanted to filter those countries: </p> <p><strong>All</strong> - all countries, <strong>Yes</strong> - postage free, <strong>No</strong> - charged postage.</p> <p>The main answer for this question did not work for me (Django 1.3) I think because there was no <code>field_path</code> parameter provided in the <code>__init__</code> method. Also it subclassed <code>DateFieldFilterSpec</code>. The <code>postage</code> field is a FloatField</p> <pre class="lang-py prettyprint-override"><code>from django.contrib.admin.filterspecs import FilterSpec class IsFreePostage(FilterSpec): def __init__(self, f, request, params, model, model_admin, field_path=None): super(IsFreePostage, self).__init__(f, request, params, model, model_admin, field_path) self.removes = { 'Yes': ['postage__gt'], 'No': ['postage__exact'], 'All': ['postage__exact', 'postage__gt'] } self.links = ( ('All', {}), ('Yes', {'postage__exact': 0}), ('No', {'postage__gt': 0})) if request.GET.has_key('postage__exact'): self.ttl = 'Yes' elif request.GET.has_key('postage__gt'): self.ttl = 'No' else: self.ttl = 'All' def choices(self, cl): for title, param_dict in self.links: yield {'selected': title == self.ttl, 'query_string': cl.get_query_string(param_dict, self.removes[title]), 'display': title} def title(self): return 'Free Postage' FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'free_postage', False), IsFreePostage)) </code></pre> <p>In self.links we supply dicts. used to construct HTTP query strings like <code>?postage__exact=0</code> for each of the possible filters. Filters <em>I think</em> are cumulative so if there was a previous request for 'No' and now we have a request for 'Yes' we have to remove the 'No' query. <code>self.removes</code> specifies what needs to be removed for each query. The <code>choices</code> method constructs the query strings, says which filter has been selected and sets the displayed name of the filter.</p>
2
2011-10-10T12:47:17Z
[ "python", "django", "django-admin" ]
Custom Filter in Django Admin on Django 1.3 or below
991,926
<p>How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this:</p> <pre><code>class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=False) byline_1 = models.CharField(max_length=4096, blank=True) dateline = models.DateTimeField(help_text=_("date/time that appears on article")) body_copy = models.TextField(blank=False) when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True) # HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!! def is_live(self): if self.when_to_publish is not None: if ( self.when_to_publish &lt; datetime.now() ): return """ &lt;img alt="True" src="/media/img/admin/icon-yes.gif"/&gt; """ else: return """ &lt;img alt="False" src="/media/img/admin/icon-no.gif"/&gt; """ is_live.allow_tags = True </code></pre> <p><hr /></p> <pre><code>class NewsItemAdmin(admin.ModelAdmin): form = NewsItemAdminForm list_display = ('headline', 'id', 'is_live') list_filter = ('is_live') # how can i make this work?? </code></pre>
66
2009-06-14T01:25:39Z
20,678,242
<p>Just a sidenote: You can use the deafult ticks on Django admin more easily like this:</p> <pre><code>def is_live(self): if self.when_to_publish is not None: if ( self.when_to_publish &lt; datetime.now() ): return True else: return False is_live.boolean = True </code></pre>
1
2013-12-19T09:49:29Z
[ "python", "django", "django-admin" ]
Custom Filter in Django Admin on Django 1.3 or below
991,926
<p>How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this:</p> <pre><code>class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=False) byline_1 = models.CharField(max_length=4096, blank=True) dateline = models.DateTimeField(help_text=_("date/time that appears on article")) body_copy = models.TextField(blank=False) when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True) # HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!! def is_live(self): if self.when_to_publish is not None: if ( self.when_to_publish &lt; datetime.now() ): return """ &lt;img alt="True" src="/media/img/admin/icon-yes.gif"/&gt; """ else: return """ &lt;img alt="False" src="/media/img/admin/icon-no.gif"/&gt; """ is_live.allow_tags = True </code></pre> <p><hr /></p> <pre><code>class NewsItemAdmin(admin.ModelAdmin): form = NewsItemAdminForm list_display = ('headline', 'id', 'is_live') list_filter = ('is_live') # how can i make this work?? </code></pre>
66
2009-06-14T01:25:39Z
25,359,657
<p>Not an optimal way (CPU-wise) but simple and will work, so I do it this way (for my small database). My Django version is 1.6.</p> <p>In admin.py:</p> <pre><code>class IsLiveFilter(admin.SimpleListFilter): title = 'Live' parameter_name = 'islive' def lookups(self, request, model_admin): return ( ('1', 'islive'), ) def queryset(self, request, queryset): if self.value(): array = [] for element in queryset: if element.is_live.__call__() == True: q_array.append(element.id) return queryset.filter(pk__in=q_array) </code></pre> <p>...</p> <pre><code>class NewsItemAdmin(admin.ModelAdmin): form = NewsItemAdminForm list_display = ('headline', 'id', 'is_live') list_filter = (IsLiveFilter) </code></pre> <p>Key idea here is to access custom fields in a QuerySet via <b>__call__()</b> function.</p>
2
2014-08-18T09:04:39Z
[ "python", "django", "django-admin" ]
What is this function doing in Python involving urllib2 and BeautifulSoup?
991,967
<p>So I asked a question earlier about retrieving high scores form an html page and another user gave me the following code to help. I am new to python and beautifulsoup so I'm trying to go through some other codes piece by piece. I understand most of it but I dont get what this piece of code is and what its function is:</p> <pre><code> def parse_string(el): text = ''.join(el.findAll(text=True)) return text.strip() </code></pre> <p>Here is the entire code:</p> <pre><code>from urllib2 import urlopen from BeautifulSoup import BeautifulSoup import sys URL = "http://hiscore.runescape.com/hiscorepersonal.ws?user1=" + sys.argv[1] # Grab page html, create BeatifulSoup object html = urlopen(URL).read() soup = BeautifulSoup(html) # Grab the &lt;table id="mini_player"&gt; element scores = soup.find('table', {'id':'mini_player'}) # Get a list of all the &lt;tr&gt;s in the table, skip the header row rows = scores.findAll('tr')[1:] # Helper function to return concatenation of all character data in an element def parse_string(el): text = ''.join(el.findAll(text=True)) return text.strip() for row in rows: # Get all the text from the &lt;td&gt;s data = map(parse_string, row.findAll('td')) # Skip the first td, which is an image data = data[1:] # Do something with the data... print data </code></pre>
1
2009-06-14T02:04:19Z
991,980
<p><code>el.findAll(text=True)</code> returns all the text contained within an element and its sub-elements. By text I mean everything not inside a tag; so in <code>&lt;b&gt;hello&lt;/b&gt;</code> then "hello" would be the text but <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> would not.</p> <p>That function therefore joins together all text found beneath the given element and strips whitespace off from the front and back.</p> <p>Here's a link to the <code>findAll</code> documentation: <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text</a></p>
3
2009-06-14T02:13:37Z
[ "python", "urllib2" ]
Why are 008 and 009 invalid keys for Python dicts?
991,978
<p>Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example:</p> <pre><code>some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } </code></pre> <p><strong>Update</strong>: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero? </p>
13
2009-06-14T02:12:20Z
991,983
<p>Python takes 008 and 009 as octal numbers, therefore...invalid.</p> <p>You can only go up to 007, then the next number would be 010 (8) then 011 (9). Try it in a Python interpreter, and you'll see what I mean.</p>
10
2009-06-14T02:16:19Z
[ "python", "dictionary", "python-2.x" ]
Why are 008 and 009 invalid keys for Python dicts?
991,978
<p>Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example:</p> <pre><code>some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } </code></pre> <p><strong>Update</strong>: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero? </p>
13
2009-06-14T02:12:20Z
991,984
<p>In Python (and many other languages), starting a number with <strong>a leading "0"</strong> indicates an <strong>octal number</strong> (base 8). Using this leading-zero notation is called an <strong>octal literal</strong>. Octal numbers go 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, etc. So <strong>08 (in octal) is invalid</strong>.</p> <p>If you remove the leading zeros, your code will be fine:</p> <pre><code>some_dict = { 1: "spam", 2: "eggs", 3: "foo", 4: "bar", 8: "anything", 9: "nothing" } </code></pre>
8
2009-06-14T02:16:33Z
[ "python", "dictionary", "python-2.x" ]
Why are 008 and 009 invalid keys for Python dicts?
991,978
<p>Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example:</p> <pre><code>some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } </code></pre> <p><strong>Update</strong>: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero? </p>
13
2009-06-14T02:12:20Z
991,985
<p>In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where only 0-7 are valid digits. You'll have to change your code to this:</p> <pre><code>some_dict = { 1: "spam", 2: "eggs", 3: "foo", 4: "bar", 8: "anything", 9: "nothing" } </code></pre> <p>Or if the leading zeros are really important, use strings for the keys.</p>
28
2009-06-14T02:16:52Z
[ "python", "dictionary", "python-2.x" ]
Why are 008 and 009 invalid keys for Python dicts?
991,978
<p>Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example:</p> <pre><code>some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } </code></pre> <p><strong>Update</strong>: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero? </p>
13
2009-06-14T02:12:20Z
991,986
<p>@<a href="#991983" rel="nofollow">DoxaLogos</a> is right. It's not that they're invalid keys - they're invalid literals. If you tried to use them in any other context, you'd get the same error.</p>
7
2009-06-14T02:17:12Z
[ "python", "dictionary", "python-2.x" ]
Why are 008 and 009 invalid keys for Python dicts?
991,978
<p>Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example:</p> <pre><code>some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } </code></pre> <p><strong>Update</strong>: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero? </p>
13
2009-06-14T02:12:20Z
991,988
<p>That is because, when you start a number with a <code>0</code>, it is interpreted as an octal number. Since <code>008</code> and <code>009</code> are not octal numbers, it fails.</p> <p>A <code>0</code> precedes an octal number so that you do not have to write <code>(127)₈</code>. From the <a href="http://en.wikipedia.org/wiki/Octal#In%5Fcomputers" rel="nofollow">Wikipedia page</a>: <em>"Sometimes octal numbers are represented by preceding a value with a 0 (e.g. in Python 2.x or JavaScript 1.x - although it is now deprecated in both)."</em></p>
2
2009-06-14T02:17:38Z
[ "python", "dictionary", "python-2.x" ]
Can client side python use threads?
992,008
<p>I have never programed in Python before, so excuse my code. I have this script that will run in a terminal but I can't get it to run client side. I am running this in Appcelerator's Titanium application. Anyway, I have been troubleshooting it and it seems that it isn't running the threads at all. Is this a limitation? does anyone know?</p> <pre><code>&lt;script type="text/python"&gt; import os import sys import Queue import threading class FindThread ( threading.Thread ): def run ( self ): running = True while running: if jobPool.empty(): #print '&lt;&lt; CLOSING THREAD' running = False continue job = jobPool.get() window.document.getElementById('output').innerHTML += os.path.join(top, name) if job != None: dirSearch(job) jobPool = Queue.Queue ( 0 ) def findPython(): #output = window.document.getElementById('output') window.document.getElementById('output').innerHTML += "Starting" dirSearch("/") # Start 10 threads: for x in xrange ( 10 ): #print '&gt;&gt; OPENING THREAD' FindThread().start() def dirSearch(top = "."): import os, stat, types names = os.listdir(top) for name in names: try: st = os.lstat(os.path.join(top, name)) except os.error: continue if stat.S_ISDIR(st.st_mode): jobPool.put( os.path.join(top, name) ) else: window.document.getElementById('output').innerHTML += os.path.join(top, name) window.findPython = findPython &lt;/script&gt; </code></pre>
0
2009-06-14T02:29:04Z
1,020,770
<p>The answer, currently (Friday, June 19th, 2009) is yes, it can run threads, but the nothing but the main thread can access JavaScript objects, this includes the DOM. so if you are planning on updating the UI with a threading app, this is not possible... YET. Until the Appcelerator team creates some sort of queue to the main thread, possible via a binding system. </p> <p>Please see discussion at the <a href="http://support.appcelerator.net/discussions/titanium-desktop-discussion/7-python-threads-in-titanium" rel="nofollow">appcelerator forums</a>.</p>
2
2009-06-20T02:19:48Z
[ "python", "multithreading", "client-side", "titanium", "appcelerator" ]
Building a Python shared object binding with cmake, which depends upon external libraries
992,068
<p>We have a c file called dbookpy.c, which will provide a Python binding some C functions.</p> <p>Next we decided to build a proper .so with cmake, but it seems we are doing something wrong with regards to linking the external library 'libdbook' in the binding:</p> <p>The CMakeLists.txt is as follows:</p> <pre><code>PROJECT(dbookpy) FIND_PACKAGE(PythonInterp) FIND_PACKAGE(PythonLibs) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) INCLUDE_DIRECTORIES("/usr/local/include") LINK_DIRECTORIES(/usr/local/lib) OPTION(BUILD_SHARED_LIBS "turn OFF for .a libs" ON) ADD_LIBRARY(dbookpy dbookpy) SET_TARGET_PROPERTIES(dbookpy PROPERTIES IMPORTED_LINK_INTERFACE_LIBRARIES dbook) SET_TARGET_PROPERTIES(dbookpy PROPERTIES LINKER_LANGUAGE C) #SET_TARGET_PROPERTIES(dbookpy PROPERTIES LINK_INTERFACE_LIBRARIES dbook) #SET_TARGET_PROPERTIES(dbookpy PROPERTIES ENABLE_EXPORTS ON) #TARGET_LINK_LIBRARIES(dbookpy LINK_INTERFACE_LIBRARIES dbook) SET_TARGET_PROPERTIES(dbookpy PROPERTIES SOVERSION 0.1 VERSION 0.1 ) </code></pre> <p>Then we build:</p> <pre><code>x31% mkdir build x31% cd build x31% cmake .. -- Check for working C compiler: /usr/bin/gcc -- Check for working C compiler: /usr/bin/gcc -- works -- Check size of void* -- Check size of void* - done -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Configuring done -- Generating done -- Build files have been written to: /home/edd/dbook2/dbookpy/build x31% make Scanning dependencies of target dbookpy [100%] Building C object CMakeFiles/dbookpy.dir/dbookpy.o Linking C shared library libdbookpy.so [100%] Built target dbookpy </code></pre> <p>So far so good. Test in Python:</p> <pre><code>x31% python Python 2.5.4 (r254:67916, Apr 24 2009, 15:28:40) [GCC 3.3.5 (propolice)] on openbsd4 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import libdbookpy python:./libdbookpy.so: undefined symbol 'dbook_isbn_13_to_10' python:./libdbookpy.so: undefined symbol 'dbook_isbn_10_to_13' python:./libdbookpy.so: undefined symbol 'dbook_sanitize' python:./libdbookpy.so: undefined symbol 'dbook_check_isbn' python:./libdbookpy.so: undefined symbol 'dbook_get_isbn_details' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: Cannot load specified object </code></pre> <p>Hmmm. Linker error. Looks like it is not linking libdbook:</p> <pre><code>x31% ldd libdbookpy.so libdbookpy.so: Start End Type Open Ref GrpRef Name 05ae8000 25aec000 dlib 1 0 0 /home/edd/dbook2/dbookpy/build/libdbookpy.so.0.1 </code></pre> <p>No it is not. A proper linkage to libdbook looks like this:</p> <pre><code>x31% ldd /usr/local/bin/dbook-test /usr/local/bin/dbook-test: Start End Type Open Ref GrpRef Name 1c000000 3c004000 exe 1 0 0 /usr/local/bin/dbook-test 08567000 28571000 rlib 0 2 0 /usr/lib/libm.so.5.0 09ef7000 29efb000 rlib 0 1 0 /usr/local/lib/libdbook.so.0.1 053a0000 253d8000 rlib 0 1 0 /usr/lib/libc.so.50.1 0c2bc000 0c2bc000 rtld 0 1 0 /usr/libexec/ld.so </code></pre> <p>Does anyone have any ideas why this is not working?</p> <p>Many thanks.</p> <p>Edd</p>
5
2009-06-14T03:22:59Z
994,760
<p>You need to link dbookpy against dbook:</p> <pre><code>target_link_libraries(dbookpy dbook) </code></pre> <p>Adding that just after the line <code>ADD_LIBRARY(dbookpy dbookpy)</code> should do it.</p> <p>I see you are using IMPORTED - the help for <code>IMPORTED_LINK_INTERFACE_LIBRARIES</code> reads:</p> <pre><code> Lists libraries whose interface is included when an IMPORTED library target is linked to another target. The libraries will be included on the link line for the target. Unlike the LINK_INTERFACE_LIBRARIES property, this property applies to all imported target types, including STATIC libraries. This property is ignored for non-imported targets. </code></pre> <p>So that means that "dbook", which is in /usr/local/lib, should be an imported library:</p> <pre><code> add_library(dbook SHARED IMPORTED) </code></pre> <p>Is that really what you wanted? I mean, imported libraries are ones that are built outside CMake but are included as part of your source tree. The dbook library seems to be installed or at least expected to be installed. I don't think you need imports here - it seems to be a regular linkage problem. But this may just be a side effect of creating a minimal example to post here.</p> <p>By the sounds of it, in order to get the linked libraries and link directories sorted out, I would probably use <code>find_library()</code>, which will look in sensible default places like /usr/local/lib, and then append that to the link libraries.</p> <pre><code>find_library(DBOOK_LIBRARY dbook REQUIRED) target_link_libraries(dbookpy ${DBOOK_LIBRARY}) </code></pre> <p>Anyway, seems like you have it sorted now.</p>
3
2009-06-15T06:44:20Z
[ "python", "c", "unix", "linker", "cmake" ]
Building a Python shared object binding with cmake, which depends upon external libraries
992,068
<p>We have a c file called dbookpy.c, which will provide a Python binding some C functions.</p> <p>Next we decided to build a proper .so with cmake, but it seems we are doing something wrong with regards to linking the external library 'libdbook' in the binding:</p> <p>The CMakeLists.txt is as follows:</p> <pre><code>PROJECT(dbookpy) FIND_PACKAGE(PythonInterp) FIND_PACKAGE(PythonLibs) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) INCLUDE_DIRECTORIES("/usr/local/include") LINK_DIRECTORIES(/usr/local/lib) OPTION(BUILD_SHARED_LIBS "turn OFF for .a libs" ON) ADD_LIBRARY(dbookpy dbookpy) SET_TARGET_PROPERTIES(dbookpy PROPERTIES IMPORTED_LINK_INTERFACE_LIBRARIES dbook) SET_TARGET_PROPERTIES(dbookpy PROPERTIES LINKER_LANGUAGE C) #SET_TARGET_PROPERTIES(dbookpy PROPERTIES LINK_INTERFACE_LIBRARIES dbook) #SET_TARGET_PROPERTIES(dbookpy PROPERTIES ENABLE_EXPORTS ON) #TARGET_LINK_LIBRARIES(dbookpy LINK_INTERFACE_LIBRARIES dbook) SET_TARGET_PROPERTIES(dbookpy PROPERTIES SOVERSION 0.1 VERSION 0.1 ) </code></pre> <p>Then we build:</p> <pre><code>x31% mkdir build x31% cd build x31% cmake .. -- Check for working C compiler: /usr/bin/gcc -- Check for working C compiler: /usr/bin/gcc -- works -- Check size of void* -- Check size of void* - done -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Configuring done -- Generating done -- Build files have been written to: /home/edd/dbook2/dbookpy/build x31% make Scanning dependencies of target dbookpy [100%] Building C object CMakeFiles/dbookpy.dir/dbookpy.o Linking C shared library libdbookpy.so [100%] Built target dbookpy </code></pre> <p>So far so good. Test in Python:</p> <pre><code>x31% python Python 2.5.4 (r254:67916, Apr 24 2009, 15:28:40) [GCC 3.3.5 (propolice)] on openbsd4 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import libdbookpy python:./libdbookpy.so: undefined symbol 'dbook_isbn_13_to_10' python:./libdbookpy.so: undefined symbol 'dbook_isbn_10_to_13' python:./libdbookpy.so: undefined symbol 'dbook_sanitize' python:./libdbookpy.so: undefined symbol 'dbook_check_isbn' python:./libdbookpy.so: undefined symbol 'dbook_get_isbn_details' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: Cannot load specified object </code></pre> <p>Hmmm. Linker error. Looks like it is not linking libdbook:</p> <pre><code>x31% ldd libdbookpy.so libdbookpy.so: Start End Type Open Ref GrpRef Name 05ae8000 25aec000 dlib 1 0 0 /home/edd/dbook2/dbookpy/build/libdbookpy.so.0.1 </code></pre> <p>No it is not. A proper linkage to libdbook looks like this:</p> <pre><code>x31% ldd /usr/local/bin/dbook-test /usr/local/bin/dbook-test: Start End Type Open Ref GrpRef Name 1c000000 3c004000 exe 1 0 0 /usr/local/bin/dbook-test 08567000 28571000 rlib 0 2 0 /usr/lib/libm.so.5.0 09ef7000 29efb000 rlib 0 1 0 /usr/local/lib/libdbook.so.0.1 053a0000 253d8000 rlib 0 1 0 /usr/lib/libc.so.50.1 0c2bc000 0c2bc000 rtld 0 1 0 /usr/libexec/ld.so </code></pre> <p>Does anyone have any ideas why this is not working?</p> <p>Many thanks.</p> <p>Edd</p>
5
2009-06-14T03:22:59Z
997,615
<p>Thanks for your help.</p> <p>You are correct to say that IMPORTED is probably not needed. Adding LINK_LIBRARIES(dbookpy dbook) indeed adds -ldbook to the gcc execution, so thats great.</p> <p>However cmake appears to ignore LINK_DIRECTORIES, and so never finds -ldbook:</p> <pre><code>/usr/bin/gcc -fPIC -shared -o libdbookpy.so.0.1 "CMakeFiles/dbookpy.dir/dbookpy.o" -ldbook /usr/bin/ld: cannot find -ldbook </code></pre> <p>Here is the CMakeList as it stands:</p> <pre><code>PROJECT(dbookpy) SET(CMAKE_VERBOSE_MAKEFILE ON) OPTION(BUILD_SHARED_LIBS "turn OFF for .a libs" ON) ADD_LIBRARY(dbookpy dbookpy) SET_TARGET_PROPERTIES(dbookpy PROPERTIES LINKER_LANGUAGE C) FIND_PACKAGE(PythonInterp) FIND_PACKAGE(PythonLibs) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) INCLUDE_DIRECTORIES(/usr/local/include) target_link_libraries(dbookpy dbook) LINK_DIRECTORIES("/usr/local/lib") SET_TARGET_PROPERTIES(dbookpy PROPERTIES SOVERSION 0.1 VERSION 0.1 ) INSTALL(TARGETS dbookpy LIBRARY DESTINATION lib ) </code></pre> <p>Any ideas?</p>
2
2009-06-15T18:33:50Z
[ "python", "c", "unix", "linker", "cmake" ]
Transform game pseudo code into python
992,076
<p>Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.</p> <p>Pseudocode </p> <pre><code>- Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries </code></pre> <p>I need some serious help! I don't understand any of this stuff at all! This is all I have </p> <pre><code>def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main() </code></pre> <p>and I don't even know if it's right!</p>
1
2009-06-14T03:28:29Z
992,092
<p>You're obviously very new to programming, and I guess that is one of the reasons for a delayed response from the community. It's tough to decide where to start and how to guide you through this whole exercise.</p> <p>So, before you get a good answer here that includes making you understand what's happening there, and guiding you through building the solution yourself (ideally!) I would suggest you visit this page to try to get a grasp of the actual problem itself.</p> <p><a href="http://www.openbookproject.net/pybiblio/gasp/course/4-highlow.html" rel="nofollow">http://www.openbookproject.net/pybiblio/gasp/course/4-highlow.html</a></p> <p>In the meantime, look at all the answers in this thread and keep editing your post so that we know you're getting it.</p>
4
2009-06-14T03:37:02Z
[ "python", "pseudocode" ]
Transform game pseudo code into python
992,076
<p>Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.</p> <p>Pseudocode </p> <pre><code>- Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries </code></pre> <p>I need some serious help! I don't understand any of this stuff at all! This is all I have </p> <pre><code>def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main() </code></pre> <p>and I don't even know if it's right!</p>
1
2009-06-14T03:28:29Z
992,098
<p>Okay, the nice part about using Python is that it's almost pseudocode anyway.</p> <p>Now, let's think about the individual steps:</p> <ol> <li><p>How do you get the average between high and low?</p></li> <li><p>How do you ask the user if the answerr is correct</p></li> <li><p>What do "if" statements look like in Python, and how would you write the pseudocode out as if statements?</p></li> </ol> <p>Here's another hint -- you can run python as an interpreter and try individual statements along, so, for example, you could do</p> <pre><code>high=23 low=7 </code></pre> <p>then compute what you think should be the average or midpoint between them (hint: 15)</p>
1
2009-06-14T03:42:48Z
[ "python", "pseudocode" ]
Transform game pseudo code into python
992,076
<p>Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.</p> <p>Pseudocode </p> <pre><code>- Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries </code></pre> <p>I need some serious help! I don't understand any of this stuff at all! This is all I have </p> <pre><code>def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main() </code></pre> <p>and I don't even know if it's right!</p>
1
2009-06-14T03:28:29Z
992,100
<blockquote> <p>I don't understand any of this stuff at all!</p> </blockquote> <p>That's pretty problematic, but, fine, let's do one step at a time! Your homework assignment begins:</p> <blockquote> <p>Print instructions to the user</p> </blockquote> <p>So you don't understand ANY of the stuff, you say, so that means you don't understand this part either. Well: "the user" is the person who's running your program. "Instructions" are English sentences that tell him or her what to do to play the game, as per the following quote from this excellently clear and detailed assignment:</p> <blockquote> <p>The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries.</p> </blockquote> <p>"<code>print</code>" is a Python instruction that emits information; for example, try a program containing only</p> <pre><code>print "some information" </code></pre> <p>to see how it works. OK, can you please edit your answer to show us that you've gotten this point, so we can move to the next one? Feel free to comment here with further questions if any words or concepts I'm using are still too advanced for you, and I'll try to clarify!</p>
11
2009-06-14T03:43:10Z
[ "python", "pseudocode" ]
Transform game pseudo code into python
992,076
<p>Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.</p> <p>Pseudocode </p> <pre><code>- Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries </code></pre> <p>I need some serious help! I don't understand any of this stuff at all! This is all I have </p> <pre><code>def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main() </code></pre> <p>and I don't even know if it's right!</p>
1
2009-06-14T03:28:29Z
992,153
<p>Before thinking about how to implement this in python (or any language) lets look at the pseudocode, which looks like a pretty good plan to solve the problem. </p> <p>I would guess that one thing you might be getting stuck on is the way the pseudocode references <strong>variables</strong>, like <code>high</code> and <code>low</code>. The way to understand variables is to consider them slots that values can be stored. At any given time, a variable has some value, like the number 5, or a reference to an open file. That value can be summoned at any time by using its name, or it can be given a new value by assigning to it, and the old value will be forgotten with the new value taking its place. </p> <p>The pseudocode references three variables, <code>high</code>, <code>low</code> and <code>tries</code>. It also tells you what their initial values should be. After the second line has executed, those values are set to 1000, 1 and 1, respectively, but they take on new values as the program progresses.</p> <p>Another feature of the pseudocode is a conditional loop, and a case analysis of the user input. Your translation of the pseudocode's loop is incorrect. In your case, you have created a new variable, <code>i</code> and have instructed your program to run the loop body with every value of i between 1 and 1000. Obviously this doesn't have a whole lot to do with the pseudocode. </p> <p>Instead what you want to do is loop forever, until some condition (which changes in the loop body) becomes false. In python, the <code>while</code> statement does this. If you're familiar with an <code>if</code> statement, <code>while</code> looks the same, but after the body is done, the condition is re-evaluated and the body is executed again if it is still true. </p> <p>Finally, the case analysis in the body of the loop requires comparing something to expected values. Although some other languages have a number of ways of expressing this, in python we only have <code>if</code>-<code>elif</code>-<code>else</code> clauses. </p> <p><hr /></p> <p>Outside of transforming pseudocode to working code, it is probably useful to understand what the program is actually doing. The key here is on line 4, where the program guesses the average of two values. after that the program acts on how well the guess worked out. </p> <p>In the first run through the loop, with <code>high</code> containing 1000 and <code>low</code> containing 1, the average is 500 (actually the average is 500.5, but since we're averaging whole numbers, python guesses that we want the result of the division to also be an integer). Obviously that guess has only a 0.1% chance of being right, but if it's wrong, the user is expected to tell us if it was too high, or too low. Either way, that answer completely eliminates 50% of the possible guesses. </p> <p>If, for instance, the user was thinking of a low number, then when the program guessed 500, the user would tell the program that 500 was too high, and then the program wouldn't ever have to guess that the number was in the range of 501 thru 1000. That can save the computer a lot of work. </p> <p>To put that information to use, the program keeps track of the range of possible values the goal number could be. When the number guessed is too high, the program adjusts its upper bound downward, just below the guess, and if the guess was too low, the program adjusts its lower bound upward to just above the guess.</p> <p>When the program guesses again, the guess is right in the middle of the possible range, cutting the range in half again. The number of possible guesses went from the original 1000 to 500 in one guess, to 250 in two guesses. If the program has terrible luck, and can't get it two (which is actually pretty likely), then by the third, it has only 125 numbers left to worry about. After the fourth guess, only 62 numbers remain in range. This continues, and after eight guesses, only 3 numbers remain, and the program tries the middle number for its ninth guess. If that turns out to be wrong, only one number is left, and the program guesses it!</p> <p>This technique of splitting a range in half and then continuing to the closer half is called <strong>bisection</strong> and appears in a wide range topics of interest to computer science. </p> <p><hr /></p> <p>How about some CODE! Since i don't want to deprive you of the learning experience, I'll just give you some snippets that might help you along. python is a language designed for interactive exploration, so fire up your interpreter and give this a shot. I'll be posting examples with the prompts shown, don't actually type that. </p> <p>Here's an example using the <code>while</code> clause: </p> <pre><code>&gt;&gt;&gt; x = 1000 &gt;&gt;&gt; while x &gt; 1: ... x = x/2 ... print x ... 500 250 125 62 31 15 7 3 1 &gt;&gt;&gt; x 1 </code></pre> <p>Getting console input from the user should be done through the <code>raw_input()</code> function. It just returns whatever the user types. This is a little harder to show. To simplify things, after every line of python that requires input, I'll type "Hello World!" (without the quotes)</p> <pre><code>&gt;&gt;&gt; raw_input() Hello World! 'Hello World!' &gt;&gt;&gt; y = raw_input() Hello World! &gt;&gt;&gt; print y Hello World! &gt;&gt;&gt; </code></pre> <p>How about some combining of concepts!</p> <pre><code>&gt;&gt;&gt; myvar = '' &gt;&gt;&gt; while myvar != 'exit': ... myvar = raw_input() ... if myvar == 'apples': ... print "I like apples" ... elif myvar == 'bananas': ... print "I don't like bananas" ... else: ... print "I've never eaten", myvar ... apples I like apples mangoes I've never eaten mangoes bananas I don't like bananas exit I've never eaten exit &gt;&gt;&gt; </code></pre> <p>Oops. little bit of a bug there. See if you can fix it!</p>
14
2009-06-14T04:17:12Z
[ "python", "pseudocode" ]
Transform game pseudo code into python
992,076
<p>Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.</p> <p>Pseudocode </p> <pre><code>- Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries </code></pre> <p>I need some serious help! I don't understand any of this stuff at all! This is all I have </p> <pre><code>def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main() </code></pre> <p>and I don't even know if it's right!</p>
1
2009-06-14T03:28:29Z
992,161
<p>Here's a few hints to get you started:</p> <p>Average = Value + Value + Value [...] / Number of Values; (for instance, ((2 + 5 + 3) / (3))</p> <p>Many programming languages use different operator precedence. When I am programming, I always use parentheses when I am unsure about operator precedence. In my example above, if you only did 2 + 5 + 3 / 3, the program would do division operations before addition - so it would evaulate to 2 + 5 + (3 / 3), or 2 + 5 + 1 == 7.</p> <p>Skip this for python users /* Secondly: your earliest programs can benefit from const correctness (<a href="http://www.parashift.com/c%2B%2B-faq-lite/const-correctness.html" rel="nofollow">here</a> is a good explanation of what it is and why it is EXTREMELY good practice). Please read through that and understand why you should use constants (or whatever the python equivalent is). Also look up "magic numbers," which is a big area where constants are used. */</p> <p>Google "Please Excuse My Dear Aunt Sally" (NOTE: this only deals with mathematical operators, and mostly holds true for programming languages; for a more comprehensive study of operator precedence, look up your chosen language's documentation for precedence - also note that most programs don't have built in power operators, but most standard libraries have pow functions).</p> <p>Speaking of standard library: Get acquainted with standard library functions (I have never used Python, I don't know how it implements a SL, but I would be extremely surprised if a language that popular didn't have a well developed SL). If you don't know what that is, and your book/tutorial doesn't have it, get a new one. Any resource that doesn't reference a standard library is not worth the time. </p> <p>Lastly: while this post may look like I know what I'm talking about, I really am still in the early phases of learning, just like you. A few things you might want to get used to early on (when I skipped these parts, it slowed my learning a lot): The use of references and pointers (Q for comments: does Python have pointers?), the difference between the data IN a memory location and the actual memory location (often times, the location of the value in memory will be more useful than the value itself, at least when writing data structures). Especially get used to the standard library; look for copy, find, etc. type functions useful in string manipulation. </p> <p>Actually, rereading your original post, I did not realize this was a homework type assignment. If you aren't doing this for fun, you will probably never take my advice. Just remember that programming can be extremely fun, if you don't make it a chore - and don't get frustrated when your code doesn't compile (or...interpret), or you get unexpected results, etc. </p>
0
2009-06-14T04:24:41Z
[ "python", "pseudocode" ]
Transform game pseudo code into python
992,076
<p>Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.</p> <p>Pseudocode </p> <pre><code>- Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries </code></pre> <p>I need some serious help! I don't understand any of this stuff at all! This is all I have </p> <pre><code>def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main() </code></pre> <p>and I don't even know if it's right!</p>
1
2009-06-14T03:28:29Z
992,278
<p>Welcome to Stack Overflow!</p> <p>The trick here is to realize that your Python program should look almost like the pseudocode.</p> <p>First let's try to understand exactly what the pseudocode is doing. If we had to interact with the program described by the pseudocode, it would look something like this:</p> <pre><code>Think of a number between 1 and 1000 and press Enter. &gt;&gt;&gt; Is it 500? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher. &gt;&gt;&gt; 1 Is it 750? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher. &gt;&gt;&gt; -1 Is it 625? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher. </code></pre> <p>etc.</p> <p>When we first think of our number, the program knows only that it is between 1 and 1000. It represents this knowledge by setting the variable 'low' to 1 and the variable 'high' to 1000. Its first guess is the average of these numbers, which is 500.</p> <p>After we tell the program that our number is greater than 500, it updates the value of 'low' to 501. In other words the program then knows that our number is between 501 and 1000. It then guesses the average of 501 and 1000, which is 750. We tell it that our number is lower, so the program updates the value of 'high' to 749 and guesses the average of 501 and 749 next, and so on until it guesses right, or it has narrowed the possible range down to a single number (meaning its next guess will be right).</p> <p>So back to writing the program in Python: We basically just translate the pseudocode line for line. For example our program loop should look just like it does in the pseucode:</p> <pre><code>while high &gt; low: # Guess (high + low) / 2 and ask user to respond # Handle user response </code></pre> <p>There is no need for a for-loop as you have in your code.</p> <p>To take input we can do something like this:</p> <pre><code>guess = (high + low) / 2 response = input('Is it ' + str(guess) + '? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.') </code></pre> <p>Now the user input is stored in the variable 'response', and we can handle the possibilities with if statements like 'if response == -1:' for example.</p> <p>Just remember to print the instructions and set 'high' and 'low' to their initial values before entering the while loop and you should be all set.</p> <p>Good luck!</p>
1
2009-06-14T05:59:19Z
[ "python", "pseudocode" ]
Transform game pseudo code into python
992,076
<p>Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.</p> <p>Pseudocode </p> <pre><code>- Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries </code></pre> <p>I need some serious help! I don't understand any of this stuff at all! This is all I have </p> <pre><code>def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main() </code></pre> <p>and I don't even know if it's right!</p>
1
2009-06-14T03:28:29Z
3,795,131
<p>Doesn't match the psudocode exactly but it works. lol ;)</p> <p>I know this is a wicked old post but this is the same assignment I got also. Here is what I ended up with:</p> <pre><code>high = 1000 low = 1 print "Pick a number between 1 and 1000." print "I will guess your number in 10 tries or less." print "Or at least i'll try to. ;)" print "My first guess is 500." guess = 500 tries = 0 answer = 1 print "Enter 1 if it's higher." print "Enter -1 if it's lower." print "Enter 0 if I guessed it!" print "" while (answer != 0): answer = int(raw_input("Am I close?")) if answer == 1: tries = tries + 1 low = guess guess = (high + low) / 2 print "My next guess is:" print guess elif answer == -1: tries = tries + 1 high = guess guess = (high + low) / 2 print "My next guess is:" print guess elif answer == 0: tries = tries + 1 print "Your number is:" print guess print "Yay! I got it! Number of guesses:" print tries </code></pre>
2
2010-09-25T19:02:28Z
[ "python", "pseudocode" ]
Does running separate python processes avoid the GIL?
992,136
<p>I'm curious in how the Global Interpreter Lock in python actually works. If I have a c++ application launch four separate instances of a python script will they run in parallel on separate cores, or does the GIL go even deeper then just the single process that was launched and control all python process's regardless of the process that spawned it? </p>
8
2009-06-14T04:07:08Z
992,141
<p>The GIL only affects threads within a single process. The <code>multiprocessing</code> module is in fact an alternative to <code>threading</code> that lets Python programs use multiple cores &amp;c. Your scenario will easily allow use of multiple cores, too.</p>
16
2009-06-14T04:09:11Z
[ "python" ]
Does running separate python processes avoid the GIL?
992,136
<p>I'm curious in how the Global Interpreter Lock in python actually works. If I have a c++ application launch four separate instances of a python script will they run in parallel on separate cores, or does the GIL go even deeper then just the single process that was launched and control all python process's regardless of the process that spawned it? </p>
8
2009-06-14T04:07:08Z
993,191
<p>As Alex Martelli points out you can indeed avoid the GIL by running multiple processes, I just want to add and point out that the GIL is a limitation of the implementation (CPython) and not of Python in general, it's possible to implement Python without this limitation. <a href="http://www.stackless.com/" rel="nofollow">Stackless Python</a> comes to mind.</p>
1
2009-06-14T16:49:48Z
[ "python" ]
Which reactor should i use for qt4?
992,169
<p>I am using twisted and now i want to make some pretty ui using qt</p>
3
2009-06-14T04:31:19Z
992,199
<p>You need a <code>qt4reactor</code>, for example <a href="http://twistedmatrix.com/trac/browser/sandbox/therve/qt4reactor.py?rev=22736" rel="nofollow">this one</a> (but that's a sandbox and thus <strong>not</strong> good for production use -- tx @Glyph for clarifying this!).</p> <p>As @Glyph says, the proper one to use is <a href="https://launchpad.net/qt4reactor" rel="nofollow">the one at launchpad</a>.</p>
4
2009-06-14T04:49:01Z
[ "python", "qt4", "twisted" ]
Which reactor should i use for qt4?
992,169
<p>I am using twisted and now i want to make some pretty ui using qt</p>
3
2009-06-14T04:31:19Z
996,006
<p>You want to use Glen Tarbox's <a href="https://launchpad.net/qt4reactor">qt4reactor</a>.</p>
5
2009-06-15T13:06:39Z
[ "python", "qt4", "twisted" ]
Why am I getting "'ResultSet' has no attribute 'findAll'" using BeautifulSoup in Python?
992,183
<p>So I am learning Python slowly, and am trying to make a simple function that will draw data from the high scores page of an online game. This is someone else's code that i rewrote into one function (which might be the problem), but I am getting this error. Here is the code:</p> <pre><code>&gt;&gt;&gt; from urllib2 import urlopen &gt;&gt;&gt; from BeautifulSoup import BeautifulSoup &gt;&gt;&gt; def create(el): source = urlopen(el).read() soup = BeautifulSoup(source) get_table = soup.find('table', {'id':'mini_player'}) get_rows = get_table.findAll('tr') text = ''.join(get_rows.findAll(text=True)) data = text.strip() return data &gt;&gt;&gt; create('http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13') Traceback (most recent call last): File "&lt;pyshell#18&gt;", line 1, in &lt;module&gt; create('http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13') File "&lt;pyshell#17&gt;", line 6, in create text = ''.join(get_rows.findAll(text=True)) AttributeError: 'ResultSet' object has no attribute 'findAll' </code></pre> <p>Thanks in advance.</p>
7
2009-06-14T04:41:27Z
992,291
<p>Wow. Triptych provided a <a href="http://stackoverflow.com/questions/989872/how-do-i-draw-out-specific-data-from-an-opened-url-in-python-using-urllib2/989920#989920"><em>great</em> answer</a> to a related question.</p> <p>We can see, <a href="http://code.google.com/p/google-blog-converters-appengine/source/browse/trunk/lib/BeautifulSoup.py">from BeautifulSoup's source code</a>, that <code>ResultSet</code> subclasses <a href="http://docs.python.org/tutorial/datastructures.html#more-on-lists"><code>list</code></a>.</p> <p>In your example, <code>get_rows</code> is an instance of BS's <code>ResultSet</code> class, <br /> and since BS's <code>ResultSet</code> subclasses <code>list</code>, that means <strong>get_rows is a list</strong>.</p> <p><code>get_rows</code>, as an instance of <code>ResultSet</code>, does <strong>not</strong> have a <code>findAll</code> method implemented; hence your error. <br /> What Triptych has done differently is to <strong>iterate</strong> over that list. <br /> Triptych's method works because the items in the <code>get_rows</code> list are instances of BS's Tag class; which has a <code>findAll</code> method.</p> <p>So, to fix your code, you could replace the last three lines of your <code>create</code> method with something like this:</p> <pre><code>for row in get_rows: text = ''.join(row.findAll(text=True)) data = text.strip() print data </code></pre> <p>Note to Leonard Richardson: in no way do I intend to demean the quality of your work by referring to it as BS ;-)</p>
18
2009-06-14T06:17:16Z
[ "python", "urllib2", "beautifulsoup" ]
django for loop counter break
992,230
<p>This is hopefully a quick/easy one. I know a way to work around this via a custom template tag, but I was curious if there were other methods I was over looking. I've created a gallery function of sorts for my blog, and I have a gallery list page that paginates all my galleries. Now, I don't want to show all the photos of each gallery in that list, since if each gallery even has 20 images, then that's 100 images on a page if I paginate at 5 posts. That'd be wasteful, and the wrong way to go about things.</p> <p>The question I have is, is there a way to just display 3 photos from the photo set? What I'd like to do, but I don't <em>think</em> is possible is something like (pseudocode):</p> <pre><code>{% for photos in gallery.photo_set %} {% if forloop.counter lt 3 %} &lt;img src="{{ photos.url }}"&gt; {% endif %} {% endfor %} </code></pre> <p>Judging from the documentation, unless I'm completely missing it, that's not possible via the templating system. Hence, I can just write my own template tag of sorts to work around it. I could probably do something from the view aspect, but I haven't looked to far into that idea. The other option I have is giving the model a preview field, and allow the user to select the photos they want in the preview field. </p> <p>Anyways, a few different options, so I thought I'd poll the audience to see how you'd do it. Any opinion is appreciated. Personally, enjoying that there's numerous ways to skin this cat.</p>
25
2009-06-14T05:15:53Z
992,243
<p>Use:</p> <pre><code>{% for photos in gallery.photo_set|slice:":3" %} </code></pre>
64
2009-06-14T05:32:19Z
[ "python", "django", "for-loop" ]
django for loop counter break
992,230
<p>This is hopefully a quick/easy one. I know a way to work around this via a custom template tag, but I was curious if there were other methods I was over looking. I've created a gallery function of sorts for my blog, and I have a gallery list page that paginates all my galleries. Now, I don't want to show all the photos of each gallery in that list, since if each gallery even has 20 images, then that's 100 images on a page if I paginate at 5 posts. That'd be wasteful, and the wrong way to go about things.</p> <p>The question I have is, is there a way to just display 3 photos from the photo set? What I'd like to do, but I don't <em>think</em> is possible is something like (pseudocode):</p> <pre><code>{% for photos in gallery.photo_set %} {% if forloop.counter lt 3 %} &lt;img src="{{ photos.url }}"&gt; {% endif %} {% endfor %} </code></pre> <p>Judging from the documentation, unless I'm completely missing it, that's not possible via the templating system. Hence, I can just write my own template tag of sorts to work around it. I could probably do something from the view aspect, but I haven't looked to far into that idea. The other option I have is giving the model a preview field, and allow the user to select the photos they want in the preview field. </p> <p>Anyways, a few different options, so I thought I'd poll the audience to see how you'd do it. Any opinion is appreciated. Personally, enjoying that there's numerous ways to skin this cat.</p>
25
2009-06-14T05:15:53Z
992,548
<p>This is better done in the <code>gallery.photo_set</code> collection. The hard-coded "3" in the template is a bad idea in the long run.</p> <pre><code>class Gallery( object ): def photo_subset( self ): return Photo.objects.filter( gallery_id = self.id )[:3] </code></pre> <p>In your view function, you can do things like pick 3 random photos, or the 3 most recent photos.</p> <pre><code> def photo_recent( self ): return Photo.objects.filter( gallery_id = self.id ).orderby( someDate )[:3] def photo_random( self ): pix = Photo.objects.filter( gallery_id = self.id ).all() random.shuffle(pix) return pix[:3] </code></pre>
1
2009-06-14T09:53:24Z
[ "python", "django", "for-loop" ]
Determining Letter Frequency Of Cipher Text
992,408
<p>I am trying to make a tool that finds the frequencies of letters in some type of cipher text. Lets suppose it is all lowercase a-z no numbers. The encoded message is in a txt file</p> <p>I am trying to build a script to help in cracking of substitution or possibly transposition ciphers.</p> <p>Code so far:</p> <pre><code>cipher = open('cipher.txt','U').read() cipherfilter = cipher.lower() cipherletters = list(cipherfilter) alpha = list('abcdefghijklmnopqrstuvwxyz') occurrences = {} for letter in alpha: occurrences[letter] = cipherfilter.count(letter) for letter in occurrences: print letter, occurrences[letter] </code></pre> <p>All it does so far is show how many times a letter appears. How would I print the frequency of all letters found in this file.</p>
4
2009-06-14T08:07:04Z
992,417
<pre><code>import collections d = collections.defaultdict(int) for c in 'test': d[c] += 1 print d # defaultdict(&lt;type 'int'&gt;, {'s': 1, 'e': 1, 't': 2}) </code></pre> <p>From a file:</p> <pre><code>myfile = open('test.txt') for line in myfile: line = line.rstrip('\n') for c in line: d[c] += 1 </code></pre> <p>For the genius that is the <a href="http://docs.python.org/library/collections.html#collections.defaultdict">defaultdict</a> container, we must give thanks and praise. Otherwise we'd all be doing something silly like this: </p> <pre><code>s = "andnowforsomethingcompletelydifferent" d = {} for letter in s: if letter not in d: d[letter] = 1 else: d[letter] += 1 </code></pre>
17
2009-06-14T08:12:00Z
[ "python", "encryption", "cryptography" ]
Determining Letter Frequency Of Cipher Text
992,408
<p>I am trying to make a tool that finds the frequencies of letters in some type of cipher text. Lets suppose it is all lowercase a-z no numbers. The encoded message is in a txt file</p> <p>I am trying to build a script to help in cracking of substitution or possibly transposition ciphers.</p> <p>Code so far:</p> <pre><code>cipher = open('cipher.txt','U').read() cipherfilter = cipher.lower() cipherletters = list(cipherfilter) alpha = list('abcdefghijklmnopqrstuvwxyz') occurrences = {} for letter in alpha: occurrences[letter] = cipherfilter.count(letter) for letter in occurrences: print letter, occurrences[letter] </code></pre> <p>All it does so far is show how many times a letter appears. How would I print the frequency of all letters found in this file.</p>
4
2009-06-14T08:07:04Z
992,463
<p>If you want to know the <a href="http://en.wikipedia.org/wiki/Relative%5Ffrequency" rel="nofollow">relative frequency</a> of a letter c, you would have to divide number of occurrences of c by the length of the input.</p> <p>For instance, taking Adam's example:</p> <pre><code>s = "andnowforsomethingcompletelydifferent" n = len(s) # n = 37 </code></pre> <p>and storing the absolute frequence of each letter in </p> <pre><code>dict[letter] </code></pre> <p>we obtain the relative frequencies by:</p> <pre><code>from string import ascii_lowercase # this is "a...z" for c in ascii_lowercase: print c, dict[c]/float(n) </code></pre> <p>putting it all together, we get something like this:</p> <pre><code># get input s = "andnowforsomethingcompletelydifferent" n = len(s) # n = 37 # get absolute frequencies of letters import collections dict = collections.defaultdict(int) for c in s: dict[c] += 1 # print relative frequencies from string import ascii_lowercase # this is "a...z" for c in ascii_lowercase: print c, dict[c]/float(n) </code></pre>
2
2009-06-14T08:50:10Z
[ "python", "encryption", "cryptography" ]
Determining Letter Frequency Of Cipher Text
992,408
<p>I am trying to make a tool that finds the frequencies of letters in some type of cipher text. Lets suppose it is all lowercase a-z no numbers. The encoded message is in a txt file</p> <p>I am trying to build a script to help in cracking of substitution or possibly transposition ciphers.</p> <p>Code so far:</p> <pre><code>cipher = open('cipher.txt','U').read() cipherfilter = cipher.lower() cipherletters = list(cipherfilter) alpha = list('abcdefghijklmnopqrstuvwxyz') occurrences = {} for letter in alpha: occurrences[letter] = cipherfilter.count(letter) for letter in occurrences: print letter, occurrences[letter] </code></pre> <p>All it does so far is show how many times a letter appears. How would I print the frequency of all letters found in this file.</p>
4
2009-06-14T08:07:04Z
25,826,941
<p>The modern way:</p> <pre><code>from collections import Counter string = "ihavesometextbutidontmindsharing" Counter(string) #&gt;&gt;&gt; Counter({'i': 4, 't': 4, 'e': 3, 'n': 3, 's': 2, 'h': 2, 'm': 2, 'o': 2, 'a': 2, 'd': 2, 'x': 1, 'r': 1, 'u': 1, 'b': 1, 'v': 1, 'g': 1}) </code></pre>
6
2014-09-13T19:38:28Z
[ "python", "encryption", "cryptography" ]
Create zip archive for instant download
992,621
<p>In a web app I am working on, the user can create a zip archive of a folder full of files. Here here's the code:</p> <pre><code>files = torrent[0].files zipfile = z.ZipFile(zipname, 'w') output = "" for f in files: zipfile.write(settings.PYRAT_TRANSMISSION_DOWNLOAD_DIR + "/" + f.name, f.name) downloadurl = settings.PYRAT_DOWNLOAD_BASE_URL + "/" + settings.PYRAT_ARCHIVE_DIR + "/" + filename output = "Download &lt;a href=\"" + downloadurl + "\"&gt;" + torrent_name + "&lt;/a&gt;" return HttpResponse(output) </code></pre> <p>But this has the nasty side effect of a long wait (10+ seconds) while the zip archive is being downloaded. Is it possible to skip this? Instead of saving the archive to a file, is it possible to send it straight to the user?</p> <p>I do beleive that torrentflux provides this excat feature I am talking about. Being able to zip GBs of data and download it within a second.</p>
5
2009-06-14T10:42:32Z
992,628
<p>Check this <a href="http://stackoverflow.com/questions/67454/serving-dynamically-generated-zip-archives-in-django">Serving dynamically generated ZIP archives in Django</a></p>
11
2009-06-14T10:47:16Z
[ "python", "django", "zip", "archive" ]
Create zip archive for instant download
992,621
<p>In a web app I am working on, the user can create a zip archive of a folder full of files. Here here's the code:</p> <pre><code>files = torrent[0].files zipfile = z.ZipFile(zipname, 'w') output = "" for f in files: zipfile.write(settings.PYRAT_TRANSMISSION_DOWNLOAD_DIR + "/" + f.name, f.name) downloadurl = settings.PYRAT_DOWNLOAD_BASE_URL + "/" + settings.PYRAT_ARCHIVE_DIR + "/" + filename output = "Download &lt;a href=\"" + downloadurl + "\"&gt;" + torrent_name + "&lt;/a&gt;" return HttpResponse(output) </code></pre> <p>But this has the nasty side effect of a long wait (10+ seconds) while the zip archive is being downloaded. Is it possible to skip this? Instead of saving the archive to a file, is it possible to send it straight to the user?</p> <p>I do beleive that torrentflux provides this excat feature I am talking about. Being able to zip GBs of data and download it within a second.</p>
5
2009-06-14T10:42:32Z
992,637
<p>Does the zip library you are using allow for output to a stream. You could stream directly to the user instead of temporarily writing to a zip file THEN streaming to the user.</p>
2
2009-06-14T10:57:08Z
[ "python", "django", "zip", "archive" ]
Create zip archive for instant download
992,621
<p>In a web app I am working on, the user can create a zip archive of a folder full of files. Here here's the code:</p> <pre><code>files = torrent[0].files zipfile = z.ZipFile(zipname, 'w') output = "" for f in files: zipfile.write(settings.PYRAT_TRANSMISSION_DOWNLOAD_DIR + "/" + f.name, f.name) downloadurl = settings.PYRAT_DOWNLOAD_BASE_URL + "/" + settings.PYRAT_ARCHIVE_DIR + "/" + filename output = "Download &lt;a href=\"" + downloadurl + "\"&gt;" + torrent_name + "&lt;/a&gt;" return HttpResponse(output) </code></pre> <p>But this has the nasty side effect of a long wait (10+ seconds) while the zip archive is being downloaded. Is it possible to skip this? Instead of saving the archive to a file, is it possible to send it straight to the user?</p> <p>I do beleive that torrentflux provides this excat feature I am talking about. Being able to zip GBs of data and download it within a second.</p>
5
2009-06-14T10:42:32Z
1,080,707
<p>Here's a simple Django view function which zips up (as an example) any readable files in <code>/tmp</code> and returns the zip file.</p> <pre><code>from django.http import HttpResponse import zipfile import os from cStringIO import StringIO # caveats for Python 3.0 apply def somezip(request): file = StringIO() zf = zipfile.ZipFile(file, mode='w', compression=zipfile.ZIP_DEFLATED) for fn in os.listdir("/tmp"): path = os.path.join("/tmp", fn) if os.path.isfile(path): try: zf.write(path) except IOError: pass zf.close() response = HttpResponse(file.getvalue(), mimetype="application/zip") response['Content-Disposition'] = 'attachment; filename=yourfiles.zip' return response </code></pre> <p>Of course this approach will only work if the zip files will conveniently fit into memory - if not, you'll have to use a disk file (which you're trying to avoid). In that case, you just replace the <code>file = StringIO()</code> with <code>file = open('/path/to/yourfiles.zip', 'wb')</code> and replace the <code>file.getvalue()</code> with code to read the contents of the disk file.</p>
4
2009-07-03T20:16:18Z
[ "python", "django", "zip", "archive" ]
Create zip archive for instant download
992,621
<p>In a web app I am working on, the user can create a zip archive of a folder full of files. Here here's the code:</p> <pre><code>files = torrent[0].files zipfile = z.ZipFile(zipname, 'w') output = "" for f in files: zipfile.write(settings.PYRAT_TRANSMISSION_DOWNLOAD_DIR + "/" + f.name, f.name) downloadurl = settings.PYRAT_DOWNLOAD_BASE_URL + "/" + settings.PYRAT_ARCHIVE_DIR + "/" + filename output = "Download &lt;a href=\"" + downloadurl + "\"&gt;" + torrent_name + "&lt;/a&gt;" return HttpResponse(output) </code></pre> <p>But this has the nasty side effect of a long wait (10+ seconds) while the zip archive is being downloaded. Is it possible to skip this? Instead of saving the archive to a file, is it possible to send it straight to the user?</p> <p>I do beleive that torrentflux provides this excat feature I am talking about. Being able to zip GBs of data and download it within a second.</p>
5
2009-06-14T10:42:32Z
1,103,491
<p>It is possible to pass an iterator to the constructor of a HttpResponse <a href="http://docs.djangoproject.com/en/dev/ref/request-response/?from=olddocs#passing-iterators" rel="nofollow">(see docs)</a>. That would allow you to create a custom iterator that generates data as it is being requested. However I don't think that will work with a zip (you would have to send partial zip as it is being created).</p> <p>The proper way, I think, would be to create the files offline, in a separate process. The user could then monitor the progress and then download the file when its ready (possibly by using the iterator method described above). This would be similar what sites like youtube use when you upload a file and wait for it to be processed.</p>
0
2009-07-09T12:19:50Z
[ "python", "django", "zip", "archive" ]
Create zip archive for instant download
992,621
<p>In a web app I am working on, the user can create a zip archive of a folder full of files. Here here's the code:</p> <pre><code>files = torrent[0].files zipfile = z.ZipFile(zipname, 'w') output = "" for f in files: zipfile.write(settings.PYRAT_TRANSMISSION_DOWNLOAD_DIR + "/" + f.name, f.name) downloadurl = settings.PYRAT_DOWNLOAD_BASE_URL + "/" + settings.PYRAT_ARCHIVE_DIR + "/" + filename output = "Download &lt;a href=\"" + downloadurl + "\"&gt;" + torrent_name + "&lt;/a&gt;" return HttpResponse(output) </code></pre> <p>But this has the nasty side effect of a long wait (10+ seconds) while the zip archive is being downloaded. Is it possible to skip this? Instead of saving the archive to a file, is it possible to send it straight to the user?</p> <p>I do beleive that torrentflux provides this excat feature I am talking about. Being able to zip GBs of data and download it within a second.</p>
5
2009-06-14T10:42:32Z
9,829,044
<p>As mandrake says, constructor of HttpResponse accepts iterable objects. </p> <p>Luckily, ZIP format is such that archive can be created in single pass, central directory record is located at the very end of file:</p> <p><img src="http://i.stack.imgur.com/sQMBQ.jpg" alt="enter image description here"></p> <p>(Picture from <a href="http://en.wikipedia.org/wiki/Zip_%28file_format%29#Structure">Wikipedia</a>)</p> <p>And luckily, <code>zipfile</code> indeed doesn't do any seeks as long as you only add files.</p> <p>Here is the code I came up with. Some notes:</p> <ul> <li>I'm using this code for zipping up a bunch of JPEG pictures. There is no point <em>compressing</em> them, I'm using ZIP only as container. </li> <li>Memory usage is O(size_of_largest_file) not O(size_of_archive). And this is good enough for me: many relatively small files that add up to potentially huge archive</li> <li>This code doesn't set Content-Length header, so user doesn't get nice progress indication. It <em>should be possible</em> to calculate this in advance if sizes of all files are known.</li> <li>Serving the ZIP straight to user like this means that resume on downloads won't work. </li> </ul> <p>So, here goes:</p> <pre><code>import zipfile class ZipBuffer(object): """ A file-like object for zipfile.ZipFile to write into. """ def __init__(self): self.data = [] self.pos = 0 def write(self, data): self.data.append(data) self.pos += len(data) def tell(self): # zipfile calls this so we need it return self.pos def flush(self): # zipfile calls this so we need it pass def get_and_clear(self): result = self.data self.data = [] return result def generate_zipped_stream(): sink = ZipBuffer() archive = zipfile.ZipFile(sink, "w") for filename in ["file1.txt", "file2.txt"]: archive.writestr(filename, "contents of file here") for chunk in sink.get_and_clear(): yield chunk archive.close() # close() generates some more data, so we yield that too for chunk in sink.get_and_clear(): yield chunk def my_django_view(request): response = HttpResponse(generate_zipped_stream(), mimetype="application/zip") response['Content-Disposition'] = 'attachment; filename=archive.zip' return response </code></pre>
7
2012-03-22T19:19:18Z
[ "python", "django", "zip", "archive" ]
How to setup twill for python 2.6 on Windows?
992,638
<p>I have already downloaded twill 0.9. Also, I have installed easy_install for python 2.6. Now I'm stuck with twill installation. Could you help me to settle the problem? </p>
0
2009-06-14T10:57:27Z
992,642
<p>Something like:</p> <pre><code>easy_install twill </code></pre> <p>It assumes you have easy_install in your PATH, which is the case on unix, but not on windows. On windows, the easy_install script can be found in C:\Python25\Scripts</p>
2
2009-06-14T11:00:26Z
[ "python" ]
How to setup twill for python 2.6 on Windows?
992,638
<p>I have already downloaded twill 0.9. Also, I have installed easy_install for python 2.6. Now I'm stuck with twill installation. Could you help me to settle the problem? </p>
0
2009-06-14T10:57:27Z
992,645
<p>easiest way is to just unzip the twill and keep it somewhere in PYTHONPATH e.g. in your project and just import twill</p> <p>else copy twill folder directly to D:\Python26\Lib\site-packages</p>
1
2009-06-14T11:03:37Z
[ "python" ]
Writing text with diacritic ("nikud", vocalization marks) using PIL (Python Imaging Library)
993,265
<p>Writing simple text on an image using PIL is easy.</p> <pre><code>draw = ImageDraw.Draw(img) draw.text((10, y), text2, font=font, fill=forecolor ) </code></pre> <p>However, when I try to write Hebrew punctuation marks (called "nikud" or ניקוד), the characters do not overlap as they should. (I would guess this question is relevant also to Arabic and other similar languages.)</p> <p>On supporting environment, these two words take up the same space/width (the below example depends on your system, hence the image):</p> <p>סֶפֶר ספר</p> <p>However when drawing the text with PIL I get:</p> <p>ס ֶ פ ֶ ר</p> <p>since the library probably doesn't obey kerning(?) rules.</p> <p>Is it possible to have the character and Hebrew punctuation mark take up the same space/width without manually writing character positioning?</p> <p><img src="http://tinypic.com/r/jglhc5/5" alt="image - nikud and letter spacing"></p> <p>image url: <a href="http://tinypic.com/r/jglhc5/5" rel="nofollow">http://tinypic.com/r/jglhc5/5</a></p>
4
2009-06-14T17:28:14Z
994,091
<p>Looks to me that the case is quite simple. You can use True Type fonts and use</p> <p>Here's the example:<a href="http://www.leancrew.com/all-this/2008/11/truetype-fonts-for-the-python-imaging-library/" rel="nofollow">True type fonts for PIL</a></p> <p>Here you can find Hebrew True Type fonts: <a href="http://www.breslov.com/hebrew/" rel="nofollow">Hebrew true type fonts</a></p> <p>Good luck or like we saying in Hebrew - Mazal' Tov.</p>
0
2009-06-15T00:10:06Z
[ "python", "unicode", "fonts", "python-imaging-library", "hebrew" ]
Writing text with diacritic ("nikud", vocalization marks) using PIL (Python Imaging Library)
993,265
<p>Writing simple text on an image using PIL is easy.</p> <pre><code>draw = ImageDraw.Draw(img) draw.text((10, y), text2, font=font, fill=forecolor ) </code></pre> <p>However, when I try to write Hebrew punctuation marks (called "nikud" or ניקוד), the characters do not overlap as they should. (I would guess this question is relevant also to Arabic and other similar languages.)</p> <p>On supporting environment, these two words take up the same space/width (the below example depends on your system, hence the image):</p> <p>סֶפֶר ספר</p> <p>However when drawing the text with PIL I get:</p> <p>ס ֶ פ ֶ ר</p> <p>since the library probably doesn't obey kerning(?) rules.</p> <p>Is it possible to have the character and Hebrew punctuation mark take up the same space/width without manually writing character positioning?</p> <p><img src="http://tinypic.com/r/jglhc5/5" alt="image - nikud and letter spacing"></p> <p>image url: <a href="http://tinypic.com/r/jglhc5/5" rel="nofollow">http://tinypic.com/r/jglhc5/5</a></p>
4
2009-06-14T17:28:14Z
1,020,099
<p>What system are you working on? It works for me on my Gentoo system; the order of the letters is reversed (I just copy-pasted from your question), which seems correct to me although I don't know much about RTL languages.</p> <pre><code>Python 2.5.4 (r254:67916, May 31 2009, 16:56:01) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import Image as I, ImageFont as IF, ImageDraw as ID &gt;&gt;&gt; t= u"סֶפֶר ספר" &gt;&gt;&gt; t u'\u05e1\u05b6\u05e4\u05b6\u05e8 \u05e1\u05e4\u05e8' &gt;&gt;&gt; i= I.new("L", (200, 200)) &gt;&gt;&gt; d= ID.Draw(i) &gt;&gt;&gt; f= IF.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf", 20) &gt;&gt;&gt; d1.text( (100, 40), t, fill=255, font=f) &gt;&gt;&gt; i.save("/tmp/dummy.png", optimize=1) </code></pre> <p>produces:</p> <p><img src="http://i39.tinypic.com/2j9jxf.png" alt="the example text rendered as white on black" /></p> <p>EDIT: I should say that using the <code>Deja Vu Sans</code> font was not accidental; although I don't like it much (and yet I find its glyphs better than Arial), it's readable, it has extended Unicode coverage, and it seems to work better with many non-MS applications than <code>Arial Unicode MS</code>.</p>
2
2009-06-19T21:26:31Z
[ "python", "unicode", "fonts", "python-imaging-library", "hebrew" ]
Writing text with diacritic ("nikud", vocalization marks) using PIL (Python Imaging Library)
993,265
<p>Writing simple text on an image using PIL is easy.</p> <pre><code>draw = ImageDraw.Draw(img) draw.text((10, y), text2, font=font, fill=forecolor ) </code></pre> <p>However, when I try to write Hebrew punctuation marks (called "nikud" or ניקוד), the characters do not overlap as they should. (I would guess this question is relevant also to Arabic and other similar languages.)</p> <p>On supporting environment, these two words take up the same space/width (the below example depends on your system, hence the image):</p> <p>סֶפֶר ספר</p> <p>However when drawing the text with PIL I get:</p> <p>ס ֶ פ ֶ ר</p> <p>since the library probably doesn't obey kerning(?) rules.</p> <p>Is it possible to have the character and Hebrew punctuation mark take up the same space/width without manually writing character positioning?</p> <p><img src="http://tinypic.com/r/jglhc5/5" alt="image - nikud and letter spacing"></p> <p>image url: <a href="http://tinypic.com/r/jglhc5/5" rel="nofollow">http://tinypic.com/r/jglhc5/5</a></p>
4
2009-06-14T17:28:14Z
25,727,238
<p>As for <strong>Arabic</strong> diacritics : Python +<strong>Wand</strong>(Python Lib) +arabic_reshaper(Python Lib) +bidi.algorithme(Python Lib). The same applies to <strong>PIL/Pillow</strong>, you need to use the <code>arabic_reshaper</code> and <code>bidi.algorithm</code> and pass the generated text to <code>draw.text((10, 25), artext, font=font)</code>:</p> <pre><code>from wand.image import Image as wImage from wand.display import display as wdiplay from wand.drawing import Drawing from wand.color import Color import arabic_reshaper from bidi.algorithm import get_display reshaped_text = arabic_reshaper.reshape(u'لغةٌ عربيّة') artext = get_display(reshaped_text) fonts = ['C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\DroidNaskh-Bold.ttf', 'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\Thabit.ttf', 'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\Thabit-Bold-Oblique.ttf', 'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\Thabit-Bold.ttf', 'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\Thabit-Oblique.ttf', 'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\majalla.ttf', 'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\majallab.ttf', ] draw = Drawing() img = wImage(width=1200,height=(len(fonts)+2)*60,background=Color('#ffffff')) #draw.fill_color(Color('#000000')) draw.text_alignment = 'right'; draw.text_antialias = True draw.text_encoding = 'utf-8' #draw.text_interline_spacing = 1 #draw.text_interword_spacing = 15.0 draw.text_kerning = 0.0 for i in range(len(fonts)): font = fonts[i] draw.font = font draw.font_size = 40 draw.text(img.width / 2, 40+(i*60),artext) print draw.get_font_metrics(img,artext) draw(img) draw.text(img.width / 2, 40+((i+1)*60),u'ناصر test') draw(img) img.save(filename='C:\\PATH\\OUTPUT\\arabictest.png'.format(r)) wdiplay(img) </code></pre> <p><img src="http://i.stack.imgur.com/q4Ni3.png" alt="Arabic typography in images"></p>
3
2014-09-08T14:59:38Z
[ "python", "unicode", "fonts", "python-imaging-library", "hebrew" ]
Writing text with diacritic ("nikud", vocalization marks) using PIL (Python Imaging Library)
993,265
<p>Writing simple text on an image using PIL is easy.</p> <pre><code>draw = ImageDraw.Draw(img) draw.text((10, y), text2, font=font, fill=forecolor ) </code></pre> <p>However, when I try to write Hebrew punctuation marks (called "nikud" or ניקוד), the characters do not overlap as they should. (I would guess this question is relevant also to Arabic and other similar languages.)</p> <p>On supporting environment, these two words take up the same space/width (the below example depends on your system, hence the image):</p> <p>סֶפֶר ספר</p> <p>However when drawing the text with PIL I get:</p> <p>ס ֶ פ ֶ ר</p> <p>since the library probably doesn't obey kerning(?) rules.</p> <p>Is it possible to have the character and Hebrew punctuation mark take up the same space/width without manually writing character positioning?</p> <p><img src="http://tinypic.com/r/jglhc5/5" alt="image - nikud and letter spacing"></p> <p>image url: <a href="http://tinypic.com/r/jglhc5/5" rel="nofollow">http://tinypic.com/r/jglhc5/5</a></p>
4
2009-06-14T17:28:14Z
25,751,321
<p>funny, after 5 years, and with great help fron @Nasser Al-Wohaibi, I realized how to do it:</p> <p>Reversing the text with a BIDI algorithm was needed.</p> <pre><code># -*- coding: utf-8 -*- from bidi.algorithm import get_display import PIL.Image, PIL.ImageFont, PIL.ImageDraw img= PIL.Image.new("L", (400, 200)) draw = PIL.ImageDraw.Draw(img) font = PIL.ImageFont.truetype( r"c:\windows\fonts\arial.ttf", 30) t1 = u'סֶפֶר ספר!' draw.text( (10,10), 'before BiDi :' + t1, fill=255, font=font) t2 = get_display(t1) # &lt;--- here's the magic &lt;--- draw.text( (10,50), 'after BiDi: ' + t2, fill=220, font=font) img.save( 'bidi-test.png') </code></pre> <p>@Nasser's answer has extra value that's probably relevant only to arabic texts (the letters in arabic change shape and connected-ness based on their neiboring letters, in hebrew all letters are separate), so only the bidi part was relevant for this question.</p> <p>in the sample result, the 2nd line is the correct form, and correct vocalization marks positioning.</p> <p><img src="http://i.stack.imgur.com/axF7z.png" alt="before and after bidi"></p> <p>thank you @tzot for help + code snippets</p> <p>a-propos:</p> <p>samples of different font behavior with Hebrew "nikud". Not all fonts behave the same: <img src="http://i.stack.imgur.com/vUVFJ.png" alt="sample PIL written, bidi hebrew text, with nikud, in different fonts"></p>
0
2014-09-09T18:22:34Z
[ "python", "unicode", "fonts", "python-imaging-library", "hebrew" ]
Error while I use math.atan in Python!
993,274
<p>When I do <code>1/2</code> in Python why does it give me zero? Even if I coerce it with <code>float(1/2)</code> still I get zero. Why? And how can I get around it?</p> <p>When I give <code>arctan(1/2)</code> I get 0 as answer, but when I give <code>arctan(.5)</code> I get the correct answer!</p>
0
2009-06-14T17:34:19Z
993,275
<pre><code>float(1)/float(2) </code></pre> <p>If you divide int / int you get an int, so float(0) still gives you 0.0</p>
2
2009-06-14T17:36:09Z
[ "python" ]
Error while I use math.atan in Python!
993,274
<p>When I do <code>1/2</code> in Python why does it give me zero? Even if I coerce it with <code>float(1/2)</code> still I get zero. Why? And how can I get around it?</p> <p>When I give <code>arctan(1/2)</code> I get 0 as answer, but when I give <code>arctan(.5)</code> I get the correct answer!</p>
0
2009-06-14T17:34:19Z
993,276
<pre><code>atan(float(1)/2) </code></pre> <p>If you do: </p> <pre><code>atan(float(1/2)) </code></pre> <p>in Python 2.x, but without:</p> <pre><code>from __future__ import division </code></pre> <p>the 1/2 is evaluated first as 0, then 0 is converted to a float, then atan(0.0) is called. This changes in Python 3, which uses float division by default even for integers. The short portable solution is what I first gave.</p>
3
2009-06-14T17:36:51Z
[ "python" ]
Error while I use math.atan in Python!
993,274
<p>When I do <code>1/2</code> in Python why does it give me zero? Even if I coerce it with <code>float(1/2)</code> still I get zero. Why? And how can I get around it?</p> <p>When I give <code>arctan(1/2)</code> I get 0 as answer, but when I give <code>arctan(.5)</code> I get the correct answer!</p>
0
2009-06-14T17:34:19Z
993,281
<p>From the standard:</p> <p>The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result.</p>
2
2009-06-14T17:38:13Z
[ "python" ]
Error while I use math.atan in Python!
993,274
<p>When I do <code>1/2</code> in Python why does it give me zero? Even if I coerce it with <code>float(1/2)</code> still I get zero. Why? And how can I get around it?</p> <p>When I give <code>arctan(1/2)</code> I get 0 as answer, but when I give <code>arctan(.5)</code> I get the correct answer!</p>
0
2009-06-14T17:34:19Z
993,283
<p>Because Python 2.x uses integer division for integers, so:</p> <pre><code>1/2 == 0 </code></pre> <p>evaluates to True.</p> <p>You want to do:</p> <pre><code>1.0/2 </code></pre> <p>or do a</p> <pre><code>from __future__ import division </code></pre>
7
2009-06-14T17:38:55Z
[ "python" ]
Error while I use math.atan in Python!
993,274
<p>When I do <code>1/2</code> in Python why does it give me zero? Even if I coerce it with <code>float(1/2)</code> still I get zero. Why? And how can I get around it?</p> <p>When I give <code>arctan(1/2)</code> I get 0 as answer, but when I give <code>arctan(.5)</code> I get the correct answer!</p>
0
2009-06-14T17:34:19Z
993,284
<p>As these answers are implying, 1/2 doesn't return what you are expecting. It returns zero, because 1 and 2 are integers (integer division causes numbers to round down). Python 3 changes this behavior, by the way.</p>
1
2009-06-14T17:38:56Z
[ "python" ]
Error while I use math.atan in Python!
993,274
<p>When I do <code>1/2</code> in Python why does it give me zero? Even if I coerce it with <code>float(1/2)</code> still I get zero. Why? And how can I get around it?</p> <p>When I give <code>arctan(1/2)</code> I get 0 as answer, but when I give <code>arctan(.5)</code> I get the correct answer!</p>
0
2009-06-14T17:34:19Z
993,285
<p>Your coercing doesn't stand a chance because the answer is already zero before you hand it to float.</p> <p>Try 1./2</p>
1
2009-06-14T17:39:00Z
[ "python" ]
Error while I use math.atan in Python!
993,274
<p>When I do <code>1/2</code> in Python why does it give me zero? Even if I coerce it with <code>float(1/2)</code> still I get zero. Why? And how can I get around it?</p> <p>When I give <code>arctan(1/2)</code> I get 0 as answer, but when I give <code>arctan(.5)</code> I get the correct answer!</p>
0
2009-06-14T17:34:19Z
993,288
<p>In Python, dividing integers yields an integer -- 0 in this case.</p> <p>There are two possible solutions. One is to force them into floats: 1/2. (note the trailing dot) or float(1)/2.</p> <p>Another is to use "from <strong>future</strong> import division" at the top of your code, and use the behavior you need.</p> <p>python -c 'from <strong>future</strong> import division;import math;print math.atan(1/2)' yields the correct 0.463647609001</p>
1
2009-06-14T17:39:20Z
[ "python" ]
Error while I use math.atan in Python!
993,274
<p>When I do <code>1/2</code> in Python why does it give me zero? Even if I coerce it with <code>float(1/2)</code> still I get zero. Why? And how can I get around it?</p> <p>When I give <code>arctan(1/2)</code> I get 0 as answer, but when I give <code>arctan(.5)</code> I get the correct answer!</p>
0
2009-06-14T17:34:19Z
993,293
<p>If 1/2 == 0 then float(1/2) will be 0.0. If you coerce it to float after it's been truncated it'll still be truncated.</p> <p>There are a few options:</p> <ul> <li>Add the following import: <code>from __future__ import division</code>. This will make the / operator divide "correctly" in that module. You can use // if you need truncating division.</li> <li>Coerce either of the operands to a float. eg: <code>float(1)/2</code></li> <li>If you're actually using constants then just add a decimal point instead of using float(), eg: <code>1.0/2</code> or <code>1/2.0</code> or <code>1.0/2.0</code></li> </ul>
1
2009-06-14T17:41:00Z
[ "python" ]
Error while I use math.atan in Python!
993,274
<p>When I do <code>1/2</code> in Python why does it give me zero? Even if I coerce it with <code>float(1/2)</code> still I get zero. Why? And how can I get around it?</p> <p>When I give <code>arctan(1/2)</code> I get 0 as answer, but when I give <code>arctan(.5)</code> I get the correct answer!</p>
0
2009-06-14T17:34:19Z
993,343
<p>First, <code>1/2</code> is integer division. Until Python 3.0.</p> <pre><code>&gt;&gt;&gt; 1/2 0 &gt;&gt;&gt; 1.0/2.0 0.5 &gt;&gt;&gt; </code></pre> <p>Second, use <code>math.atan2</code> for this kind of thing.</p> <pre><code>&gt;&gt;&gt; math.atan2(1,2) 0.46364760900080609 &gt;&gt;&gt; math.atan(.5) 0.46364760900080609 </code></pre>
6
2009-06-14T17:59:05Z
[ "python" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
993,367
<p>Marginally better...</p> <pre><code>base = datetime.datetime.today() date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)] </code></pre>
188
2009-06-14T18:06:32Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
993,369
<p>You can write a generator function that returns date objects starting from today:</p> <pre><code>import datetime def date_generator(): from_date = datetime.datetime.today() while True: yield from_date from_date = from_date - datetime.timedelta(days=1) </code></pre> <p>This generator returns dates starting from today and going backwards one day at a time. Here is how to take the first 3 dates:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; dates = itertools.islice(date_generator(), 3) &gt;&gt;&gt; list(dates) [datetime.datetime(2009, 6, 14, 19, 12, 21, 703890), datetime.datetime(2009, 6, 13, 19, 12, 21, 703890), datetime.datetime(2009, 6, 12, 19, 12, 21, 703890)] </code></pre> <p>The advantage of this approach over a loop or list comprehension is that you can go back as many times as you want.</p> <p><strong>Edit</strong></p> <p>A more compact version using a generator expression instead of a function:</p> <pre><code>date_generator = (datetime.datetime.today() - datetime.timedelta(days=i) for i in itertools.count()) </code></pre> <p>Usage:</p> <pre><code>&gt;&gt;&gt; dates = itertools.islice(date_generator, 3) &gt;&gt;&gt; list(dates) [datetime.datetime(2009, 6, 15, 1, 32, 37, 286765), datetime.datetime(2009, 6, 14, 1, 32, 37, 286836), datetime.datetime(2009, 6, 13, 1, 32, 37, 286859)] </code></pre>
24
2009-06-14T18:06:57Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
6,046,264
<p>A bit of a late answer I know, but I just had the same problem and decided that Python's internal range function was a bit lacking in this respect so I've overridden it in a util module of mine.</p> <pre><code>from __builtin__ import range as _range from datetime import datetime, timedelta def range(*args): if len(args) != 3: return _range(*args) start, stop, step = args if start &lt; stop: cmp = lambda a, b: a &lt; b inc = lambda a: a + step else: cmp = lambda a, b: a &gt; b inc = lambda a: a - step output = [start] while cmp(start, stop): start = inc(start) output.append(start) return output print range(datetime(2011, 5, 1), datetime(2011, 10, 1), timedelta(days=30)) </code></pre>
4
2011-05-18T14:21:15Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
9,984,132
<p>Here is gist I created, from my own code, this might help. (I know the question is too old, but others can use it)</p> <p><a href="https://gist.github.com/2287345" rel="nofollow">https://gist.github.com/2287345</a></p> <p>(same thing below)</p> <pre><code>import datetime from time import mktime def convert_date_to_datetime(date_object): date_tuple = date_object.timetuple() date_timestamp = mktime(date_tuple) return datetime.datetime.fromtimestamp(date_timestamp) def date_range(how_many=7): for x in range(0, how_many): some_date = datetime.datetime.today() - datetime.timedelta(days=x) some_datetime = convert_date_to_datetime(some_date.date()) yield some_datetime def pick_two_dates(how_many=7): a = b = convert_date_to_datetime(datetime.datetime.now().date()) for each_date in date_range(how_many): b = a a = each_date if a == b: continue yield b, a </code></pre>
2
2012-04-02T21:31:09Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
11,324,695
<p>yeah, reinvent the wheel.... just search the forum and you'll get something like this: </p> <pre><code>from dateutil import rrule from datetime import datetime list(rrule.rrule(rrule.DAILY,count=100,dtstart=datetime.now())) </code></pre>
16
2012-07-04T07:52:08Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
23,190,286
<p>Pandas is great for time series in general, and has direct support for date ranges.</p> <pre><code>import pandas as pd datelist = pd.date_range(pd.datetime.today(), periods=100).tolist() </code></pre> <p>It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in <code>bdate_range</code>.</p> <p>See <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#generating-ranges-of-timestamps">http://pandas.pydata.org/pandas-docs/stable/timeseries.html#generating-ranges-of-timestamps</a></p> <p>In addition it fully supports pytz timezones and can smoothly span spring/autumn DST shifts.</p>
57
2014-04-21T03:16:13Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
24,637,447
<p>Get range of dates between specified start and end date (Optimized for time &amp; space complexity):</p> <pre><code>import datetime start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y") end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y") date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)] for date in date_generated: print date.strftime("%d-%m-%Y") </code></pre>
20
2014-07-08T16:50:27Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
29,480,840
<p>Matplotlib related</p> <pre><code>from matplotlib.dates import drange import datetime base = datetime.date.today() end = base + datetime.timedelta(days=100) delta = datetime.timedelta(days=1) l = drange(base, end, delta) </code></pre>
1
2015-04-06T22:38:32Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
31,452,467
<pre><code>import datetime def date_generator(): cur = base = datetime.date.today() end = base + datetime.timedelta(days=100) delta = datetime.timedelta(days=1) while(end&gt;base): base = base+delta print base date_generator() </code></pre>
-1
2015-07-16T11:07:55Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
32,616,832
<p>You can also use the day ordinal to make it simpler:</p> <pre><code>def daterange(start_date, end_date): for ordinal in range(start_date.toordinal(), end_date.toordinal()): yield datetime.date.fromordinal(ordinal) </code></pre>
13
2015-09-16T19:12:49Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
34,533,517
<p>Here's a one liner for bash scripts to get a list of weekdays, this is python 3. Easily modified for whatever, the int at the end is the number of days in the past you want. </p> <pre><code>python -c "import sys,datetime; print('\n'.join([(datetime.datetime.today() - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int(sys.argv[1])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()&lt;6]))" 10 </code></pre> <p>Here is a variant to provide a start (or rather, end) date</p> <pre><code>python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d \") for x in range(0,int(sys.argv[2])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()&lt;6]))" 2015/12/30 10 </code></pre> <p>Here is a variant for arbitrary start and end dates. not that this isn't terribly efficient, but is good for putting in a for loop in a bash script:</p> <pre><code>python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") + datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int((datetime.datetime.strptime(sys.argv[2], \"%Y/%m/%d\") - datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\")).days)) if (datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\") + datetime.timedelta(days=x)).isoweekday()&lt;6]))" 2015/12/15 2015/12/30 </code></pre>
3
2015-12-30T16:43:35Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
36,637,717
<pre><code>from datetime import datetime, timedelta from dateutil import parser def getDateRange(begin, end): """ """ beginDate = parser.parse(begin) endDate = parser.parse(end) delta = endDate-beginDate numdays = delta.days + 1 dayList = [datetime.strftime(beginDate + timedelta(days=x), '%Y%m%d') for x in range(0, numdays)] return dayList </code></pre>
0
2016-04-15T03:23:29Z
[ "python", "datetime", "date" ]
Creating a range of dates in Python
993,358
<p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p> <pre><code>import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList </code></pre>
125
2009-06-14T18:03:59Z
36,651,311
<p>From the title of this question I was expecting to find something like <code>range()</code>, that would let me specify two dates and create a list with all the dates in between. That way one does not need to calculate the number of days between those two dates, if one does not know it beforehand.</p> <p>So with the risk of being slightly off-topic, this one-liner does the job:</p> <pre><code>import datetime start_date = datetime.date(2011, 01, 01) end_date = datetime.date(2014, 01, 01) dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))] </code></pre> <p>All credits to <a href="http://stackoverflow.com/a/1060330/4041970">this answer</a>! </p>
1
2016-04-15T15:33:19Z
[ "python", "datetime", "date" ]
User Authentication And Text Parsing in Python
993,619
<p>Well I am working on a multistage program... I am having trouble getting the first stage done.. What I want to do is log on to Twitter.com, and then read all the direct messages on the user's page.</p> <p>Eventually I am going to be reading all the direct messages looking for certain thing, but that shouldn't be hard.</p> <p>This is my code so far</p> <pre><code>import urllib import urllib2 import httplib import sys userName = "notmyusername" password = "notmypassword" URL = "http://twitter.com/#inbox" password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, "http://twitter.com/", userName, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) pageshit = urllib2.urlopen(URL, "80").readlines() print pageshit </code></pre> <p>So a little insight and and help on what I am doing wrong would be quite helpful.</p>
1
2009-06-14T19:55:10Z
993,643
<p>Twitter does not use HTTP Basic Authentication to authenticate its users. It would be better, in this case, to use the Twitter API. </p> <p>A tutorial for using Python with the Twitter API is here: <a href="http://www.webmonkey.com/tutorial/Get%5FStarted%5FWith%5Fthe%5FTwitter%5FAPI%28"><code>http://www.webmonkey.com/tutorial/Get_Started_With_the_Twitter_API</code></a></p>
5
2009-06-14T20:05:58Z
[ "python", "http", "authentication", "urllib2" ]
User Authentication And Text Parsing in Python
993,619
<p>Well I am working on a multistage program... I am having trouble getting the first stage done.. What I want to do is log on to Twitter.com, and then read all the direct messages on the user's page.</p> <p>Eventually I am going to be reading all the direct messages looking for certain thing, but that shouldn't be hard.</p> <p>This is my code so far</p> <pre><code>import urllib import urllib2 import httplib import sys userName = "notmyusername" password = "notmypassword" URL = "http://twitter.com/#inbox" password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, "http://twitter.com/", userName, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) pageshit = urllib2.urlopen(URL, "80").readlines() print pageshit </code></pre> <p>So a little insight and and help on what I am doing wrong would be quite helpful.</p>
1
2009-06-14T19:55:10Z
993,651
<p>The regular web interface of Twitter does not use basic authentication, so requesting pages from the web interface using this method won't work.</p> <p>According to <a href="http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-direct%5Fmessages" rel="nofollow">the Twitter API docs</a>, you can retrieve private messages by fetching this URL:</p> <pre><code>http://twitter.com/direct_messages.format </code></pre> <p>Format can be xml, json, rss or atom. This URL does accept basic authentication.</p> <p>Also, your code does not use the <code>handler</code> object that it builds at all.</p> <p>Here is a working example that corrects both problems. It fetches private messages in json format:</p> <pre><code>import urllib2 username = "USERNAME" password = "PASSWORD" URL = "http://twitter.com/direct_messages.json" password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, "http://twitter.com/", username, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(handler) try: file_obj = opener.open(URL) messages = file_obj.read() print messages except IOError, e: print "Error: ", e </code></pre>
3
2009-06-14T20:11:32Z
[ "python", "http", "authentication", "urllib2" ]
How do I wait for an image to load after an ajax call using jquery?
993,712
<p>I have a Python script that is doing some manipulation on a JPEG image. I pass some parameters to this script and call it from my HTML page. The script returns an img src="newimage.jpg tag.</p> <p>I know how to wait for the reply from the script but I don't know how to tell when the image is fully loaded (when it is, I want to display it). What I get now is the image loading slowly so the user is seeing this "loading" process. Instead, I want to have a msg telling the user to wait while the image is loading, only then I want to display the image.</p>
1
2009-06-14T20:40:07Z
993,720
<p><a href="http://jqueryfordesigners.com/demo/image-load-demo.php" rel="nofollow">Image Loading</a></p> <p><a href="http://www.rodsdot.com/ee/ajaxCallChangeImage.asp" rel="nofollow">Wait for ajaxRequest</a></p>
2
2009-06-14T20:46:03Z
[ "jquery", "python", "ajax" ]
How do I wait for an image to load after an ajax call using jquery?
993,712
<p>I have a Python script that is doing some manipulation on a JPEG image. I pass some parameters to this script and call it from my HTML page. The script returns an img src="newimage.jpg tag.</p> <p>I know how to wait for the reply from the script but I don't know how to tell when the image is fully loaded (when it is, I want to display it). What I get now is the image loading slowly so the user is seeing this "loading" process. Instead, I want to have a msg telling the user to wait while the image is loading, only then I want to display the image.</p>
1
2009-06-14T20:40:07Z
993,806
<p>You can dynamically create a new image, bind something to its load event, and set the source:</p> <pre><code>$('&lt;img&gt;').bind('load', function() { $(this).appendTo('body'); }).attr('src', image_source); </code></pre>
4
2009-06-14T21:32:47Z
[ "jquery", "python", "ajax" ]
How do I wait for an image to load after an ajax call using jquery?
993,712
<p>I have a Python script that is doing some manipulation on a JPEG image. I pass some parameters to this script and call it from my HTML page. The script returns an img src="newimage.jpg tag.</p> <p>I know how to wait for the reply from the script but I don't know how to tell when the image is fully loaded (when it is, I want to display it). What I get now is the image loading slowly so the user is seeing this "loading" process. Instead, I want to have a msg telling the user to wait while the image is loading, only then I want to display the image.</p>
1
2009-06-14T20:40:07Z
993,819
<p>The other answers have mentioned how to do so with jQuery, but regardless of library that you use, ultimately you will be tying into the load event of the image.</p> <p>Without a library, you could do something like this:</p> <pre><code>var el = document.getElementById('ImgLocation'); var img = document.createElement('img'); img.onload = function() { this.style.display = 'block'; } img.src = '/path/to/image.jpg'; img.style.display = 'none'; el.appendChild(img); </code></pre>
0
2009-06-14T21:40:22Z
[ "jquery", "python", "ajax" ]
How to tell a panel that it is being resized when using wx.aui
993,923
<p>I'm using wx.aui to build my user interface. I'm defining a class that inherits from wx.Panel and I need to change the content of that panel when its window pane is resized.</p> <p>I'm using code very similar to the code below (which is a modified version of sample code found <a href="http://stackoverflow.com/questions/523363/how-do-i-layout-a-3-pane-window-using-wxpython/532873#532873">here</a>).</p> <p>My question is: is there a wx.Panel method being called behind the scenes by the AuiManager that I can overload? If not, how can my ControlPanel object know that it's being resized?</p> <p>For instance, if I run this code and drag up the horizontal divider between the upper and lower panes on the right, how is the upper right panel told that its size just changed? </p> <pre><code>import wx import wx.aui class ControlPanel(wx.Panel): def __init__(self, *args, **kwargs): wx.Panel.__init__(self, *args, **kwargs) class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.mgr = wx.aui.AuiManager(self) leftpanel = ControlPanel(self, -1, size = (200, 150)) rightpanel = ControlPanel(self, -1, size = (200, 150)) bottompanel = ControlPanel(self, -1, size = (200, 150)) self.mgr.AddPane(leftpanel, wx.aui.AuiPaneInfo().Bottom()) self.mgr.AddPane(rightpanel, wx.aui.AuiPaneInfo().Left().Layer(1)) self.mgr.AddPane(bottompanel, wx.aui.AuiPaneInfo().Center().Layer(2)) self.mgr.Update() class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, '07_wxaui.py') frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) app.MainLoop() </code></pre>
2
2009-06-14T22:27:56Z
993,947
<p>According to the wx.Panel docs, wx.Panel.Layout is called "automatically by the default EVT_SIZE handler when the window is resized."</p> <p>EDIT: However, the above doesn't work as I would expect, so try manually binding EVT_SIZE:</p> <pre><code>class ControlPanel(wx.Panel): def __init__(self, *args, **kwargs): wx.Panel.__init__(self, *args, **kwargs) self.Bind(wx.EVT_SIZE, self.OnResize) def OnResize(self, *args, **kwargs): print "Resizing" </code></pre>
3
2009-06-14T22:45:49Z
[ "python", "wxpython" ]
Python regular expression with [:numeric:]
994,178
<p>I am having some trouble with Python giving me a result I do not expect. Here is a sample code :</p> <pre><code>number = re.search(" [0-9] ", "test test2 test_ 2 333") print number.groups() number = re.search(" [[:digit:]] ", "test test2 test_ 2 333") print number.groups() </code></pre> <p>In the first block I get an object returned but with nothing in it. Where I think I should get the string "2".</p> <p>In the second block I don't even get an object, where I am expection the string "2".</p> <p>While when I do this in bash everything looks fine :</p> <pre><code>echo "test test2 test_ 2 333" | grep " [[:digit:]] " echo "test test2 test_ 2 333" | grep " [0-9] " </code></pre> <p>Can somebody help me please?</p>
2
2009-06-15T01:05:18Z
994,196
<p>Is this what you're looking for?</p> <pre><code>&gt;&gt;&gt; re.findall(r'([0-9])', "test test2 test_ 2 333") ['2', '2', '3', '3', '3'] </code></pre>
1
2009-06-15T01:13:32Z
[ "python", "regex", "bash" ]
Python regular expression with [:numeric:]
994,178
<p>I am having some trouble with Python giving me a result I do not expect. Here is a sample code :</p> <pre><code>number = re.search(" [0-9] ", "test test2 test_ 2 333") print number.groups() number = re.search(" [[:digit:]] ", "test test2 test_ 2 333") print number.groups() </code></pre> <p>In the first block I get an object returned but with nothing in it. Where I think I should get the string "2".</p> <p>In the second block I don't even get an object, where I am expection the string "2".</p> <p>While when I do this in bash everything looks fine :</p> <pre><code>echo "test test2 test_ 2 333" | grep " [[:digit:]] " echo "test test2 test_ 2 333" | grep " [0-9] " </code></pre> <p>Can somebody help me please?</p>
2
2009-06-15T01:05:18Z
994,205
<p>You are missing the () which capture the contents for use with the groups() (and other) function(s).</p> <pre><code>number = re.search(" ([0-9]) ", "test test2 test_ 2 333") print number.groups() </code></pre> <p>This however won't work because python does not support the [[:number:]] notation</p> <pre><code>number = re.search(" ([[:digit:]]) ", "test test2 test_ 2 333") print number.groups() </code></pre>
2
2009-06-15T01:17:40Z
[ "python", "regex", "bash" ]
Python regular expression with [:numeric:]
994,178
<p>I am having some trouble with Python giving me a result I do not expect. Here is a sample code :</p> <pre><code>number = re.search(" [0-9] ", "test test2 test_ 2 333") print number.groups() number = re.search(" [[:digit:]] ", "test test2 test_ 2 333") print number.groups() </code></pre> <p>In the first block I get an object returned but with nothing in it. Where I think I should get the string "2".</p> <p>In the second block I don't even get an object, where I am expection the string "2".</p> <p>While when I do this in bash everything looks fine :</p> <pre><code>echo "test test2 test_ 2 333" | grep " [[:digit:]] " echo "test test2 test_ 2 333" | grep " [0-9] " </code></pre> <p>Can somebody help me please?</p>
2
2009-06-15T01:05:18Z
994,212
<pre><code>number = re.search(" [0-9] ", "test test2 test_ 2 333") print number.group(0) </code></pre> <p>groups() only returns groups 1 and up (a bit odd if you're used to other languages).</p>
1
2009-06-15T01:19:50Z
[ "python", "regex", "bash" ]
Python regular expression with [:numeric:]
994,178
<p>I am having some trouble with Python giving me a result I do not expect. Here is a sample code :</p> <pre><code>number = re.search(" [0-9] ", "test test2 test_ 2 333") print number.groups() number = re.search(" [[:digit:]] ", "test test2 test_ 2 333") print number.groups() </code></pre> <p>In the first block I get an object returned but with nothing in it. Where I think I should get the string "2".</p> <p>In the second block I don't even get an object, where I am expection the string "2".</p> <p>While when I do this in bash everything looks fine :</p> <pre><code>echo "test test2 test_ 2 333" | grep " [[:digit:]] " echo "test test2 test_ 2 333" | grep " [0-9] " </code></pre> <p>Can somebody help me please?</p>
2
2009-06-15T01:05:18Z
994,217
<p>.groups() returns values inside of matched parentheses. This regex doesn't have any regions defined by parens so groups returns nothing. You want:</p> <blockquote> <blockquote> <blockquote> <p>m = re.search(" ([0-9]) ", "test test2 test_ 2 333") m.groups() ('2',)</p> </blockquote> </blockquote> </blockquote>
0
2009-06-15T01:23:04Z
[ "python", "regex", "bash" ]
Python regular expression with [:numeric:]
994,178
<p>I am having some trouble with Python giving me a result I do not expect. Here is a sample code :</p> <pre><code>number = re.search(" [0-9] ", "test test2 test_ 2 333") print number.groups() number = re.search(" [[:digit:]] ", "test test2 test_ 2 333") print number.groups() </code></pre> <p>In the first block I get an object returned but with nothing in it. Where I think I should get the string "2".</p> <p>In the second block I don't even get an object, where I am expection the string "2".</p> <p>While when I do this in bash everything looks fine :</p> <pre><code>echo "test test2 test_ 2 333" | grep " [[:digit:]] " echo "test test2 test_ 2 333" | grep " [0-9] " </code></pre> <p>Can somebody help me please?</p>
2
2009-06-15T01:05:18Z
994,218
<p>The groups() method returns the capture groups. It does <em>not</em> return group 0, in case that's what you were expecting. Use parens to indicate capture groups. eg:</p> <pre><code>&gt;&gt;&gt; number = re.search(" ([0-9]) ", "test test2 test_ 2 333") &gt;&gt;&gt; print number.groups() ('2',) </code></pre> <p>For your second example, Python's re module doesn't recognize the "[:digit:]" syntax. Use <code>\d</code>. eg:</p> <pre><code>&gt;&gt;&gt; number = re.search(r" (\d) ", "test test2 test_ 2 333") &gt;&gt;&gt; print number.groups() ('2',) </code></pre>
3
2009-06-15T01:23:07Z
[ "python", "regex", "bash" ]
How can I explicitly disable compilation of _tkinter.c when compiling Python 2.4.3 on CentOS 5?
994,278
<p>I'm trying to explicitly disable the compilation of the _tkinter module when compiling Python 2.4.3. It's easy enough to do by modifying the makefile but I'd rather just append a configuration option to avoid supplying a patch.</p> <p>I do not understand the complex interplay between Modules/Setup*, setup.py and their contribution to the generation of makefile.</p>
3
2009-06-15T02:05:20Z
994,311
<p>Unfortunately I suspect you can't do it without editing <em>some</em> file or other -- it's not a <code>configure</code> option we wrote in as far as I recall (I hope I'm wrong and somebody else snuck it in while I wasn't looking but a quick look at the configure file seems to confirm they didnt'). Sorry -- we never thought that somebody (with all the tk libraries installed, otherwise tkinter gets skipped) would need to deliberately avoid building _tkinter:-(. In retrospect, we clearly were wrong, so I apologize.</p>
5
2009-06-15T02:27:18Z
[ "python", "compilation", "tkinter" ]
Is the Python Imaging Library not available on PyPI, or am I missing something?
994,281
<p><code>easy_install pil</code> results in an error:</p> <pre><code>Searching for pil Reading http://pypi.python.org/simple/pil/ Reading http://www.pythonware.com/products/pil Reading http://effbot.org/zone/pil-changes-115.htm Reading http://effbot.org/downloads/#Imaging No local packages or download links found for pil error: Could not find suitable distribution for Requirement.parse(‘pil’) </code></pre> <p>Any ideas?</p> <p>--</p> <p><strong>UPDATE:</strong> Hm, asking it to find-links on the Python Ware site seems to be working:</p> <p><code>easy_install -f <a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a> Imaging</code></p> <p>Got a heap of warnings along the way though. I’ll see how it turns out.</p> <p>--</p> <p><strong>UPDATE:</strong> I can import it in Python using <code>import Image</code>, but when I tell Django to syncdb I still get the following error:</p> <pre><code>Error: One or more models did not validate: core.userprofile: “avatar”: To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ . </code></pre> <p>I'm using an ImageField in one of my models.</p>
1
2009-06-15T02:08:00Z
994,284
<p>Of course PIL is on PyPi! Specifically, it's <a href="http://pypi.python.org/pypi/PIL/1.1.6">right here</a>.</p>
5
2009-06-15T02:09:35Z
[ "python", "django", "python-imaging-library" ]
Is the Python Imaging Library not available on PyPI, or am I missing something?
994,281
<p><code>easy_install pil</code> results in an error:</p> <pre><code>Searching for pil Reading http://pypi.python.org/simple/pil/ Reading http://www.pythonware.com/products/pil Reading http://effbot.org/zone/pil-changes-115.htm Reading http://effbot.org/downloads/#Imaging No local packages or download links found for pil error: Could not find suitable distribution for Requirement.parse(‘pil’) </code></pre> <p>Any ideas?</p> <p>--</p> <p><strong>UPDATE:</strong> Hm, asking it to find-links on the Python Ware site seems to be working:</p> <p><code>easy_install -f <a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a> Imaging</code></p> <p>Got a heap of warnings along the way though. I’ll see how it turns out.</p> <p>--</p> <p><strong>UPDATE:</strong> I can import it in Python using <code>import Image</code>, but when I tell Django to syncdb I still get the following error:</p> <pre><code>Error: One or more models did not validate: core.userprofile: “avatar”: To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ . </code></pre> <p>I'm using an ImageField in one of my models.</p>
1
2009-06-15T02:08:00Z
994,358
<blockquote> <p>import Image</p> </blockquote> <p>Django tries to import PIL directly:</p> <pre><code>from PIL import Image </code></pre> <p>You should check presence of PIL directory in your site-packages</p>
0
2009-06-15T02:59:04Z
[ "python", "django", "python-imaging-library" ]
Is the Python Imaging Library not available on PyPI, or am I missing something?
994,281
<p><code>easy_install pil</code> results in an error:</p> <pre><code>Searching for pil Reading http://pypi.python.org/simple/pil/ Reading http://www.pythonware.com/products/pil Reading http://effbot.org/zone/pil-changes-115.htm Reading http://effbot.org/downloads/#Imaging No local packages or download links found for pil error: Could not find suitable distribution for Requirement.parse(‘pil’) </code></pre> <p>Any ideas?</p> <p>--</p> <p><strong>UPDATE:</strong> Hm, asking it to find-links on the Python Ware site seems to be working:</p> <p><code>easy_install -f <a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a> Imaging</code></p> <p>Got a heap of warnings along the way though. I’ll see how it turns out.</p> <p>--</p> <p><strong>UPDATE:</strong> I can import it in Python using <code>import Image</code>, but when I tell Django to syncdb I still get the following error:</p> <pre><code>Error: One or more models did not validate: core.userprofile: “avatar”: To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ . </code></pre> <p>I'm using an ImageField in one of my models.</p>
1
2009-06-15T02:08:00Z
1,214,160
<p>easy_install is case-sensitive. The package is under PIL.</p>
1
2009-07-31T18:39:40Z
[ "python", "django", "python-imaging-library" ]
Is the Python Imaging Library not available on PyPI, or am I missing something?
994,281
<p><code>easy_install pil</code> results in an error:</p> <pre><code>Searching for pil Reading http://pypi.python.org/simple/pil/ Reading http://www.pythonware.com/products/pil Reading http://effbot.org/zone/pil-changes-115.htm Reading http://effbot.org/downloads/#Imaging No local packages or download links found for pil error: Could not find suitable distribution for Requirement.parse(‘pil’) </code></pre> <p>Any ideas?</p> <p>--</p> <p><strong>UPDATE:</strong> Hm, asking it to find-links on the Python Ware site seems to be working:</p> <p><code>easy_install -f <a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a> Imaging</code></p> <p>Got a heap of warnings along the way though. I’ll see how it turns out.</p> <p>--</p> <p><strong>UPDATE:</strong> I can import it in Python using <code>import Image</code>, but when I tell Django to syncdb I still get the following error:</p> <pre><code>Error: One or more models did not validate: core.userprofile: “avatar”: To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ . </code></pre> <p>I'm using an ImageField in one of my models.</p>
1
2009-06-15T02:08:00Z
1,271,216
<p>workaround is in easy_install PIL egg directory create link to this directory in name "PIL"</p>
1
2009-08-13T10:39:27Z
[ "python", "django", "python-imaging-library" ]
Is the Python Imaging Library not available on PyPI, or am I missing something?
994,281
<p><code>easy_install pil</code> results in an error:</p> <pre><code>Searching for pil Reading http://pypi.python.org/simple/pil/ Reading http://www.pythonware.com/products/pil Reading http://effbot.org/zone/pil-changes-115.htm Reading http://effbot.org/downloads/#Imaging No local packages or download links found for pil error: Could not find suitable distribution for Requirement.parse(‘pil’) </code></pre> <p>Any ideas?</p> <p>--</p> <p><strong>UPDATE:</strong> Hm, asking it to find-links on the Python Ware site seems to be working:</p> <p><code>easy_install -f <a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a> Imaging</code></p> <p>Got a heap of warnings along the way though. I’ll see how it turns out.</p> <p>--</p> <p><strong>UPDATE:</strong> I can import it in Python using <code>import Image</code>, but when I tell Django to syncdb I still get the following error:</p> <pre><code>Error: One or more models did not validate: core.userprofile: “avatar”: To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ . </code></pre> <p>I'm using an ImageField in one of my models.</p>
1
2009-06-15T02:08:00Z
3,228,207
<p>from <a href="http://code.djangoproject.com/ticket/6054" rel="nofollow">http://code.djangoproject.com/ticket/6054</a></p> <p>It seems that there is something wrong with easy_install which installs PIL in the root namespace, installing from sources fixes this, strange.</p>
0
2010-07-12T11:48:34Z
[ "python", "django", "python-imaging-library" ]
OpenOffice.org development with pyUno for Windows—which Python?
994,429
<p>At home, on Linux, I've experimented with pyUNO to control OpenOffice.org using Python. I've been using Python 2.6. It all seems to work nicely.</p> <p>Now I thought I would try one of my scripts (<a href="http://craig.mcqueen.id.au/OpenOfficeGraphicalDiff.html">run a graphical diff for ODF doc</a>) on Windows. But when I tried to run it, I got:</p> <pre><code>ImportError: No module named uno </code></pre> <p>According to <a href="http://udk.openoffice.org/python/python-bridge.html">udk: Python UNO Bridge</a> and <a href="http://wiki.services.openoffice.org/wiki/Using_Python_on_Windows">OpenOffice.org Running Python on Windows</a>, I have to run the Python interpretter that's installed with OpenOffice.org.</p> <p><strong>Q1: Is Python 2.6 available for OpenOffice.org?</strong></p> <p>However, that interpreter is <strong>Python 2.3</strong>, which is getting a little old! and my script uses a feature not supported by 2.3 (<code>subprocess</code> module).</p> <p><strong>Q2: Can pyUNO programming on Windows be done with a pyUNO add-on to the standard Python distribution, not the Python that is bundled with OpenOffice.org?</strong></p> <p>In my searching so far, I haven't been able to find any indication that there is a pyUNO module available to be installed into the standard Python Windows distribution... which is a surprise because on Ubuntu Linux, UNO is supported just fine in Python just by:</p> <pre><code> apt-get install python-uno </code></pre> <p>Another problem with this is: what if I want to make a program that uses both pyUNO and other 3rd party libraries? I can't install pyUNO into my Python installation on Windows, so am I forced to somehow install my other 3rd party libraries into OpenOffice.org's bundled Python? It makes it difficult to create larger, more full-featured programs.</p> <p>Am I missing something, or are we stuck with this situation for now?</p>
7
2009-06-15T03:47:34Z
994,432
<p>Per <a href="http://wiki.services.openoffice.org/wiki/Python" rel="nofollow">openoffice's docs</a>, the Python version supported is WAY behind -- "Efforts on moving PyUNO to Python 2.5 continue", 2.6 not even on the map. So "stuck with this situation for now" is a fair assessment!-)</p>
5
2009-06-15T03:50:11Z
[ "python", "windows", "openoffice.org", "uno", "pyuno" ]
OpenOffice.org development with pyUno for Windows—which Python?
994,429
<p>At home, on Linux, I've experimented with pyUNO to control OpenOffice.org using Python. I've been using Python 2.6. It all seems to work nicely.</p> <p>Now I thought I would try one of my scripts (<a href="http://craig.mcqueen.id.au/OpenOfficeGraphicalDiff.html">run a graphical diff for ODF doc</a>) on Windows. But when I tried to run it, I got:</p> <pre><code>ImportError: No module named uno </code></pre> <p>According to <a href="http://udk.openoffice.org/python/python-bridge.html">udk: Python UNO Bridge</a> and <a href="http://wiki.services.openoffice.org/wiki/Using_Python_on_Windows">OpenOffice.org Running Python on Windows</a>, I have to run the Python interpretter that's installed with OpenOffice.org.</p> <p><strong>Q1: Is Python 2.6 available for OpenOffice.org?</strong></p> <p>However, that interpreter is <strong>Python 2.3</strong>, which is getting a little old! and my script uses a feature not supported by 2.3 (<code>subprocess</code> module).</p> <p><strong>Q2: Can pyUNO programming on Windows be done with a pyUNO add-on to the standard Python distribution, not the Python that is bundled with OpenOffice.org?</strong></p> <p>In my searching so far, I haven't been able to find any indication that there is a pyUNO module available to be installed into the standard Python Windows distribution... which is a surprise because on Ubuntu Linux, UNO is supported just fine in Python just by:</p> <pre><code> apt-get install python-uno </code></pre> <p>Another problem with this is: what if I want to make a program that uses both pyUNO and other 3rd party libraries? I can't install pyUNO into my Python installation on Windows, so am I forced to somehow install my other 3rd party libraries into OpenOffice.org's bundled Python? It makes it difficult to create larger, more full-featured programs.</p> <p>Am I missing something, or are we stuck with this situation for now?</p>
7
2009-06-15T03:47:34Z
995,150
<p>OpenOffice.org 3.1 comes with Python 2.6.1. (As I recall, it was a fairly last-minute merge that ticked some people off, but it's there and it works.) Now the docs are the only thing hopelessly out-of-date. :)</p>
4
2009-06-15T09:09:27Z
[ "python", "windows", "openoffice.org", "uno", "pyuno" ]
OpenOffice.org development with pyUno for Windows—which Python?
994,429
<p>At home, on Linux, I've experimented with pyUNO to control OpenOffice.org using Python. I've been using Python 2.6. It all seems to work nicely.</p> <p>Now I thought I would try one of my scripts (<a href="http://craig.mcqueen.id.au/OpenOfficeGraphicalDiff.html">run a graphical diff for ODF doc</a>) on Windows. But when I tried to run it, I got:</p> <pre><code>ImportError: No module named uno </code></pre> <p>According to <a href="http://udk.openoffice.org/python/python-bridge.html">udk: Python UNO Bridge</a> and <a href="http://wiki.services.openoffice.org/wiki/Using_Python_on_Windows">OpenOffice.org Running Python on Windows</a>, I have to run the Python interpretter that's installed with OpenOffice.org.</p> <p><strong>Q1: Is Python 2.6 available for OpenOffice.org?</strong></p> <p>However, that interpreter is <strong>Python 2.3</strong>, which is getting a little old! and my script uses a feature not supported by 2.3 (<code>subprocess</code> module).</p> <p><strong>Q2: Can pyUNO programming on Windows be done with a pyUNO add-on to the standard Python distribution, not the Python that is bundled with OpenOffice.org?</strong></p> <p>In my searching so far, I haven't been able to find any indication that there is a pyUNO module available to be installed into the standard Python Windows distribution... which is a surprise because on Ubuntu Linux, UNO is supported just fine in Python just by:</p> <pre><code> apt-get install python-uno </code></pre> <p>Another problem with this is: what if I want to make a program that uses both pyUNO and other 3rd party libraries? I can't install pyUNO into my Python installation on Windows, so am I forced to somehow install my other 3rd party libraries into OpenOffice.org's bundled Python? It makes it difficult to create larger, more full-featured programs.</p> <p>Am I missing something, or are we stuck with this situation for now?</p>
7
2009-06-15T03:47:34Z
4,393,670
<p>You can import uno into your system's python on Win32 systems. (Not Python 3 yet). Tutorial at <a href="http://user.services.openoffice.org/en/forum/viewtopic.php?f=45&amp;t=36370&amp;p=166783" rel="nofollow">http://user.services.openoffice.org/en/forum/viewtopic.php?f=45&amp;t=36370&amp;p=166783</a> It's not difficult - import three environment variables, and append one item to your pythonpath.</p> <p>For additional flexibility, you can use the COM-UNO bridge instead of the Python-UNO bridge. The syntax is generally quite similar, and you can use any version of Python (including Python3). Info at <a href="http://user.services.openoffice.org/en/forum/viewtopic.php?f=45&amp;t=36608&amp;p=167909" rel="nofollow">http://user.services.openoffice.org/en/forum/viewtopic.php?f=45&amp;t=36608&amp;p=167909</a></p>
3
2010-12-09T00:14:14Z
[ "python", "windows", "openoffice.org", "uno", "pyuno" ]
Pylons FormEncode with an array of form elements
994,460
<p>I have a Pylons app and am using FormEncode and HtmlFill to handle my forms. I have an array of text fields in my template (Mako)</p> <pre> &lt;tr&gt; &lt;td&gt;Yardage&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;/tr&gt; </pre> <p>However, I can't seem to figure out how to validate these fields. Here is the relevant entry from my Schema</p> <p><code>yardage = formencode.ForEach(formencode.validators.Int())</code></p> <p>I'm trying to validate that each of these fields is an Int. However, no validation occurs for these fields.</p> <p><strong>UPDATE</strong> As requested here is the code for the action of this controller. I know it was working as I can validate other form fields. </p> <pre> def submit(self): schema = CourseForm() try: c.form_result = schema.to_python(dict(request.params)) except formencode.Invalid, error: c.form_result = error.value c.form_errors = error.error_dict or {} c.heading = 'Add a course' html = render('/derived/course/add.html') return htmlfill.render( html, defaults = c.form_result, errors = c.form_errors ) else: h.redirect_to(controler='course', action='view') </pre> <p><strong>UPDATE</strong> It was suggested on IRC that I change the name of the elements from <code>yardage[]</code> to <code>yardage</code> No result. They should all be ints but putting in f into one of the elements doesn't cause it to be invalid. As I said before, I am able to validate other form fields. Below is my entire schema.</p> <pre> import formencode class CourseForm(formencode.Schema): allow_extra_fields = True filter_extra_fields = True name = formencode.validators.NotEmpty(messages={'empty': 'Name must not be empty'}) par = formencode.ForEach(formencode.validators.Int()) yardage = formencode.ForEach(formencode.validators.Int()) </pre>
2
2009-06-15T04:04:25Z
1,004,477
<p>Turns out what I wanted to do wasn't quite right. </p> <p><strong>Template</strong>:</p> <pre><code>&lt;tr&gt; &lt;td&gt;Yardage&lt;/td&gt; % for hole in range(9): &lt;td&gt;${h.text('hole-%s.yardage'%(hole), maxlength=3, size=3)}&lt;/td&gt; % endfor &lt;/tr&gt; </code></pre> <p>(Should have made it in a loop to begin with.) You'll notice that the name of the first element will become <code>hole-1.yardage</code>. I will then use <code><a href="http://www.formencode.org/en/latest/modules/variabledecode.html" rel="nofollow">FormEncode.variabledecode</a></code> to turn this into a dictionary. This is done in the </p> <p><strong>Schema</strong>:</p> <pre><code>import formencode class HoleSchema(formencode.Schema): allow_extra_fields = False yardage = formencode.validators.Int(not_empty=True) par = formencode.validators.Int(not_empty=True) class CourseForm(formencode.Schema): allow_extra_fields = True filter_extra_fields = True name = formencode.validators.NotEmpty(messages={'empty': 'Name must not be empty'}) hole = formencode.ForEach(HoleSchema()) </code></pre> <p>The HoleSchema will validate that <code>hole-#.par</code> and <code>hole-#.yardage</code> are both ints and are not empty. <code>formencode.ForEach</code> allows me to apply <code>HoleSchema</code> to the dictionary that I get from passing <code>variable_decode=True</code> to the <code>@validate</code> decorator.</p> <p>Here is the <code>submit</code> action from my </p> <p><strong>Controller</strong>:</p> <pre><code>@validate(schema=CourseForm(), form='add', post_only=False, on_get=True, auto_error_formatter=custom_formatter, variable_decode=True) def submit(self): # Do whatever here. return 'Submitted!' </code></pre> <p>Using the <code>@validate</code> decorator allows for a much cleaner way to validate and fill in the forms. The <code>variable_decode=True</code> is very important or the dictionary will not be properly created.</p>
5
2009-06-16T23:56:40Z
[ "python", "pylons", "formencode", "htmlfill" ]
Pylons FormEncode with an array of form elements
994,460
<p>I have a Pylons app and am using FormEncode and HtmlFill to handle my forms. I have an array of text fields in my template (Mako)</p> <pre> &lt;tr&gt; &lt;td&gt;Yardage&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;td&gt;${h.text('yardage[]', maxlength=3, size=3)}&lt;/td&gt; &lt;/tr&gt; </pre> <p>However, I can't seem to figure out how to validate these fields. Here is the relevant entry from my Schema</p> <p><code>yardage = formencode.ForEach(formencode.validators.Int())</code></p> <p>I'm trying to validate that each of these fields is an Int. However, no validation occurs for these fields.</p> <p><strong>UPDATE</strong> As requested here is the code for the action of this controller. I know it was working as I can validate other form fields. </p> <pre> def submit(self): schema = CourseForm() try: c.form_result = schema.to_python(dict(request.params)) except formencode.Invalid, error: c.form_result = error.value c.form_errors = error.error_dict or {} c.heading = 'Add a course' html = render('/derived/course/add.html') return htmlfill.render( html, defaults = c.form_result, errors = c.form_errors ) else: h.redirect_to(controler='course', action='view') </pre> <p><strong>UPDATE</strong> It was suggested on IRC that I change the name of the elements from <code>yardage[]</code> to <code>yardage</code> No result. They should all be ints but putting in f into one of the elements doesn't cause it to be invalid. As I said before, I am able to validate other form fields. Below is my entire schema.</p> <pre> import formencode class CourseForm(formencode.Schema): allow_extra_fields = True filter_extra_fields = True name = formencode.validators.NotEmpty(messages={'empty': 'Name must not be empty'}) par = formencode.ForEach(formencode.validators.Int()) yardage = formencode.ForEach(formencode.validators.Int()) </pre>
2
2009-06-15T04:04:25Z
4,025,225
<pre><code>c.form_result = schema.to_python(request.params) - (without dict) </code></pre> <p>It seems to works fine.</p>
1
2010-10-26T15:26:00Z
[ "python", "pylons", "formencode", "htmlfill" ]
What is the equivalent of object oriented constructs in python?
994,476
<p>How does python handle object oriented constructs such as <strong>abstract</strong>, <strong>virtual</strong>, <strong>pure virtual</strong> etc </p> <p>Examples and links would really be good.</p>
9
2009-06-15T04:15:32Z
994,482
<p>An <strong>abstract</strong> method is one that (in the base class) raises <code>NotImplementedError</code>.</p> <p>An abstract class, like in C++, is any class that has one or more abstract methods.</p> <p>All methods in Python are virtual (i.e., all can be overridden by subclasses).</p> <p>A "pure virtual" method would presumably be the same thing as an abstract one.</p> <p>In each case you could attempt deep black magic to fight against the language, but it would be (generally speaking) exceedingly silly to do so.</p> <p>I've striven to deal with the "etc" part in two books, a dozen videos, two dozen essays and PDFs and other presentations, and I can't spend the next few days summarizing it all here. Ask <strong>specific</strong> questions, and I'll be glad to try and answer!</p>
28
2009-06-15T04:24:13Z
[ "python", "oop" ]
What is the equivalent of object oriented constructs in python?
994,476
<p>How does python handle object oriented constructs such as <strong>abstract</strong>, <strong>virtual</strong>, <strong>pure virtual</strong> etc </p> <p>Examples and links would really be good.</p>
9
2009-06-15T04:15:32Z
995,520
<p>"How does python handle object oriented constructs such as abstract, virtual, pure virtual etc."</p> <p>These are language constructs more than OO constructs. One can argue that abstract is a language-agnostic concept (even though Python doesn't need it.) Virtual and Pure Virtual are implementation details for C++.</p> <p>There are two OO constructs that aren't necessary in Python but sometimes helpful.</p> <p>The notion of "Interface" makes sense when (1) you have single inheritance and (2) you have static type-checking. Since Python has multiple inheritance and no static type checking, the concept is <em>almost</em> irrelevant.</p> <p>You can, however, define "interface"-like superclasses which don't actually do anything except define the interface. It's handy for documentation. One idiom is the following.</p> <pre><code>class InterfaceMixin( object ): def requiredMethod( self ): raise NotImplemntedError() class RealClass( SuperClass, InterfaceMixin ): def requiredMethod( self ): # actual implementation. </code></pre> <p>The notion of "Abstract" only makes sense when you have static type checking and you need to alert the compiler that there's no body in one or more methods in this class definition. It also alerts the compiler that you can't create instances. You don't need this in Python because the methods are located dynamically at run-time. Attempting to use an undefined method is just an <code>AttributeError</code>.</p> <p>The closest you can do this kind of thing.</p> <pre><code>class AbstractSuperclass( object ): def abstractMethod( self ): raise NotImplementedError() </code></pre> <p>It isn't completely like Java or C++ <code>abstract</code>. It's a class with a method that raises an error. But it behaves enough like an abstract class to be useful.</p> <p>To match Java, you'd have to prevent creating instances. This requires you to override <code>__new__</code>. If you did this, your concrete subclasses would then need to implement <code>__new__</code>, which is a pain in the neck, so we rarely take active steps to prevent creating instances of something that's supposed to be abstract.</p> <p>The concept of "virtual" and "pure virtual" are C++ optimizations that force a method lookup. Python always does this.</p> <p><hr /></p> <p><strong>Edit</strong> </p> <p>Example of Abstract without the explicit method definition.</p> <pre><code>&gt;&gt;&gt; class Foo( object ): ... pass ... &gt;&gt;&gt; f= Foo() &gt;&gt;&gt; f.bar() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Foo' object has no attribute 'bar' </code></pre>
6
2009-06-15T11:03:25Z
[ "python", "oop" ]
Getting an input/output error from Python with pySerial
994,538
<p>I have a Python script that writes data packets to an Arduino board through <a href="http://pyserial.sourceforge.net/" rel="nofollow">pySerial</a>. Sometimes while writing the code to the board pySerial raises an input/output error with errno 5.</p> <p>Some research says that this indicates an error while writing in the file representing the connection to the Arduino board.</p> <p>The code that sends, sends only single byte packets: </p> <pre><code>try: # Check if it's already a single byte if isinstance(byte, str): if len(byte) == 1: # It is. Send it. self.serial.write(byte) else: # It's not raise PacketException # Check if it's an integer elif isinstance(byte, int): self.serial.write(chr(byte)) # It is; convert it to a byte and send it else: raise PacketException # I don't know what this is. except Exception as ex: print("Exception is: " + ex.__getitem__() + " " + ex.__str__()) </code></pre> <p>The error printed by this code is:</p> <blockquote> <p>OS Error Input/Output Error Errno 5</p> </blockquote> <p>Is there something wrong in my code while sending? Do I need to check if the serial connection is ready to send something or should there be a delay after the sending? Or could there be a problem with the hardware or the connection with the hardware?</p> <p><strong>Edit</strong>: I looked into the Linux implementation from pyserial and the implementation is only passing the error to my code. So no new real insights from there. Is there a good way to test what is happening in the program?</p>
4
2009-06-15T04:55:26Z
994,553
<p>The only issue I can immediately see in your code is an indentation problem -- change your code as follows:</p> <pre><code>try: # Check if it's already a single byte if isinstance(byte, str): if len(byte) == 1: # It is. Send it. self.serial.write(byte) else: # It's not raise PacketException # else, check if it's an integer elif isinstance(byte, int): self.serial.write(chr(byte)) # It is; convert it to a byte and send it else: raise PacketException # I don't know what this is. except Exception as ex: print("Exception is: " + ex.__getitem__() + " " + ex.__str__()) </code></pre> <p>I doubt your error comes from this, but try it this way and let us know! You were checking if <code>byte</code> is an <code>int</code> only in the case in which it's a <code>str</code>, so the <code>elif</code> <strong>always</strong> failed by definition. But I think if you <strong>real</strong> code indentation had been like this, you'd have gotten a <code>SyntaxError</code>, so I think you just erred in posting and your real problem remains hidden.</p>
1
2009-06-15T05:03:32Z
[ "python", "serial-port", "arduino", "pyserial" ]
Getting an input/output error from Python with pySerial
994,538
<p>I have a Python script that writes data packets to an Arduino board through <a href="http://pyserial.sourceforge.net/" rel="nofollow">pySerial</a>. Sometimes while writing the code to the board pySerial raises an input/output error with errno 5.</p> <p>Some research says that this indicates an error while writing in the file representing the connection to the Arduino board.</p> <p>The code that sends, sends only single byte packets: </p> <pre><code>try: # Check if it's already a single byte if isinstance(byte, str): if len(byte) == 1: # It is. Send it. self.serial.write(byte) else: # It's not raise PacketException # Check if it's an integer elif isinstance(byte, int): self.serial.write(chr(byte)) # It is; convert it to a byte and send it else: raise PacketException # I don't know what this is. except Exception as ex: print("Exception is: " + ex.__getitem__() + " " + ex.__str__()) </code></pre> <p>The error printed by this code is:</p> <blockquote> <p>OS Error Input/Output Error Errno 5</p> </blockquote> <p>Is there something wrong in my code while sending? Do I need to check if the serial connection is ready to send something or should there be a delay after the sending? Or could there be a problem with the hardware or the connection with the hardware?</p> <p><strong>Edit</strong>: I looked into the Linux implementation from pyserial and the implementation is only passing the error to my code. So no new real insights from there. Is there a good way to test what is happening in the program?</p>
4
2009-06-15T04:55:26Z
996,077
<p>If you are running this on Windows, you can't have the Arduino IDE open with a serial connection at the same time that you run your Python script. This will throw the same error.</p>
1
2009-06-15T13:21:00Z
[ "python", "serial-port", "arduino", "pyserial" ]
Getting an input/output error from Python with pySerial
994,538
<p>I have a Python script that writes data packets to an Arduino board through <a href="http://pyserial.sourceforge.net/" rel="nofollow">pySerial</a>. Sometimes while writing the code to the board pySerial raises an input/output error with errno 5.</p> <p>Some research says that this indicates an error while writing in the file representing the connection to the Arduino board.</p> <p>The code that sends, sends only single byte packets: </p> <pre><code>try: # Check if it's already a single byte if isinstance(byte, str): if len(byte) == 1: # It is. Send it. self.serial.write(byte) else: # It's not raise PacketException # Check if it's an integer elif isinstance(byte, int): self.serial.write(chr(byte)) # It is; convert it to a byte and send it else: raise PacketException # I don't know what this is. except Exception as ex: print("Exception is: " + ex.__getitem__() + " " + ex.__str__()) </code></pre> <p>The error printed by this code is:</p> <blockquote> <p>OS Error Input/Output Error Errno 5</p> </blockquote> <p>Is there something wrong in my code while sending? Do I need to check if the serial connection is ready to send something or should there be a delay after the sending? Or could there be a problem with the hardware or the connection with the hardware?</p> <p><strong>Edit</strong>: I looked into the Linux implementation from pyserial and the implementation is only passing the error to my code. So no new real insights from there. Is there a good way to test what is happening in the program?</p>
4
2009-06-15T04:55:26Z
998,560
<p>Sorry to have bothered you but I'm very sure that the error is caused by the arduino resetting itself and therefore closing the connection to the computer. </p>
2
2009-06-15T21:45:22Z
[ "python", "serial-port", "arduino", "pyserial" ]