title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
39,164,442
<p>Another option I wasn't aware of until recently - <code>QuerySet</code> also overrides the <code>&amp;</code>, <code>|</code>, <code>~</code>, etc, operators. The other answers that OR Q objects are a better solution to this question, but for the sake of interest/argument, you can do:</p> <pre><code>id_list = [1, 2, 3] q = Article.objects.filter(pk=id_list[0]) for i in id_list[1:]: q |= Article.objects.filter(pk=i) </code></pre> <p><code>str(q.query)</code> will return one query with all the filters in the <code>WHERE</code> clause.</p>
0
2016-08-26T10:45:46Z
[ "python", "django", "django-q" ]
Reverse proxy capable pure python webserver?
852,541
<p>I am looking for a pure python based web server has the capability for reverse proxy as well? </p>
1
2009-05-12T12:37:00Z
852,635
<p>pretty sure you can do that with twisted,</p> <p><a href="http://twistedmatrix.com/trac/wiki/TwistedWeb" rel="nofollow">twisted web</a></p> <p>but why not just use apache?</p>
2
2009-05-12T12:56:03Z
[ "python", "proxy", "webserver", "reverse" ]
Reverse proxy capable pure python webserver?
852,690
<p>I am looking for a pure python based web server has the capability for reverse proxy as well? </p>
3
2009-05-12T13:09:52Z
852,749
<p>Have a look at <a href="http://twistedmatrix.com/" rel="nofollow">Twisted</a>, especially its <a href="http://twistedmatrix.com/documents/current/api/twisted.web.proxy.ReverseProxyResource.html" rel="nofollow">ReverseProxyResource</a>.</p> <blockquote> <p>Twisted Web also provides various facilities for being set up behind a reverse-proxy, which is the suggested mechanism to integrate your Twisted application with an existing site.</p> </blockquote>
3
2009-05-12T13:21:18Z
[ "python", "proxy", "webserver", "reverse" ]
Reverse proxy capable pure python webserver?
852,690
<p>I am looking for a pure python based web server has the capability for reverse proxy as well? </p>
3
2009-05-12T13:09:52Z
852,857
<p><a href="http://pypi.python.org/pypi/proxylet/" rel="nofollow">http://pypi.python.org/pypi/proxylet/</a></p> <p>From <a href="http://www.rfk.id.au/blog/entry/proxylet-lightweight-HTTP-reverse-proxy" rel="nofollow">http://www.rfk.id.au/blog/entry/proxylet-lightweight-HTTP-reverse-proxy</a></p> <blockquote> <p>proxylet is a lightweight reverse proxy for HTTP with nonblocking IO courtesy of eventlet.</p> </blockquote> <p>Looks like source is available as well. I've never used it, as we use <a href="http://www-01.ibm.com/software/webservers/httpservers/" rel="nofollow">IHS</a> for all our reverse proxy needs.</p>
0
2009-05-12T13:39:41Z
[ "python", "proxy", "webserver", "reverse" ]
How can I find the locations of an item in a Python list of lists?
853,023
<p>I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:</p> <pre><code>list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #returns [(1,0)] </code></pre>
5
2009-05-12T14:18:36Z
853,036
<pre><code>def get_positions(xs, target): return [(i,e.index(target)) for i,e in enumerate(xs)] </code></pre> <p>That's a good starting point. Presumably you have some sort of class such as</p> <pre><code>class SomeClass: def __init__(self): self.xs = [['1','2','4','6'], ['7','0','1','4']] def get_positions(self, target): return [(i,e.index(target)) for i,e in enumerate(self.xs)] </code></pre> <p>which in this case would let you say</p> <pre><code>model = SomeClass() model.get_position(1) # returns [(0,0), (1,2)] </code></pre> <p>Note that in both cases you'll get an exception if your target isn't in every one of your sublists. The question does not specify whether this is the desired behavior.</p>
2
2009-05-12T14:21:07Z
[ "python" ]
How can I find the locations of an item in a Python list of lists?
853,023
<p>I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:</p> <pre><code>list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #returns [(1,0)] </code></pre>
5
2009-05-12T14:18:36Z
853,055
<p>It looks likes you want, for a list of sublists and a given item, to return a list of pairs where each pair is (the index of the sublist, the index of the item within the sublist). You can do that using <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a> and Python's built in <a href="http://docs.python.org/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a> function:</p> <pre><code>def getPosition(list, item): return [(i, sublist.index(item)) for i, sublist in enumerate(list)] </code></pre> <p><strong>Edit:</strong> See @scribble's answer above/below.</p>
5
2009-05-12T14:23:36Z
[ "python" ]
How can I find the locations of an item in a Python list of lists?
853,023
<p>I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:</p> <pre><code>list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #returns [(1,0)] </code></pre>
5
2009-05-12T14:18:36Z
853,189
<p>If you don't want a exception if the item is not in the list try this. Also as a generator because they are cool and versatile.</p> <pre><code>xs = [['1', '2', '4', '6'], ['7', '0', '1', '4']] def get_positions(xs, item): for i, xt in enumerate( xs ): try: # trying beats checking yield (i, xt.index(item)) except ValueError: pass print list(get_positions(xs, '1')) print list(get_positions(xs, '6')) # Edit for fun: The one-line version, without try: get_positions2 = lambda xs,item: ((i,xt.index(item)) for i, xt in enumerate(xs) if item in xt) print list(get_positions2(xs, '1')) print list(get_positions2(xs, '6')) </code></pre>
2
2009-05-12T14:51:49Z
[ "python" ]
How can I find the locations of an item in a Python list of lists?
853,023
<p>I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:</p> <pre><code>list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #returns [(1,0)] </code></pre>
5
2009-05-12T14:18:36Z
853,335
<p>If you want something that will both </p> <ul> <li>find duplicates and </li> <li>handle nested lists (lists of lists of lists of ...)</li> </ul> <p>you can do something like the following:</p> <pre><code>def get_positions(xs, item): if isinstance(xs, list): for i, it in enumerate(xs): for pos in get_positions(it, item): yield (i,) + pos elif xs == item: yield () </code></pre> <p>Testing this:</p> <pre><code>&gt;&gt;&gt; xs = [['1', '2', '4', '6'], ... ['7', '0', '1', '4'], ... [ [ '0', '1', '1'], ['1']] ... ] &gt;&gt;&gt; print list(get_positions(xs, '1')) [(0, 0), (1, 2), (2, 0, 1), (2, 0, 2), (2, 1, 0)] </code></pre>
7
2009-05-12T15:19:58Z
[ "python" ]
How can I find the locations of an item in a Python list of lists?
853,023
<p>I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:</p> <pre><code>list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #returns [(1,0)] </code></pre>
5
2009-05-12T14:18:36Z
853,427
<p>A while ago I wrote a library for python to do list matching that would fit the bill pretty well. It used the tokens ?, +, and * as wildcards, where ? signifies a single atom, + is a non-greedy one-or-more, and * is greedy one-or-more. For example:</p> <pre><code>from matching import match match(['?', 2, 3, '*'], [1, 2, 3, 4, 5]) =&gt; [1, [4, 5]] match([1, 2, 3], [1, 2, 4]) =&gt; MatchError: broken at 4 match([1, [2, 3, '*']], [1, [2, 3, 4]]) =&gt; [[4]] match([1, [2, 3, '*']], [1, [2, 3, 4]], True) =&gt; [1, 2, 3, [4]] </code></pre> <p>Download it here: <a href="http://www.artfulcode.net/wp-content/uploads/2008/12/matching.zip" rel="nofollow">http://www.artfulcode.net/wp-content/uploads/2008/12/matching.zip</a></p>
0
2009-05-12T15:39:48Z
[ "python" ]
How can I find the locations of an item in a Python list of lists?
853,023
<p>I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:</p> <pre><code>list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #returns [(1,0)] </code></pre>
5
2009-05-12T14:18:36Z
855,402
<p>Here is a version without try..except, returning an iterator and that for</p> <pre><code>[['1', '1', '1', '1'], ['7', '0', '4']] </code></pre> <p>returns </p> <pre><code>[(0, 0), (0, 1), (0, 2), (0, 3)] def getPosition1(l, val): for row_nb, r in enumerate(l): for col_nb in (x for x in xrange(len(r)) if r[x] == val): yield row_nb, col_nb </code></pre>
0
2009-05-12T23:26:22Z
[ "python" ]
How can I find the locations of an item in a Python list of lists?
853,023
<p>I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:</p> <pre><code>list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #returns [(1,0)] </code></pre>
5
2009-05-12T14:18:36Z
855,669
<p>The most strainghtforward and probably the slowest way to do it would be:</p> <pre><code> &gt;&gt;&gt; value = '1' &gt;&gt;&gt; l = [['1', '2', '3', '4'], ['3', '4', '5', '1']] &gt;&gt;&gt; m = [] &gt;&gt;&gt; for i in range(len(l)): ... for j in range(len(l[i])): ... if l[i][j] == value: ... m.append((i,j)) ... &gt;&gt;&gt; m [(0, 0), (1, 3)] </code></pre>
0
2009-05-13T01:29:19Z
[ "python" ]
How can I find the locations of an item in a Python list of lists?
853,023
<p>I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:</p> <pre><code>list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #returns [(1,0)] </code></pre>
5
2009-05-12T14:18:36Z
855,811
<p>Here is another straight forward method that doesn't use generators.</p> <pre><code>def getPosition(lists,item): positions = [] for i,li in enumerate(lists): j = -1 try: while True: j = li.index(item,j+1) positions.append((i,j)) except ValueError: pass return positions l = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition(l,'1') #returns [(0, 0), (1, 2)] getPosition(l,'9') # returns [] l = [['1', '1', '1', '1'], ['7', '0', '1', '4']] getPosition(l,'1') #returns [(0, 0), (0, 1), (0,2), (0,3), (1,2)] </code></pre>
0
2009-05-13T02:39:12Z
[ "python" ]
How can I find the locations of an item in a Python list of lists?
853,023
<p>I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:</p> <pre><code>list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #returns [(1,0)] </code></pre>
5
2009-05-12T14:18:36Z
861,107
<pre><code>def getPosition(list, item): return [(i, sublist.index(item)) for i, sublist in enumerate(list) if item in sublist] </code></pre>
3
2009-05-14T00:55:28Z
[ "python" ]
Django ORM: Selecting related set
853,184
<p>Say I have 2 models:</p> <pre><code>class Poll(models.Model): category = models.CharField(u"Category", max_length = 64) [...] class Choice(models.Model): poll = models.ForeignKey(Poll) [...] </code></pre> <p>Given a Poll object, I can query its choices with:</p> <pre><code>poll.choice_set.all() </code></pre> <p>But, is there a utility function to query all choices from a set of Poll?</p> <p>Actually, I'm looking for something like the following (which is not supported, and I don't seek how it could be):</p> <pre><code>polls = Poll.objects.filter(category = 'foo').select_related('choice_set') for poll in polls: print poll.choice_set.all() # this shouldn't perform a SQL query at each iteration </code></pre> <p>I made an (ugly) function to help me achieve that:</p> <pre><code>def qbind(objects, target_name, model, field_name): objects = list(objects) objects_dict = dict([(object.id, object) for object in objects]) for foreign in model.objects.filter(**{field_name + '__in': objects_dict.keys()}): id = getattr(foreign, field_name + '_id') if id in objects_dict: object = objects_dict[id] if hasattr(object, target_name): getattr(object, target_name).append(foreign) else: setattr(object, target_name, [foreign]) return objects </code></pre> <p>which is used as follow:</p> <pre><code>polls = Poll.objects.filter(category = 'foo') polls = qbind(polls, 'choices', Choice, 'poll') # Now, each object in polls have a 'choices' member with the list of choices. # This was achieved with 2 SQL queries only. </code></pre> <p>Is there something easier already provided by Django? Or at least, a snippet doing the same thing in a better way.</p> <p>How do you handle this problem usually?</p>
11
2009-05-12T14:50:25Z
853,228
<p>I think what you're saying is, "I want all Choices for a set of Polls." If so, try this:</p> <pre><code>polls = Poll.objects.filter(category='foo') choices = Choice.objects.filter(poll__in=polls) </code></pre>
12
2009-05-12T15:00:07Z
[ "python", "django", "orm" ]
Django ORM: Selecting related set
853,184
<p>Say I have 2 models:</p> <pre><code>class Poll(models.Model): category = models.CharField(u"Category", max_length = 64) [...] class Choice(models.Model): poll = models.ForeignKey(Poll) [...] </code></pre> <p>Given a Poll object, I can query its choices with:</p> <pre><code>poll.choice_set.all() </code></pre> <p>But, is there a utility function to query all choices from a set of Poll?</p> <p>Actually, I'm looking for something like the following (which is not supported, and I don't seek how it could be):</p> <pre><code>polls = Poll.objects.filter(category = 'foo').select_related('choice_set') for poll in polls: print poll.choice_set.all() # this shouldn't perform a SQL query at each iteration </code></pre> <p>I made an (ugly) function to help me achieve that:</p> <pre><code>def qbind(objects, target_name, model, field_name): objects = list(objects) objects_dict = dict([(object.id, object) for object in objects]) for foreign in model.objects.filter(**{field_name + '__in': objects_dict.keys()}): id = getattr(foreign, field_name + '_id') if id in objects_dict: object = objects_dict[id] if hasattr(object, target_name): getattr(object, target_name).append(foreign) else: setattr(object, target_name, [foreign]) return objects </code></pre> <p>which is used as follow:</p> <pre><code>polls = Poll.objects.filter(category = 'foo') polls = qbind(polls, 'choices', Choice, 'poll') # Now, each object in polls have a 'choices' member with the list of choices. # This was achieved with 2 SQL queries only. </code></pre> <p>Is there something easier already provided by Django? Or at least, a snippet doing the same thing in a better way.</p> <p>How do you handle this problem usually?</p>
11
2009-05-12T14:50:25Z
853,397
<p>I think what you are trying to do is the term "eager loading" of child data - meaning you are loading the child list (choice_set) for each Poll, but all in the first query to the DB, so that you don't have to make a bunch of queries later on. </p> <p>If this is correct, then what you are looking for is 'select_related' - see <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related</a></p> <p>I noticed you tried 'select_related' but it didn't work. Can you try doing the 'select_related' and then the filter. That might fix it.</p> <hr> <p>UPDATE: This doesn't work, see comments below.</p>
1
2009-05-12T15:34:56Z
[ "python", "django", "orm" ]
Django ORM: Selecting related set
853,184
<p>Say I have 2 models:</p> <pre><code>class Poll(models.Model): category = models.CharField(u"Category", max_length = 64) [...] class Choice(models.Model): poll = models.ForeignKey(Poll) [...] </code></pre> <p>Given a Poll object, I can query its choices with:</p> <pre><code>poll.choice_set.all() </code></pre> <p>But, is there a utility function to query all choices from a set of Poll?</p> <p>Actually, I'm looking for something like the following (which is not supported, and I don't seek how it could be):</p> <pre><code>polls = Poll.objects.filter(category = 'foo').select_related('choice_set') for poll in polls: print poll.choice_set.all() # this shouldn't perform a SQL query at each iteration </code></pre> <p>I made an (ugly) function to help me achieve that:</p> <pre><code>def qbind(objects, target_name, model, field_name): objects = list(objects) objects_dict = dict([(object.id, object) for object in objects]) for foreign in model.objects.filter(**{field_name + '__in': objects_dict.keys()}): id = getattr(foreign, field_name + '_id') if id in objects_dict: object = objects_dict[id] if hasattr(object, target_name): getattr(object, target_name).append(foreign) else: setattr(object, target_name, [foreign]) return objects </code></pre> <p>which is used as follow:</p> <pre><code>polls = Poll.objects.filter(category = 'foo') polls = qbind(polls, 'choices', Choice, 'poll') # Now, each object in polls have a 'choices' member with the list of choices. # This was achieved with 2 SQL queries only. </code></pre> <p>Is there something easier already provided by Django? Or at least, a snippet doing the same thing in a better way.</p> <p>How do you handle this problem usually?</p>
11
2009-05-12T14:50:25Z
854,077
<p><strong>Update</strong>: Since Django 1.4, this feature is built in: see <a href="https://docs.djangoproject.com/en/stable/ref/models/querysets/#prefetch-related" rel="nofollow">prefetch_related</a>.</p> <p>First answer: don't waste time writing something like qbind until you've already written a working application, profiled it, and demonstrated that N queries is actually a performance problem for your database and load scenarios.</p> <p>But maybe you've done that. So second answer: qbind() does what you'll need to do, but it would be more idiomatic if packaged in a custom QuerySet subclass, with an accompanying Manager subclass that returns instances of the custom QuerySet. Ideally you could even make them generic and reusable for any reverse relation. Then you could do something like:</p> <pre><code>Poll.objects.filter(category='foo').fetch_reverse_relations('choices_set') </code></pre> <p>For an example of the Manager/QuerySet technique, see <a href="http://www.djangosnippets.org/snippets/1079/" rel="nofollow">this snippet</a>, which solves a similar problem but for the case of Generic Foreign Keys, not reverse relations. It wouldn't be too hard to combine the guts of your qbind() function with the structure shown there to make a really nice solution to your problem.</p>
10
2009-05-12T18:11:29Z
[ "python", "django", "orm" ]
Django ORM: Selecting related set
853,184
<p>Say I have 2 models:</p> <pre><code>class Poll(models.Model): category = models.CharField(u"Category", max_length = 64) [...] class Choice(models.Model): poll = models.ForeignKey(Poll) [...] </code></pre> <p>Given a Poll object, I can query its choices with:</p> <pre><code>poll.choice_set.all() </code></pre> <p>But, is there a utility function to query all choices from a set of Poll?</p> <p>Actually, I'm looking for something like the following (which is not supported, and I don't seek how it could be):</p> <pre><code>polls = Poll.objects.filter(category = 'foo').select_related('choice_set') for poll in polls: print poll.choice_set.all() # this shouldn't perform a SQL query at each iteration </code></pre> <p>I made an (ugly) function to help me achieve that:</p> <pre><code>def qbind(objects, target_name, model, field_name): objects = list(objects) objects_dict = dict([(object.id, object) for object in objects]) for foreign in model.objects.filter(**{field_name + '__in': objects_dict.keys()}): id = getattr(foreign, field_name + '_id') if id in objects_dict: object = objects_dict[id] if hasattr(object, target_name): getattr(object, target_name).append(foreign) else: setattr(object, target_name, [foreign]) return objects </code></pre> <p>which is used as follow:</p> <pre><code>polls = Poll.objects.filter(category = 'foo') polls = qbind(polls, 'choices', Choice, 'poll') # Now, each object in polls have a 'choices' member with the list of choices. # This was achieved with 2 SQL queries only. </code></pre> <p>Is there something easier already provided by Django? Or at least, a snippet doing the same thing in a better way.</p> <p>How do you handle this problem usually?</p>
11
2009-05-12T14:50:25Z
11,374,381
<p>Time has passed and this functionality is now available in Django 1.4 with the introduction of the <a href="https://docs.djangoproject.com/en/1.4/ref/models/querysets/#prefetch-related">prefetch_related()</a> QuerySet function. This function effectively does what is performed by the suggested <code>qbind</code> function. ie. Two queries are performed and the join occurs in Python land, but now this is handled by the ORM.</p> <p>The original query request would now become:</p> <pre><code>polls = Poll.objects.filter(category = 'foo').prefetch_related('choice_set') </code></pre> <p>As is shown in the following code sample, the <code>polls</code> QuerySet can be used to obtain all <code>Choice</code> objects per <code>Poll</code> without requiring any further database hits:</p> <pre><code>for poll in polls: for choice in poll.choice_set: print choice </code></pre>
15
2012-07-07T10:56:21Z
[ "python", "django", "orm" ]
How can you migrate Django models similar to Ruby on Rails migrations?
853,248
<p>Django has a number of open source projects that tackle one of the framework's more notable <a href="http://code.djangoproject.com/wiki/SchemaEvolution">missing features</a>: model "evolution". Ruby on Rails has native support for <a href="http://api.rubyonrails.org/classes/ActiveRecord/Migration.html">migrations</a>, but I'm curious if anyone can recommend one of the following Django "evolution" projects:</p> <ul> <li><a href="http://south.aeracode.org/">South</a></li> <li><a href="http://code.google.com/p/django-evolution/">django-evolution</a></li> <li><a href="http://code.google.com/p/dmigrations/">dmigrations</a></li> </ul>
5
2009-05-12T15:04:24Z
853,468
<p>South has the most steam behind it. dmigrations is too basic IMO. django-evolution screams if you ever touch the db outside of it.</p> <p>South is the strongest contender by far. With the model freezing and auto-migrations it's come a long way.</p>
10
2009-05-12T15:46:14Z
[ "python", "django", "migration" ]
How can you migrate Django models similar to Ruby on Rails migrations?
853,248
<p>Django has a number of open source projects that tackle one of the framework's more notable <a href="http://code.djangoproject.com/wiki/SchemaEvolution">missing features</a>: model "evolution". Ruby on Rails has native support for <a href="http://api.rubyonrails.org/classes/ActiveRecord/Migration.html">migrations</a>, but I'm curious if anyone can recommend one of the following Django "evolution" projects:</p> <ul> <li><a href="http://south.aeracode.org/">South</a></li> <li><a href="http://code.google.com/p/django-evolution/">django-evolution</a></li> <li><a href="http://code.google.com/p/dmigrations/">dmigrations</a></li> </ul>
5
2009-05-12T15:04:24Z
854,022
<p>South and django-evolution are certainly the best options. South's model-freezing and auto-hinting are still quite fragile in my experience (django-evolution's hinting is much more robust in edge cases), but django-evolution's development seems to have mostly stalled since last summer. If I were starting now I'd probably pick South, mostly for that reason.</p>
5
2009-05-12T18:00:30Z
[ "python", "django", "migration" ]
How can you migrate Django models similar to Ruby on Rails migrations?
853,248
<p>Django has a number of open source projects that tackle one of the framework's more notable <a href="http://code.djangoproject.com/wiki/SchemaEvolution">missing features</a>: model "evolution". Ruby on Rails has native support for <a href="http://api.rubyonrails.org/classes/ActiveRecord/Migration.html">migrations</a>, but I'm curious if anyone can recommend one of the following Django "evolution" projects:</p> <ul> <li><a href="http://south.aeracode.org/">South</a></li> <li><a href="http://code.google.com/p/django-evolution/">django-evolution</a></li> <li><a href="http://code.google.com/p/dmigrations/">dmigrations</a></li> </ul>
5
2009-05-12T15:04:24Z
854,059
<p>I'm a member of the team that developed dmigrations - but I would wholeheartedly recommend South. It's much more mature, is under active development, and has some killer features like ORM freezing (if you try to use ORM code in dmigrations, then change your models, you're in for a world of pain).</p>
1
2009-05-12T18:08:12Z
[ "python", "django", "migration" ]
How can you migrate Django models similar to Ruby on Rails migrations?
853,248
<p>Django has a number of open source projects that tackle one of the framework's more notable <a href="http://code.djangoproject.com/wiki/SchemaEvolution">missing features</a>: model "evolution". Ruby on Rails has native support for <a href="http://api.rubyonrails.org/classes/ActiveRecord/Migration.html">migrations</a>, but I'm curious if anyone can recommend one of the following Django "evolution" projects:</p> <ul> <li><a href="http://south.aeracode.org/">South</a></li> <li><a href="http://code.google.com/p/django-evolution/">django-evolution</a></li> <li><a href="http://code.google.com/p/dmigrations/">dmigrations</a></li> </ul>
5
2009-05-12T15:04:24Z
1,898,037
<p>After reading this, I went from 'knowing nothing about data model evolution' to 'using south to manage model migration' in less than 1 hour. South's documentation is outstanding and got me up to speed in record time. Not having looked at the other tools mentioned, I fully recommend it.</p> <p>Update: Since posting this answer about a month ago, I went through several data model reviews, ranging from simple field renaming to completely replacing some tables by new ones. South can not do everything in a fully automated manner (e.g. a rename looks like delete &amp; add), but the documentation guides you smoothly through the manual steps.</p> <p>I will bring south into any future project. Fantastic tool!</p>
1
2009-12-13T22:28:40Z
[ "python", "django", "migration" ]
Which open-source Python or Java library provides an easy way to draw circles on a ESRI Shapefile?
853,311
<p>I need to write a software that creates an shapefile with various circles or circumferences on it. The shapefile created should be readable by ESRI ArcMap.</p> <p>I need a library that let me add circles or circular arc to it.</p> <p>The library could be in for Python or in Java. </p>
2
2009-05-12T15:15:35Z
853,382
<p>If you look at <a href="http://openmap.bbn.com/" rel="nofollow">OpenMap</a>, it may be possible to write some code using that set of libraries in Java to do what you are asking.</p> <p>I don't know if its possible from a single call, but there is definitely code in OpenMap to <a href="http://openmap.bbn.com/doc/api/com/bbn/openmap/geo/package-summary.html" rel="nofollow">generate circles and arcs</a> and it also has code to read in a shapefile. The jump to <a href="http://openmap.bbn.com/doc/api/com/bbn/openmap/dataAccess/shape/output/package-summary.html" rel="nofollow">exporting a shape file</a> shouldn't be too big.</p>
1
2009-05-12T15:31:04Z
[ "java", "python", "arcgis", "shapefile", "esri" ]
Which open-source Python or Java library provides an easy way to draw circles on a ESRI Shapefile?
853,311
<p>I need to write a software that creates an shapefile with various circles or circumferences on it. The shapefile created should be readable by ESRI ArcMap.</p> <p>I need a library that let me add circles or circular arc to it.</p> <p>The library could be in for Python or in Java. </p>
2
2009-05-12T15:15:35Z
3,366,881
<p>Matt Perry has a short and sweet example of creating circles in a shapefile in <a href="http://www.perrygeo.net/wordpress/?p=4" rel="nofollow">Tissot Indicatrix - Examining the distortion of map projections</a>. Not listed in the post is how to install the prerequiste gdal/ogr; for that see <a href="http://trac.osgeo.org/osgeo4w/wiki" rel="nofollow">OSGeo4W</a> on windows or a simple <code>apt-get install gdal python-gdal</code> on ubuntu linux. </p>
0
2010-07-29T20:58:36Z
[ "java", "python", "arcgis", "shapefile", "esri" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
853,424
<p>How about <a href="http://code.google.com/p/pyodbc/">pyodbc</a>? <a href="http://stackoverflow.com/questions/827502/pyodbc-and-microsoft-access-inconsistent-results-from-simple-query">This SO question</a> demonstrates it's possible to read MS Access using it.</p>
10
2009-05-12T15:39:23Z
[ "python", "linux", "ms-access", "python-module" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
853,762
<p>Most likely, you'll want to use a nice framework like <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> to access your data, or at least, I would recommend it. <a href="http://www.sqlalchemy.org/trac/wiki/DatabaseNotes#MicrosoftAccess" rel="nofollow">Support for Access</a> is "experimental", but I remember using it without too many problems. It itself uses <a href="http://code.google.com/p/pyodbc/" rel="nofollow">pyodbc</a> under the hood to connect to Access dbs, so it should work from windows, linux, os x and whatnot.</p>
2
2009-05-12T16:51:52Z
[ "python", "linux", "ms-access", "python-module" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
855,090
<p>If you sync your database to the web using <a href="http://eqldata.com/" rel="nofollow">EQL Data</a>, then you can query the contents of your Access tables using JSON or YAML: <a href="http://eqldata.com/kb/1002" rel="nofollow">http://eqldata.com/kb/1002</a>.</p> <p>That article is about PHP, but it would work just as well in Python.</p>
0
2009-05-12T22:00:41Z
[ "python", "linux", "ms-access", "python-module" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
855,212
<p>I've used <a href="https://pypi.python.org/pypi/pyodbc/" rel="nofollow">PYODBC</a> to connect succesfully to an MS Access db - on Windows though. Install was easy, usage is fairly simple, you just need to set the right connection string (the one for MS Access is given in the list) and of you go with the examples.</p>
17
2009-05-12T22:33:26Z
[ "python", "linux", "ms-access", "python-module" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
855,788
<p>You've got what sounds like some good solutions. Another one that might be a bit closer to the "metal" than you'd like is MDB Tools.</p> <p><a href="http://sourceforge.net/projects/mdbtools/">MDB Tools</a> is a set of open source libraries and utilities to facilitate exporting data from MS Access databases (mdb files) without using the Microsoft DLLs. Thus non Windows OSs can read the data. Or, to put it another way, they are reverse engineering the layout of the MDB file. </p> <p>Also note that I doubt they've started working on ACCDB files and there is likely not going to be much request for that capability.</p>
8
2009-05-13T02:32:10Z
[ "python", "linux", "ms-access", "python-module" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
15,400,363
<p>On Linux, MDBTools is your only chance as of now. <sup><a href="http://stackoverflow.com/questions/853370/#comment53931912_15400363">[disputed]</a></sup></p> <p>On Windows, you can deal with mdb files with pypyodbc.</p> <p>To create an Access mdb file:</p> <pre><code>import pypyodbc pypyodbc.win_create_mdb( "D:\\Your_MDB_file_path.mdb" ) </code></pre> <p><a href="https://code.google.com/p/pypyodbc/wiki/pypyodbc_for_access_mdb_file" rel="nofollow">Here is an Hello World script</a> that fully demostate pypyodbc's Access support functions.</p> <p>Disclaimer: I'm the developer of pypyodbc.</p>
25
2013-03-14T02:56:02Z
[ "python", "linux", "ms-access", "python-module" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
18,155,406
<p>Old question, but I thought I'd post a pypyodbc alternative suggestion for Windows: ADO. Turns out, it's really easy to get at Access databases, Excel spreadsheets and anything else with a modern (as opposed to old-school ODBC) driver via COM.</p> <p>Check out the following articles:</p> <ul> <li><a href="http://www.mayukhbose.com/python/ado/index.php" rel="nofollow">http://www.mayukhbose.com/python/ado/index.php</a></li> <li><a href="http://www.markcarter.me.uk/computing/python/ado.html" rel="nofollow">http://www.markcarter.me.uk/computing/python/ado.html</a></li> <li><a href="http://www.ecp.cc/ado_examples.shtml" rel="nofollow">http://www.ecp.cc/ado_examples.shtml</a></li> </ul>
3
2013-08-09T20:48:15Z
[ "python", "linux", "ms-access", "python-module" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
24,096,474
<p>On Ubuntu 12.04 this was what I did to make it work.</p> <p>Install pyodbc:</p> <pre><code>$ sudo apt-get install python-pyodbc </code></pre> <p>Follow on installing some extra drivers:</p> <pre><code>$ sudo apt-get install mdbtools libmdbodbc1 </code></pre> <p>Make a little test program which connects to the DB and displays all the tables:</p> <pre><code>import os import pyodbc db_path = os.path.join("path", "toyour", "db.mdb") odbc_connection_str = 'DRIVER={MDBTools};DBQ=%s;' % (db_path) connection = pyodbc.connect(odbc_connection_str) cursor = connection.cursor() query = "SELECT * FROM MSysObjects WHERE Type=1 AND Flags=0" cursor.execute(query) rows = cursor.fetchall() for row in rows: print row </code></pre> <p>I hope it helped.</p>
1
2014-06-07T11:01:31Z
[ "python", "linux", "ms-access", "python-module" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
25,773,262
<p>If you have some time to spare, you can try to fix and update this python-class that reads MS-Access DBs through the native COM32-client API: <a href="http://code.activestate.com/recipes/528868-extraction-and-manipulation-class-for-microsoft-ac/" rel="nofollow">Extraction and manipulation class for Microsoft Access</a></p>
0
2014-09-10T19:12:11Z
[ "python", "linux", "ms-access", "python-module" ]
What do I need to read Microsoft Access databases using Python?
853,370
<p>How can I access Microsoft Access databases in Python? With SQL?</p> <p>I'd prefere a solution that works with Linux, but I could also settle for Windows.</p> <p>I only require read access.</p>
24
2009-05-12T15:29:23Z
25,774,158
<p>Personally, I have never been able to get MDB Tools (along with related ODBC stuff like unixODBC) to work properly with Python or PHP under Linux, even after numerous attempts. I just tried the instructions in the other answer to this question <a href="http://stackoverflow.com/a/24096474/2144390">here</a> and all I got was "Segmentation fault (core dumped)".</p> <p>However, I did get Jython and the <a href="http://ucanaccess.sourceforge.net/site.html" rel="nofollow">UCanAccess</a> JDBC driver to read both .mdb and .accdb files on Linux. For detailed instructions on how I set it up under Ubuntu 14.04 LTS see my other answer <a href="http://stackoverflow.com/a/25614063/2144390">here</a>.</p>
2
2014-09-10T20:06:12Z
[ "python", "linux", "ms-access", "python-module" ]
Alternate newline character? python
853,398
<p>I am looking for a way to represent '\n' with only one character. I am writing a program that uses dictionaries to 'encrypt' text. Because each character is represented in the dictionary, i am having a problem when my program gets to a '\n' in a string, but reads it as '\' 'n' . Is there alternate way to represent a newline, that is only one character? This is my code below, sorry if some of the indentation is messed up. I dont entirely understand how to input code into this window. :)</p> <pre><code>################################## #This program will take an input and encrypt it or decrypt it #A cipher is used to transform the text, which can either be #input or from a text file. #The cipher can be any letter a-z, as well as most commonly used special characters #numbers and spaces are not allowed. #For the text, a-z, most special characters, space, and new line may be used. #no numbers can be encrypted. ################################## #These three dictionaries are used during the encryption process. keyDict={'a': 17,'b': 3,'c':16,'d':26,'e':6,'f':19,'g':10,'h':12, 'i':22,'j':8,'k': 11,'l':2,'m':18,'n':9,'o':23,'p':7, 'q':5,'r': 20,'s': 1,'t': 24,'u':13,'v':25,'w':21,'x':15, 'y':4,'z': 14, ' ':42, '.':0,'!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33,'&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict2={' ': 43, 'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17,'\n': 42, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26, ' ':0, '!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33, '&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict={0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 42:'\n', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 43:' ', 32: ':', 33: "'", 34: '@', 35: '#', 36: '$', 37: '%', 38: '^', 39: '&amp;', 40: '*', 41: '~', 27: '!', 28: '?', 29: ',', 30: '.', 31: ';'} #switch1 reverses a list. It is its own inverse, so we don't need an unswitch function. def switch1(l): return l[::-1] #switch2 takes a list as input and moves every fourth entry to the front #so switch2([a,b,c,d,e,f,g]) returns ([a,e,b,c,d,f,g]) #unswitch2 undoes this, so unswitch2([a,e,c,d,f,g]) returns [a,b,c,d,e,f,g] def switch2(l): List4 = [] ListNot4 = [] for i in range(0,len(l)): if i%4 == 0: List4.append(l[i]) else: ListNot4.append(l[i]) return List4+ListNot4 def unswitch2(l): num4 = len(l)/4 + 1 fixedList = l[num4:] for i in range (0,num4): fixedList.insert(4*i,l[i]) return fixedList #switch3 takes a list as input and returns a list with the first half moved to the end. #so switch3([a,b,c,d,e,f]) returns [d,e,f,a,b,c] #for lists of odd length, switch3 puts the separation closer to the beginning of the list, so the #middle entry becomes the first entry. #For example, switch3([a,b,c,d,e,f,g]) returns [d,e,f,g,a,b,c] def switch3(l): return l[len(l)/2:] + l[:len(l)/2] def unswitch3(l): if len(l)%2==0: return switch3(l) else: return l[len(l)/2+1:] + l[:len(l)/2+1] ################################## #This is the Crypt function. ################################## def Crypt(text, cipher): counter=0 text=text.lower() cipher=cipher.lower() keyValue=[] textValue=[] newValue=[] newString='' for letter in cipher: keyValue.append(keyDict[letter]) for letter in text: textValue.append(refDict2[letter]) for num in textValue: newValue.append(num+keyValue[counter%len(keyValue)]) counter+=1 newValue = switch1(newValue) newValue = switch2(newValue) newValue = switch3(newValue) for num in newValue: newString+=refDict[num%43] return newString ################################## #This is the Decrypt function ################################## def Decrypt(encryptedText, cipher): counter=0 cipher=cipher.lower() keyValue=[] textValue=[] finalValue=[] finalString='' for letter in encryptedText: textValue.append(refDict2[letter]) textValue = unswitch3(textValue) textValue = unswitch2(textValue) textValue = switch1(textValue) for letter in cipher: keyValue.append(keyDict[letter]) for num in textValue: finalValue.append((num-keyValue[counter%len(keyValue)])%43) counter+=1 for num in finalValue: finalString+=refDict[num] return finalString ################################## #This is the user interface. ################################## choice=raw_input('Would you like to: 1)Encrypt or 2)Decrypt? Pick 1 or 2: ') if choice=='1': textType=raw_input("Would you like to: 1)encrypt a text file or 2) input the text to be encrypted? Pick 1 or 2: ") if textType=='1': cryptName=raw_input( 'Please enter the name of the text file you would like to encrypt(eg. text.txt): ') newName=raw_input('Please name the file in which the encrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter your personal encryption key(eg. secret code):" ) cryptFile=open(cryptName, 'r') newFile=open(newName, 'w') print &gt;&gt; newFile, Crypt(cryptFile.read(),cipher) cryptFile.close() newFile.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to encrypt(eg. computers rock!): ') cipher=raw_input("Now enter your personal encryption key (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Crypt(inputText, cipher) else: print 'Try again!' elif choice=='2': textType=raw_input("Would you like to:1)decrypt a text file or 2) input the text to be decrypted? Pick 1 or 2: ") if textType=='1': decryptName=raw_input( 'Please enter the name of the text file you would like to decrypt(eg. text.txt): ') newName2=raw_input('Please name the file in which the decrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter the encryption key that was used to encrypt the file(eg. secret code):" ) #Text decrypt decryptFile=open(decryptName, 'r') newFile2=open(newName2, 'w') print&gt;&gt; newFile2, Decrypt(decryptFile.read(),cipher) #other stuff #textTodecrypt=decryptFile.read() #newFile2.writelines(Decrypt(textTodecrypt, cipher)) decryptFile.close() newFile2.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to decrypt(eg. dig&amp;ak:do): ') cipher=raw_input("Now enter the encryption key that was used to encrypt the text (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Decrypt(inputText, cipher) print "Have a nice day!" #there is an issue with the newline character </code></pre>
0
2009-05-12T15:35:10Z
853,419
<p>'\n' is one character. It is a new line escape character and is just a representation of the new line. </p> <p>please rephrase your question in a readable way.</p> <p>[Edit] I think I know what your problem is. I ran your program and it is working just fine. You are probably trying to pass '\n' to your program from the command line. That will not work! </p> <p>You see, if you gave raw_input() this string: <code>line1\nline2</code> it will escape the <code>\n</code> and make it <code>\\n</code> like this: <code>'line1\\nline2'</code></p> <p>So a quick hacky fix is to find and replace '\\n' with '\n':</p> <pre><code>text.replace('\\n', '\n') </code></pre> <p>I don't like this. But it will work for you.</p> <p>A much better way is to read multiple lines, like this:</p> <pre><code>input = raw_input('Please type in something: ') lines = [input] while input: input = raw_input() lines.append(input) text = '\n'.join(lines) print text </code></pre>
9
2009-05-12T15:38:21Z
[ "python" ]
Alternate newline character? python
853,398
<p>I am looking for a way to represent '\n' with only one character. I am writing a program that uses dictionaries to 'encrypt' text. Because each character is represented in the dictionary, i am having a problem when my program gets to a '\n' in a string, but reads it as '\' 'n' . Is there alternate way to represent a newline, that is only one character? This is my code below, sorry if some of the indentation is messed up. I dont entirely understand how to input code into this window. :)</p> <pre><code>################################## #This program will take an input and encrypt it or decrypt it #A cipher is used to transform the text, which can either be #input or from a text file. #The cipher can be any letter a-z, as well as most commonly used special characters #numbers and spaces are not allowed. #For the text, a-z, most special characters, space, and new line may be used. #no numbers can be encrypted. ################################## #These three dictionaries are used during the encryption process. keyDict={'a': 17,'b': 3,'c':16,'d':26,'e':6,'f':19,'g':10,'h':12, 'i':22,'j':8,'k': 11,'l':2,'m':18,'n':9,'o':23,'p':7, 'q':5,'r': 20,'s': 1,'t': 24,'u':13,'v':25,'w':21,'x':15, 'y':4,'z': 14, ' ':42, '.':0,'!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33,'&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict2={' ': 43, 'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17,'\n': 42, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26, ' ':0, '!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33, '&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict={0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 42:'\n', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 43:' ', 32: ':', 33: "'", 34: '@', 35: '#', 36: '$', 37: '%', 38: '^', 39: '&amp;', 40: '*', 41: '~', 27: '!', 28: '?', 29: ',', 30: '.', 31: ';'} #switch1 reverses a list. It is its own inverse, so we don't need an unswitch function. def switch1(l): return l[::-1] #switch2 takes a list as input and moves every fourth entry to the front #so switch2([a,b,c,d,e,f,g]) returns ([a,e,b,c,d,f,g]) #unswitch2 undoes this, so unswitch2([a,e,c,d,f,g]) returns [a,b,c,d,e,f,g] def switch2(l): List4 = [] ListNot4 = [] for i in range(0,len(l)): if i%4 == 0: List4.append(l[i]) else: ListNot4.append(l[i]) return List4+ListNot4 def unswitch2(l): num4 = len(l)/4 + 1 fixedList = l[num4:] for i in range (0,num4): fixedList.insert(4*i,l[i]) return fixedList #switch3 takes a list as input and returns a list with the first half moved to the end. #so switch3([a,b,c,d,e,f]) returns [d,e,f,a,b,c] #for lists of odd length, switch3 puts the separation closer to the beginning of the list, so the #middle entry becomes the first entry. #For example, switch3([a,b,c,d,e,f,g]) returns [d,e,f,g,a,b,c] def switch3(l): return l[len(l)/2:] + l[:len(l)/2] def unswitch3(l): if len(l)%2==0: return switch3(l) else: return l[len(l)/2+1:] + l[:len(l)/2+1] ################################## #This is the Crypt function. ################################## def Crypt(text, cipher): counter=0 text=text.lower() cipher=cipher.lower() keyValue=[] textValue=[] newValue=[] newString='' for letter in cipher: keyValue.append(keyDict[letter]) for letter in text: textValue.append(refDict2[letter]) for num in textValue: newValue.append(num+keyValue[counter%len(keyValue)]) counter+=1 newValue = switch1(newValue) newValue = switch2(newValue) newValue = switch3(newValue) for num in newValue: newString+=refDict[num%43] return newString ################################## #This is the Decrypt function ################################## def Decrypt(encryptedText, cipher): counter=0 cipher=cipher.lower() keyValue=[] textValue=[] finalValue=[] finalString='' for letter in encryptedText: textValue.append(refDict2[letter]) textValue = unswitch3(textValue) textValue = unswitch2(textValue) textValue = switch1(textValue) for letter in cipher: keyValue.append(keyDict[letter]) for num in textValue: finalValue.append((num-keyValue[counter%len(keyValue)])%43) counter+=1 for num in finalValue: finalString+=refDict[num] return finalString ################################## #This is the user interface. ################################## choice=raw_input('Would you like to: 1)Encrypt or 2)Decrypt? Pick 1 or 2: ') if choice=='1': textType=raw_input("Would you like to: 1)encrypt a text file or 2) input the text to be encrypted? Pick 1 or 2: ") if textType=='1': cryptName=raw_input( 'Please enter the name of the text file you would like to encrypt(eg. text.txt): ') newName=raw_input('Please name the file in which the encrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter your personal encryption key(eg. secret code):" ) cryptFile=open(cryptName, 'r') newFile=open(newName, 'w') print &gt;&gt; newFile, Crypt(cryptFile.read(),cipher) cryptFile.close() newFile.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to encrypt(eg. computers rock!): ') cipher=raw_input("Now enter your personal encryption key (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Crypt(inputText, cipher) else: print 'Try again!' elif choice=='2': textType=raw_input("Would you like to:1)decrypt a text file or 2) input the text to be decrypted? Pick 1 or 2: ") if textType=='1': decryptName=raw_input( 'Please enter the name of the text file you would like to decrypt(eg. text.txt): ') newName2=raw_input('Please name the file in which the decrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter the encryption key that was used to encrypt the file(eg. secret code):" ) #Text decrypt decryptFile=open(decryptName, 'r') newFile2=open(newName2, 'w') print&gt;&gt; newFile2, Decrypt(decryptFile.read(),cipher) #other stuff #textTodecrypt=decryptFile.read() #newFile2.writelines(Decrypt(textTodecrypt, cipher)) decryptFile.close() newFile2.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to decrypt(eg. dig&amp;ak:do): ') cipher=raw_input("Now enter the encryption key that was used to encrypt the text (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Decrypt(inputText, cipher) print "Have a nice day!" #there is an issue with the newline character </code></pre>
0
2009-05-12T15:35:10Z
853,432
<p>I'm guessing that your real problem is not with reading in \n as a '\' 'n' -- internally, Python should automagically translate \n into a single character.</p> <p>My guess is that the real problem is that your newlines are probably actually two characters -- carriage return ('\r') and newline ('\n'). Try handling \r in addition to \n, and I wonder if that won't make your problem go away.</p>
4
2009-05-12T15:40:18Z
[ "python" ]
Alternate newline character? python
853,398
<p>I am looking for a way to represent '\n' with only one character. I am writing a program that uses dictionaries to 'encrypt' text. Because each character is represented in the dictionary, i am having a problem when my program gets to a '\n' in a string, but reads it as '\' 'n' . Is there alternate way to represent a newline, that is only one character? This is my code below, sorry if some of the indentation is messed up. I dont entirely understand how to input code into this window. :)</p> <pre><code>################################## #This program will take an input and encrypt it or decrypt it #A cipher is used to transform the text, which can either be #input or from a text file. #The cipher can be any letter a-z, as well as most commonly used special characters #numbers and spaces are not allowed. #For the text, a-z, most special characters, space, and new line may be used. #no numbers can be encrypted. ################################## #These three dictionaries are used during the encryption process. keyDict={'a': 17,'b': 3,'c':16,'d':26,'e':6,'f':19,'g':10,'h':12, 'i':22,'j':8,'k': 11,'l':2,'m':18,'n':9,'o':23,'p':7, 'q':5,'r': 20,'s': 1,'t': 24,'u':13,'v':25,'w':21,'x':15, 'y':4,'z': 14, ' ':42, '.':0,'!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33,'&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict2={' ': 43, 'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17,'\n': 42, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26, ' ':0, '!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33, '&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict={0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 42:'\n', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 43:' ', 32: ':', 33: "'", 34: '@', 35: '#', 36: '$', 37: '%', 38: '^', 39: '&amp;', 40: '*', 41: '~', 27: '!', 28: '?', 29: ',', 30: '.', 31: ';'} #switch1 reverses a list. It is its own inverse, so we don't need an unswitch function. def switch1(l): return l[::-1] #switch2 takes a list as input and moves every fourth entry to the front #so switch2([a,b,c,d,e,f,g]) returns ([a,e,b,c,d,f,g]) #unswitch2 undoes this, so unswitch2([a,e,c,d,f,g]) returns [a,b,c,d,e,f,g] def switch2(l): List4 = [] ListNot4 = [] for i in range(0,len(l)): if i%4 == 0: List4.append(l[i]) else: ListNot4.append(l[i]) return List4+ListNot4 def unswitch2(l): num4 = len(l)/4 + 1 fixedList = l[num4:] for i in range (0,num4): fixedList.insert(4*i,l[i]) return fixedList #switch3 takes a list as input and returns a list with the first half moved to the end. #so switch3([a,b,c,d,e,f]) returns [d,e,f,a,b,c] #for lists of odd length, switch3 puts the separation closer to the beginning of the list, so the #middle entry becomes the first entry. #For example, switch3([a,b,c,d,e,f,g]) returns [d,e,f,g,a,b,c] def switch3(l): return l[len(l)/2:] + l[:len(l)/2] def unswitch3(l): if len(l)%2==0: return switch3(l) else: return l[len(l)/2+1:] + l[:len(l)/2+1] ################################## #This is the Crypt function. ################################## def Crypt(text, cipher): counter=0 text=text.lower() cipher=cipher.lower() keyValue=[] textValue=[] newValue=[] newString='' for letter in cipher: keyValue.append(keyDict[letter]) for letter in text: textValue.append(refDict2[letter]) for num in textValue: newValue.append(num+keyValue[counter%len(keyValue)]) counter+=1 newValue = switch1(newValue) newValue = switch2(newValue) newValue = switch3(newValue) for num in newValue: newString+=refDict[num%43] return newString ################################## #This is the Decrypt function ################################## def Decrypt(encryptedText, cipher): counter=0 cipher=cipher.lower() keyValue=[] textValue=[] finalValue=[] finalString='' for letter in encryptedText: textValue.append(refDict2[letter]) textValue = unswitch3(textValue) textValue = unswitch2(textValue) textValue = switch1(textValue) for letter in cipher: keyValue.append(keyDict[letter]) for num in textValue: finalValue.append((num-keyValue[counter%len(keyValue)])%43) counter+=1 for num in finalValue: finalString+=refDict[num] return finalString ################################## #This is the user interface. ################################## choice=raw_input('Would you like to: 1)Encrypt or 2)Decrypt? Pick 1 or 2: ') if choice=='1': textType=raw_input("Would you like to: 1)encrypt a text file or 2) input the text to be encrypted? Pick 1 or 2: ") if textType=='1': cryptName=raw_input( 'Please enter the name of the text file you would like to encrypt(eg. text.txt): ') newName=raw_input('Please name the file in which the encrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter your personal encryption key(eg. secret code):" ) cryptFile=open(cryptName, 'r') newFile=open(newName, 'w') print &gt;&gt; newFile, Crypt(cryptFile.read(),cipher) cryptFile.close() newFile.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to encrypt(eg. computers rock!): ') cipher=raw_input("Now enter your personal encryption key (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Crypt(inputText, cipher) else: print 'Try again!' elif choice=='2': textType=raw_input("Would you like to:1)decrypt a text file or 2) input the text to be decrypted? Pick 1 or 2: ") if textType=='1': decryptName=raw_input( 'Please enter the name of the text file you would like to decrypt(eg. text.txt): ') newName2=raw_input('Please name the file in which the decrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter the encryption key that was used to encrypt the file(eg. secret code):" ) #Text decrypt decryptFile=open(decryptName, 'r') newFile2=open(newName2, 'w') print&gt;&gt; newFile2, Decrypt(decryptFile.read(),cipher) #other stuff #textTodecrypt=decryptFile.read() #newFile2.writelines(Decrypt(textTodecrypt, cipher)) decryptFile.close() newFile2.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to decrypt(eg. dig&amp;ak:do): ') cipher=raw_input("Now enter the encryption key that was used to encrypt the text (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Decrypt(inputText, cipher) print "Have a nice day!" #there is an issue with the newline character </code></pre>
0
2009-05-12T15:35:10Z
853,445
<p>You should probably take advantage of a number's numeric value to perform your encryption and avoid those big data structures that will fail for non-ascii text anyway.</p>
1
2009-05-12T15:41:53Z
[ "python" ]
Alternate newline character? python
853,398
<p>I am looking for a way to represent '\n' with only one character. I am writing a program that uses dictionaries to 'encrypt' text. Because each character is represented in the dictionary, i am having a problem when my program gets to a '\n' in a string, but reads it as '\' 'n' . Is there alternate way to represent a newline, that is only one character? This is my code below, sorry if some of the indentation is messed up. I dont entirely understand how to input code into this window. :)</p> <pre><code>################################## #This program will take an input and encrypt it or decrypt it #A cipher is used to transform the text, which can either be #input or from a text file. #The cipher can be any letter a-z, as well as most commonly used special characters #numbers and spaces are not allowed. #For the text, a-z, most special characters, space, and new line may be used. #no numbers can be encrypted. ################################## #These three dictionaries are used during the encryption process. keyDict={'a': 17,'b': 3,'c':16,'d':26,'e':6,'f':19,'g':10,'h':12, 'i':22,'j':8,'k': 11,'l':2,'m':18,'n':9,'o':23,'p':7, 'q':5,'r': 20,'s': 1,'t': 24,'u':13,'v':25,'w':21,'x':15, 'y':4,'z': 14, ' ':42, '.':0,'!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33,'&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict2={' ': 43, 'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17,'\n': 42, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26, ' ':0, '!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33, '&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict={0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 42:'\n', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 43:' ', 32: ':', 33: "'", 34: '@', 35: '#', 36: '$', 37: '%', 38: '^', 39: '&amp;', 40: '*', 41: '~', 27: '!', 28: '?', 29: ',', 30: '.', 31: ';'} #switch1 reverses a list. It is its own inverse, so we don't need an unswitch function. def switch1(l): return l[::-1] #switch2 takes a list as input and moves every fourth entry to the front #so switch2([a,b,c,d,e,f,g]) returns ([a,e,b,c,d,f,g]) #unswitch2 undoes this, so unswitch2([a,e,c,d,f,g]) returns [a,b,c,d,e,f,g] def switch2(l): List4 = [] ListNot4 = [] for i in range(0,len(l)): if i%4 == 0: List4.append(l[i]) else: ListNot4.append(l[i]) return List4+ListNot4 def unswitch2(l): num4 = len(l)/4 + 1 fixedList = l[num4:] for i in range (0,num4): fixedList.insert(4*i,l[i]) return fixedList #switch3 takes a list as input and returns a list with the first half moved to the end. #so switch3([a,b,c,d,e,f]) returns [d,e,f,a,b,c] #for lists of odd length, switch3 puts the separation closer to the beginning of the list, so the #middle entry becomes the first entry. #For example, switch3([a,b,c,d,e,f,g]) returns [d,e,f,g,a,b,c] def switch3(l): return l[len(l)/2:] + l[:len(l)/2] def unswitch3(l): if len(l)%2==0: return switch3(l) else: return l[len(l)/2+1:] + l[:len(l)/2+1] ################################## #This is the Crypt function. ################################## def Crypt(text, cipher): counter=0 text=text.lower() cipher=cipher.lower() keyValue=[] textValue=[] newValue=[] newString='' for letter in cipher: keyValue.append(keyDict[letter]) for letter in text: textValue.append(refDict2[letter]) for num in textValue: newValue.append(num+keyValue[counter%len(keyValue)]) counter+=1 newValue = switch1(newValue) newValue = switch2(newValue) newValue = switch3(newValue) for num in newValue: newString+=refDict[num%43] return newString ################################## #This is the Decrypt function ################################## def Decrypt(encryptedText, cipher): counter=0 cipher=cipher.lower() keyValue=[] textValue=[] finalValue=[] finalString='' for letter in encryptedText: textValue.append(refDict2[letter]) textValue = unswitch3(textValue) textValue = unswitch2(textValue) textValue = switch1(textValue) for letter in cipher: keyValue.append(keyDict[letter]) for num in textValue: finalValue.append((num-keyValue[counter%len(keyValue)])%43) counter+=1 for num in finalValue: finalString+=refDict[num] return finalString ################################## #This is the user interface. ################################## choice=raw_input('Would you like to: 1)Encrypt or 2)Decrypt? Pick 1 or 2: ') if choice=='1': textType=raw_input("Would you like to: 1)encrypt a text file or 2) input the text to be encrypted? Pick 1 or 2: ") if textType=='1': cryptName=raw_input( 'Please enter the name of the text file you would like to encrypt(eg. text.txt): ') newName=raw_input('Please name the file in which the encrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter your personal encryption key(eg. secret code):" ) cryptFile=open(cryptName, 'r') newFile=open(newName, 'w') print &gt;&gt; newFile, Crypt(cryptFile.read(),cipher) cryptFile.close() newFile.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to encrypt(eg. computers rock!): ') cipher=raw_input("Now enter your personal encryption key (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Crypt(inputText, cipher) else: print 'Try again!' elif choice=='2': textType=raw_input("Would you like to:1)decrypt a text file or 2) input the text to be decrypted? Pick 1 or 2: ") if textType=='1': decryptName=raw_input( 'Please enter the name of the text file you would like to decrypt(eg. text.txt): ') newName2=raw_input('Please name the file in which the decrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter the encryption key that was used to encrypt the file(eg. secret code):" ) #Text decrypt decryptFile=open(decryptName, 'r') newFile2=open(newName2, 'w') print&gt;&gt; newFile2, Decrypt(decryptFile.read(),cipher) #other stuff #textTodecrypt=decryptFile.read() #newFile2.writelines(Decrypt(textTodecrypt, cipher)) decryptFile.close() newFile2.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to decrypt(eg. dig&amp;ak:do): ') cipher=raw_input("Now enter the encryption key that was used to encrypt the text (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Decrypt(inputText, cipher) print "Have a nice day!" #there is an issue with the newline character </code></pre>
0
2009-05-12T15:35:10Z
853,459
<p>Newline character is a single character.</p> <pre><code>&gt;&gt;&gt; a = '\n' &gt;&gt;&gt; print len(a) 1 &gt;&gt;&gt; a = '\n\n\n' &gt;&gt;&gt; a[1] '\n' &gt;&gt;&gt; len(a) 3 &gt;&gt;&gt; len(a[0]) 1 </code></pre> <p>So you misunderstand what your problem is.</p>
3
2009-05-12T15:44:14Z
[ "python" ]
Alternate newline character? python
853,398
<p>I am looking for a way to represent '\n' with only one character. I am writing a program that uses dictionaries to 'encrypt' text. Because each character is represented in the dictionary, i am having a problem when my program gets to a '\n' in a string, but reads it as '\' 'n' . Is there alternate way to represent a newline, that is only one character? This is my code below, sorry if some of the indentation is messed up. I dont entirely understand how to input code into this window. :)</p> <pre><code>################################## #This program will take an input and encrypt it or decrypt it #A cipher is used to transform the text, which can either be #input or from a text file. #The cipher can be any letter a-z, as well as most commonly used special characters #numbers and spaces are not allowed. #For the text, a-z, most special characters, space, and new line may be used. #no numbers can be encrypted. ################################## #These three dictionaries are used during the encryption process. keyDict={'a': 17,'b': 3,'c':16,'d':26,'e':6,'f':19,'g':10,'h':12, 'i':22,'j':8,'k': 11,'l':2,'m':18,'n':9,'o':23,'p':7, 'q':5,'r': 20,'s': 1,'t': 24,'u':13,'v':25,'w':21,'x':15, 'y':4,'z': 14, ' ':42, '.':0,'!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33,'&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict2={' ': 43, 'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17,'\n': 42, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26, ' ':0, '!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33, '&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict={0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 42:'\n', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 43:' ', 32: ':', 33: "'", 34: '@', 35: '#', 36: '$', 37: '%', 38: '^', 39: '&amp;', 40: '*', 41: '~', 27: '!', 28: '?', 29: ',', 30: '.', 31: ';'} #switch1 reverses a list. It is its own inverse, so we don't need an unswitch function. def switch1(l): return l[::-1] #switch2 takes a list as input and moves every fourth entry to the front #so switch2([a,b,c,d,e,f,g]) returns ([a,e,b,c,d,f,g]) #unswitch2 undoes this, so unswitch2([a,e,c,d,f,g]) returns [a,b,c,d,e,f,g] def switch2(l): List4 = [] ListNot4 = [] for i in range(0,len(l)): if i%4 == 0: List4.append(l[i]) else: ListNot4.append(l[i]) return List4+ListNot4 def unswitch2(l): num4 = len(l)/4 + 1 fixedList = l[num4:] for i in range (0,num4): fixedList.insert(4*i,l[i]) return fixedList #switch3 takes a list as input and returns a list with the first half moved to the end. #so switch3([a,b,c,d,e,f]) returns [d,e,f,a,b,c] #for lists of odd length, switch3 puts the separation closer to the beginning of the list, so the #middle entry becomes the first entry. #For example, switch3([a,b,c,d,e,f,g]) returns [d,e,f,g,a,b,c] def switch3(l): return l[len(l)/2:] + l[:len(l)/2] def unswitch3(l): if len(l)%2==0: return switch3(l) else: return l[len(l)/2+1:] + l[:len(l)/2+1] ################################## #This is the Crypt function. ################################## def Crypt(text, cipher): counter=0 text=text.lower() cipher=cipher.lower() keyValue=[] textValue=[] newValue=[] newString='' for letter in cipher: keyValue.append(keyDict[letter]) for letter in text: textValue.append(refDict2[letter]) for num in textValue: newValue.append(num+keyValue[counter%len(keyValue)]) counter+=1 newValue = switch1(newValue) newValue = switch2(newValue) newValue = switch3(newValue) for num in newValue: newString+=refDict[num%43] return newString ################################## #This is the Decrypt function ################################## def Decrypt(encryptedText, cipher): counter=0 cipher=cipher.lower() keyValue=[] textValue=[] finalValue=[] finalString='' for letter in encryptedText: textValue.append(refDict2[letter]) textValue = unswitch3(textValue) textValue = unswitch2(textValue) textValue = switch1(textValue) for letter in cipher: keyValue.append(keyDict[letter]) for num in textValue: finalValue.append((num-keyValue[counter%len(keyValue)])%43) counter+=1 for num in finalValue: finalString+=refDict[num] return finalString ################################## #This is the user interface. ################################## choice=raw_input('Would you like to: 1)Encrypt or 2)Decrypt? Pick 1 or 2: ') if choice=='1': textType=raw_input("Would you like to: 1)encrypt a text file or 2) input the text to be encrypted? Pick 1 or 2: ") if textType=='1': cryptName=raw_input( 'Please enter the name of the text file you would like to encrypt(eg. text.txt): ') newName=raw_input('Please name the file in which the encrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter your personal encryption key(eg. secret code):" ) cryptFile=open(cryptName, 'r') newFile=open(newName, 'w') print &gt;&gt; newFile, Crypt(cryptFile.read(),cipher) cryptFile.close() newFile.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to encrypt(eg. computers rock!): ') cipher=raw_input("Now enter your personal encryption key (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Crypt(inputText, cipher) else: print 'Try again!' elif choice=='2': textType=raw_input("Would you like to:1)decrypt a text file or 2) input the text to be decrypted? Pick 1 or 2: ") if textType=='1': decryptName=raw_input( 'Please enter the name of the text file you would like to decrypt(eg. text.txt): ') newName2=raw_input('Please name the file in which the decrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter the encryption key that was used to encrypt the file(eg. secret code):" ) #Text decrypt decryptFile=open(decryptName, 'r') newFile2=open(newName2, 'w') print&gt;&gt; newFile2, Decrypt(decryptFile.read(),cipher) #other stuff #textTodecrypt=decryptFile.read() #newFile2.writelines(Decrypt(textTodecrypt, cipher)) decryptFile.close() newFile2.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to decrypt(eg. dig&amp;ak:do): ') cipher=raw_input("Now enter the encryption key that was used to encrypt the text (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Decrypt(inputText, cipher) print "Have a nice day!" #there is an issue with the newline character </code></pre>
0
2009-05-12T15:35:10Z
853,471
<p>I'm new to Python, but there could be a way to simplify what you are doing by using the <strong>ord</strong> and <strong>chr</strong> functions to change characters to ASCII values and vice versa. Here's a link to the <a href="http://docs.python.org/library/functions.html" rel="nofollow">built-in function documentation in Python</a>.</p>
2
2009-05-12T15:46:22Z
[ "python" ]
Alternate newline character? python
853,398
<p>I am looking for a way to represent '\n' with only one character. I am writing a program that uses dictionaries to 'encrypt' text. Because each character is represented in the dictionary, i am having a problem when my program gets to a '\n' in a string, but reads it as '\' 'n' . Is there alternate way to represent a newline, that is only one character? This is my code below, sorry if some of the indentation is messed up. I dont entirely understand how to input code into this window. :)</p> <pre><code>################################## #This program will take an input and encrypt it or decrypt it #A cipher is used to transform the text, which can either be #input or from a text file. #The cipher can be any letter a-z, as well as most commonly used special characters #numbers and spaces are not allowed. #For the text, a-z, most special characters, space, and new line may be used. #no numbers can be encrypted. ################################## #These three dictionaries are used during the encryption process. keyDict={'a': 17,'b': 3,'c':16,'d':26,'e':6,'f':19,'g':10,'h':12, 'i':22,'j':8,'k': 11,'l':2,'m':18,'n':9,'o':23,'p':7, 'q':5,'r': 20,'s': 1,'t': 24,'u':13,'v':25,'w':21,'x':15, 'y':4,'z': 14, ' ':42, '.':0,'!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33,'&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict2={' ': 43, 'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17,'\n': 42, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26, ' ':0, '!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33, '&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict={0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 42:'\n', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 43:' ', 32: ':', 33: "'", 34: '@', 35: '#', 36: '$', 37: '%', 38: '^', 39: '&amp;', 40: '*', 41: '~', 27: '!', 28: '?', 29: ',', 30: '.', 31: ';'} #switch1 reverses a list. It is its own inverse, so we don't need an unswitch function. def switch1(l): return l[::-1] #switch2 takes a list as input and moves every fourth entry to the front #so switch2([a,b,c,d,e,f,g]) returns ([a,e,b,c,d,f,g]) #unswitch2 undoes this, so unswitch2([a,e,c,d,f,g]) returns [a,b,c,d,e,f,g] def switch2(l): List4 = [] ListNot4 = [] for i in range(0,len(l)): if i%4 == 0: List4.append(l[i]) else: ListNot4.append(l[i]) return List4+ListNot4 def unswitch2(l): num4 = len(l)/4 + 1 fixedList = l[num4:] for i in range (0,num4): fixedList.insert(4*i,l[i]) return fixedList #switch3 takes a list as input and returns a list with the first half moved to the end. #so switch3([a,b,c,d,e,f]) returns [d,e,f,a,b,c] #for lists of odd length, switch3 puts the separation closer to the beginning of the list, so the #middle entry becomes the first entry. #For example, switch3([a,b,c,d,e,f,g]) returns [d,e,f,g,a,b,c] def switch3(l): return l[len(l)/2:] + l[:len(l)/2] def unswitch3(l): if len(l)%2==0: return switch3(l) else: return l[len(l)/2+1:] + l[:len(l)/2+1] ################################## #This is the Crypt function. ################################## def Crypt(text, cipher): counter=0 text=text.lower() cipher=cipher.lower() keyValue=[] textValue=[] newValue=[] newString='' for letter in cipher: keyValue.append(keyDict[letter]) for letter in text: textValue.append(refDict2[letter]) for num in textValue: newValue.append(num+keyValue[counter%len(keyValue)]) counter+=1 newValue = switch1(newValue) newValue = switch2(newValue) newValue = switch3(newValue) for num in newValue: newString+=refDict[num%43] return newString ################################## #This is the Decrypt function ################################## def Decrypt(encryptedText, cipher): counter=0 cipher=cipher.lower() keyValue=[] textValue=[] finalValue=[] finalString='' for letter in encryptedText: textValue.append(refDict2[letter]) textValue = unswitch3(textValue) textValue = unswitch2(textValue) textValue = switch1(textValue) for letter in cipher: keyValue.append(keyDict[letter]) for num in textValue: finalValue.append((num-keyValue[counter%len(keyValue)])%43) counter+=1 for num in finalValue: finalString+=refDict[num] return finalString ################################## #This is the user interface. ################################## choice=raw_input('Would you like to: 1)Encrypt or 2)Decrypt? Pick 1 or 2: ') if choice=='1': textType=raw_input("Would you like to: 1)encrypt a text file or 2) input the text to be encrypted? Pick 1 or 2: ") if textType=='1': cryptName=raw_input( 'Please enter the name of the text file you would like to encrypt(eg. text.txt): ') newName=raw_input('Please name the file in which the encrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter your personal encryption key(eg. secret code):" ) cryptFile=open(cryptName, 'r') newFile=open(newName, 'w') print &gt;&gt; newFile, Crypt(cryptFile.read(),cipher) cryptFile.close() newFile.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to encrypt(eg. computers rock!): ') cipher=raw_input("Now enter your personal encryption key (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Crypt(inputText, cipher) else: print 'Try again!' elif choice=='2': textType=raw_input("Would you like to:1)decrypt a text file or 2) input the text to be decrypted? Pick 1 or 2: ") if textType=='1': decryptName=raw_input( 'Please enter the name of the text file you would like to decrypt(eg. text.txt): ') newName2=raw_input('Please name the file in which the decrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter the encryption key that was used to encrypt the file(eg. secret code):" ) #Text decrypt decryptFile=open(decryptName, 'r') newFile2=open(newName2, 'w') print&gt;&gt; newFile2, Decrypt(decryptFile.read(),cipher) #other stuff #textTodecrypt=decryptFile.read() #newFile2.writelines(Decrypt(textTodecrypt, cipher)) decryptFile.close() newFile2.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to decrypt(eg. dig&amp;ak:do): ') cipher=raw_input("Now enter the encryption key that was used to encrypt the text (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Decrypt(inputText, cipher) print "Have a nice day!" #there is an issue with the newline character </code></pre>
0
2009-05-12T15:35:10Z
853,530
<p>I assume the problem is if there is \n in the text to be decrypted, it breaks:</p> <pre><code>KeyError: \ module body in untitled at line 166 function Crypt in untitled at line 94 </code></pre> <p>Basically, <code>raw_input()</code> returns a string containing two characters <code>\</code> and <code>n</code> - and you have no mapping for <code>\</code> thus the error.</p> <p>The simplest solution is so simply replace the literal characters <code>\n</code> with the <code>\n</code> escape sequence</p> <pre><code>def Crypt(text, cipher): text.replace(r"\n", "\n") ... </code></pre> <p>The raw string <code>r"\n"</code> creates a string containing the literal character <code>\</code> followed by <code>n</code> (the same as doing <code>"\\n"</code>).</p> <p>In a regular string <code>"\n"</code> it's treated as the escape-sequence for a new-line. So the above code-block replaces <code>\n</code> in text with an newline.</p> <p>You may have to define a mapping for "\n" in your <code>keyDict</code> mapping.</p> <p>Another solution would be to split the text using <code>text.split(r"\n")</code> and treat each line separately. Or as others have suggested, use <a href="http://docs.python.org/library/functions.html#ord" rel="nofollow"><code>ord()</code></a> every character and deal with numbers, rather than making your own numerical mapping.</p> <blockquote> <p><code>ord(c)</code> Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, <code>ord('a')</code> returns the integer 97, <code>ord(u'\u2020')</code> returns 8224. This is the inverse of <code>chr()</code> for 8-bit strings and of <code>unichr()</code> for unicode objects.</p> </blockquote> <p>As the docs explains, <a href="http://docs.python.org/library/functions.html#chr" rel="nofollow"><code>chr()</code></a> is the opposite, and will turn the number back into a ASCII or Unicode character:</p> <blockquote> <p><code>chr(i)</code> Return a string of one character whose ASCII code is the integer i. For example, <code>chr(97)</code> returns the string 'a'. This is the inverse of <code>ord()</code>. The argument must be in the range [0..255], inclusive; ValueError will be raised if i is outside that range.</p> </blockquote> <p>Basically you would do..</p> <pre><code>def Crypt(text, cipher): keyvalue = [ord(x) for x in cipher) textvalue = [ord(x) for x in text] </code></pre> <p>..instead of the two for loops (the <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list-comprehension</a> is basically the same as making a list, looping over each character in text or cipher, and appending to the list each time)</p>
4
2009-05-12T15:56:59Z
[ "python" ]
Alternate newline character? python
853,398
<p>I am looking for a way to represent '\n' with only one character. I am writing a program that uses dictionaries to 'encrypt' text. Because each character is represented in the dictionary, i am having a problem when my program gets to a '\n' in a string, but reads it as '\' 'n' . Is there alternate way to represent a newline, that is only one character? This is my code below, sorry if some of the indentation is messed up. I dont entirely understand how to input code into this window. :)</p> <pre><code>################################## #This program will take an input and encrypt it or decrypt it #A cipher is used to transform the text, which can either be #input or from a text file. #The cipher can be any letter a-z, as well as most commonly used special characters #numbers and spaces are not allowed. #For the text, a-z, most special characters, space, and new line may be used. #no numbers can be encrypted. ################################## #These three dictionaries are used during the encryption process. keyDict={'a': 17,'b': 3,'c':16,'d':26,'e':6,'f':19,'g':10,'h':12, 'i':22,'j':8,'k': 11,'l':2,'m':18,'n':9,'o':23,'p':7, 'q':5,'r': 20,'s': 1,'t': 24,'u':13,'v':25,'w':21,'x':15, 'y':4,'z': 14, ' ':42, '.':0,'!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33,'&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict2={' ': 43, 'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17,'\n': 42, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26, ' ':0, '!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33, '&amp;': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38} refDict={0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 42:'\n', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 43:' ', 32: ':', 33: "'", 34: '@', 35: '#', 36: '$', 37: '%', 38: '^', 39: '&amp;', 40: '*', 41: '~', 27: '!', 28: '?', 29: ',', 30: '.', 31: ';'} #switch1 reverses a list. It is its own inverse, so we don't need an unswitch function. def switch1(l): return l[::-1] #switch2 takes a list as input and moves every fourth entry to the front #so switch2([a,b,c,d,e,f,g]) returns ([a,e,b,c,d,f,g]) #unswitch2 undoes this, so unswitch2([a,e,c,d,f,g]) returns [a,b,c,d,e,f,g] def switch2(l): List4 = [] ListNot4 = [] for i in range(0,len(l)): if i%4 == 0: List4.append(l[i]) else: ListNot4.append(l[i]) return List4+ListNot4 def unswitch2(l): num4 = len(l)/4 + 1 fixedList = l[num4:] for i in range (0,num4): fixedList.insert(4*i,l[i]) return fixedList #switch3 takes a list as input and returns a list with the first half moved to the end. #so switch3([a,b,c,d,e,f]) returns [d,e,f,a,b,c] #for lists of odd length, switch3 puts the separation closer to the beginning of the list, so the #middle entry becomes the first entry. #For example, switch3([a,b,c,d,e,f,g]) returns [d,e,f,g,a,b,c] def switch3(l): return l[len(l)/2:] + l[:len(l)/2] def unswitch3(l): if len(l)%2==0: return switch3(l) else: return l[len(l)/2+1:] + l[:len(l)/2+1] ################################## #This is the Crypt function. ################################## def Crypt(text, cipher): counter=0 text=text.lower() cipher=cipher.lower() keyValue=[] textValue=[] newValue=[] newString='' for letter in cipher: keyValue.append(keyDict[letter]) for letter in text: textValue.append(refDict2[letter]) for num in textValue: newValue.append(num+keyValue[counter%len(keyValue)]) counter+=1 newValue = switch1(newValue) newValue = switch2(newValue) newValue = switch3(newValue) for num in newValue: newString+=refDict[num%43] return newString ################################## #This is the Decrypt function ################################## def Decrypt(encryptedText, cipher): counter=0 cipher=cipher.lower() keyValue=[] textValue=[] finalValue=[] finalString='' for letter in encryptedText: textValue.append(refDict2[letter]) textValue = unswitch3(textValue) textValue = unswitch2(textValue) textValue = switch1(textValue) for letter in cipher: keyValue.append(keyDict[letter]) for num in textValue: finalValue.append((num-keyValue[counter%len(keyValue)])%43) counter+=1 for num in finalValue: finalString+=refDict[num] return finalString ################################## #This is the user interface. ################################## choice=raw_input('Would you like to: 1)Encrypt or 2)Decrypt? Pick 1 or 2: ') if choice=='1': textType=raw_input("Would you like to: 1)encrypt a text file or 2) input the text to be encrypted? Pick 1 or 2: ") if textType=='1': cryptName=raw_input( 'Please enter the name of the text file you would like to encrypt(eg. text.txt): ') newName=raw_input('Please name the file in which the encrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter your personal encryption key(eg. secret code):" ) cryptFile=open(cryptName, 'r') newFile=open(newName, 'w') print &gt;&gt; newFile, Crypt(cryptFile.read(),cipher) cryptFile.close() newFile.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to encrypt(eg. computers rock!): ') cipher=raw_input("Now enter your personal encryption key (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Crypt(inputText, cipher) else: print 'Try again!' elif choice=='2': textType=raw_input("Would you like to:1)decrypt a text file or 2) input the text to be decrypted? Pick 1 or 2: ") if textType=='1': decryptName=raw_input( 'Please enter the name of the text file you would like to decrypt(eg. text.txt): ') newName2=raw_input('Please name the file in which the decrypted text will be stored(eg. secret.txt):' ) cipher=raw_input("Now enter the encryption key that was used to encrypt the file(eg. secret code):" ) #Text decrypt decryptFile=open(decryptName, 'r') newFile2=open(newName2, 'w') print&gt;&gt; newFile2, Decrypt(decryptFile.read(),cipher) #other stuff #textTodecrypt=decryptFile.read() #newFile2.writelines(Decrypt(textTodecrypt, cipher)) decryptFile.close() newFile2.close() print "Ok, all done!" elif textType=='2': inputText=raw_input('Ok, please input the text you would like to decrypt(eg. dig&amp;ak:do): ') cipher=raw_input("Now enter the encryption key that was used to encrypt the text (eg. ultra secret code): ") if inputText=='': print 'Oops, no text was entered! Try again!' else: print Decrypt(inputText, cipher) print "Have a nice day!" #there is an issue with the newline character </code></pre>
0
2009-05-12T15:35:10Z
12,133,036
<p>A simple and fast way to replace the usual escapes with the corresponding ASCII characters is using the <code>str.decode</code> method:</p> <pre><code>&gt;&gt;&gt; s = r'This string has\tsome\nescapes' &gt;&gt;&gt; s 'This string has\\tsome\\nescapes' &gt;&gt;&gt; s.decode('string-escape') 'This string has\tsome\nescapes' &gt;&gt;&gt; print s This string has\tsome\nescapes &gt;&gt;&gt; print s.decode('string-escape') This string has some escapes </code></pre>
0
2012-08-26T19:05:06Z
[ "python" ]
Strange python behaviour
853,407
<p>I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand</p> <pre><code>In [1]: 2**2 Out[1]: 4 In [2]: 2**2**2 Out[2]: 16 In [3]: 2**2**2**2 Out[3]: 65536 In [4]: 2**2**2**2**2 </code></pre> <p>The answer to [4] is <em>not</em> 4294967296L, it's a very long number, but I can't really figure out why.</p> <p>The number can be found here: <a href="http://pastie.org/475714" rel="nofollow">http://pastie.org/475714</a></p> <p>(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)<br /> (Mac OS X 10.5.6, Python 2.5.1)</p>
7
2009-05-12T15:36:58Z
853,449
<p>Python is going right to left on the mathematical power operation. For example, IN[2] is doing:</p> <p>2**(4) = 16</p> <p>IN[3] = 2**2**2**2 = 2**2**(4) = 2**16 = 65536</p> <p>You would need parenthesis if you want it to calculate from left to right. The reason OUT[4] is not outputting the answer you want is because the number is astronomical and Python cannot print it out. </p> <p>2^65536 = extremely huge</p>
16
2009-05-12T15:42:53Z
[ "python", "ipython" ]
Strange python behaviour
853,407
<p>I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand</p> <pre><code>In [1]: 2**2 Out[1]: 4 In [2]: 2**2**2 Out[2]: 16 In [3]: 2**2**2**2 Out[3]: 65536 In [4]: 2**2**2**2**2 </code></pre> <p>The answer to [4] is <em>not</em> 4294967296L, it's a very long number, but I can't really figure out why.</p> <p>The number can be found here: <a href="http://pastie.org/475714" rel="nofollow">http://pastie.org/475714</a></p> <p>(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)<br /> (Mac OS X 10.5.6, Python 2.5.1)</p>
7
2009-05-12T15:36:58Z
853,460
<p>The precedence of the ** operator makes the evaluation goes from right-to-left (instead of the expected left-to-right). In other words:</p> <pre><code>2**2**2**2 == (2**(2**(2**2))) </code></pre>
7
2009-05-12T15:44:27Z
[ "python", "ipython" ]
Strange python behaviour
853,407
<p>I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand</p> <pre><code>In [1]: 2**2 Out[1]: 4 In [2]: 2**2**2 Out[2]: 16 In [3]: 2**2**2**2 Out[3]: 65536 In [4]: 2**2**2**2**2 </code></pre> <p>The answer to [4] is <em>not</em> 4294967296L, it's a very long number, but I can't really figure out why.</p> <p>The number can be found here: <a href="http://pastie.org/475714" rel="nofollow">http://pastie.org/475714</a></p> <p>(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)<br /> (Mac OS X 10.5.6, Python 2.5.1)</p>
7
2009-05-12T15:36:58Z
853,464
<p>This is because the order of precedence in Python causes this equation to be evaluated from right-to-left.</p> <pre><code>&gt;&gt;&gt; 2**2 4 &gt;&gt;&gt; 2**2**2 16 &gt;&gt;&gt; 2**(2**2) 16 &gt;&gt;&gt; 2**2**2**2 65536 &gt;&gt;&gt; 2**2**(2**2) 65536 &gt;&gt;&gt; 2**(2**(2**2)) 65536 &gt;&gt;&gt; 2**2**2**2**2 57896044618658097711785492504343953926634992332820282019728792003956564819968L &gt;&gt;&gt; 2**2**2**(2**2) 57896044618658097711785492504343953926634992332820282019728792003956564819968L &gt;&gt;&gt; 2**2**(2**(2**2)) 57896044618658097711785492504343953926634992332820282019728792003956564819968L &gt;&gt;&gt; 2**(2**(2**(2**2))) 57896044618658097711785492504343953926634992332820282019728792003956564819968L &gt;&gt;&gt; 2**255 57896044618658097711785492504343953926634992332820282019728792003956564819968L </code></pre>
4
2009-05-12T15:45:34Z
[ "python", "ipython" ]
Strange python behaviour
853,407
<p>I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand</p> <pre><code>In [1]: 2**2 Out[1]: 4 In [2]: 2**2**2 Out[2]: 16 In [3]: 2**2**2**2 Out[3]: 65536 In [4]: 2**2**2**2**2 </code></pre> <p>The answer to [4] is <em>not</em> 4294967296L, it's a very long number, but I can't really figure out why.</p> <p>The number can be found here: <a href="http://pastie.org/475714" rel="nofollow">http://pastie.org/475714</a></p> <p>(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)<br /> (Mac OS X 10.5.6, Python 2.5.1)</p>
7
2009-05-12T15:36:58Z
853,469
<p>Evaluating right-to-left, let's look at the steps Python is going through to get these answers:</p> <pre><code>2**2 4 2**(2**2) 2**(4) 16 2**(2**(2**2)) 2**(2**(4)) 2**(16) 65536 2**(2**(2**(2**2))) 2**(2**(2**(4))) 2**(2**(16)) 2**(65536) 2.0035299304068464649790723515603e+19728 </code></pre>
3
2009-05-12T15:46:16Z
[ "python", "ipython" ]
Strange python behaviour
853,407
<p>I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand</p> <pre><code>In [1]: 2**2 Out[1]: 4 In [2]: 2**2**2 Out[2]: 16 In [3]: 2**2**2**2 Out[3]: 65536 In [4]: 2**2**2**2**2 </code></pre> <p>The answer to [4] is <em>not</em> 4294967296L, it's a very long number, but I can't really figure out why.</p> <p>The number can be found here: <a href="http://pastie.org/475714" rel="nofollow">http://pastie.org/475714</a></p> <p>(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)<br /> (Mac OS X 10.5.6, Python 2.5.1)</p>
7
2009-05-12T15:36:58Z
854,650
<p>As the other answers already said, it's because <code>**</code> is evaluated from right to left. Here is the <a href="http://docs.python.org/reference/expressions.html#summary" rel="nofollow">documentation link</a>, where all the precedences are described.</p>
4
2009-05-12T20:15:14Z
[ "python", "ipython" ]
How should I store state for a long-running process invoked from Django?
853,421
<p>I am working on a Django application which allows a user to upload files. I need to perform some server-side processing on these files before sending them on to <a href="http://aws.amazon.com/s3/">Amazon S3</a>. After reading the responses to <a href="http://stackoverflow.com/questions/219329/django-fastcgi-how-to-manage-a-long-running-process">this question</a> and <a href="http://iraniweb.com/blog/?p=56">this blog post</a> I decided that the best manner in which to handle this is to have my view handler invoke a method on <a href="http://pyro.sourceforge.net/">Pyro</a> remote object to perform the processing asynchronously and then immediately return an Http 200 to the client. I have this prototyped and it seems to work well, however, I would also like to store the state of the processing so that the client can poll the application to see if the file has been processed and uploaded to S3.</p> <p>I can handle the polling easily enough, but I am not sure where the appropriate location is to store the process state. It needs to be writable by the Pyro process and readable by my polling view.</p> <ul> <li>I am hesitant to add columns to the database for data which should really only persist for 30 to 60 seconds. </li> <li>I have considered using Django's <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">low-level cache API</a> and using a file id as the key, however, I don't believe this is really what the cache framework is designed for and I'm not sure what unforeseen problems there might be with going this route.</li> <li>Lastly, I have considered storing state in the Pyro object doing the processing, but then it still seems like I would need to add a boolean "processing_complete" database column so that the view knows whether or not to query state from the Pyro object.</li> </ul> <p>Of course, there are also some data integrity concerns with decoupling state from the database (what happens if the server goes down and all this data is in-memory?). I am to hear how more seasoned web application developers would handle this sort of stateful processing.</p>
5
2009-05-12T15:39:05Z
853,611
<p>We do this by having a "Request" table in the database.</p> <p>When the upload arrives, we create the uploaded File object, and create a Request.</p> <p>We start the background batch processor.</p> <p>We return a 200 "we're working on it" page -- it shows the Requests and their status.</p> <p>Our batch processor uses the Django ORM. When it finishes, it updates the Request object. We can (but don't) send an email notification. Mostly, we just update the status so that the user can log in again and see that processing has completed.</p> <p><hr /></p> <p>Batch Server Architecture notes.</p> <p>It's a WSGI server that waits on a port for a batch processing request. The request is a REST POST with an ID number; the batch processor looks this up in the database and processes it.</p> <p>The server is started automagically by our REST interface. If it isn't running, we spawn it. This makes a user transaction appear slow, but, oh well. It's not supposed to crash. </p> <p>Also, we have a simple crontab to check that it's running. At most, it will be down for 30 minutes between "are you alive?" checks. We don't have a formal startup script (we run under Apache with mod_wsgi), but we may create a "restart" script that touches the WSGI file and then does a POST to a URL that does a health-check (and starts the batch processor).</p> <p>When the batch server starts, there may be unprocessed requests for which it has never gotten a POST. So, the default startup is to pull ALL work out of the Request queue -- assuming it may have missed something. </p>
6
2009-05-12T16:12:37Z
[ "python", "django", "asynchronous", "amazon-s3", "pyro" ]
How should I store state for a long-running process invoked from Django?
853,421
<p>I am working on a Django application which allows a user to upload files. I need to perform some server-side processing on these files before sending them on to <a href="http://aws.amazon.com/s3/">Amazon S3</a>. After reading the responses to <a href="http://stackoverflow.com/questions/219329/django-fastcgi-how-to-manage-a-long-running-process">this question</a> and <a href="http://iraniweb.com/blog/?p=56">this blog post</a> I decided that the best manner in which to handle this is to have my view handler invoke a method on <a href="http://pyro.sourceforge.net/">Pyro</a> remote object to perform the processing asynchronously and then immediately return an Http 200 to the client. I have this prototyped and it seems to work well, however, I would also like to store the state of the processing so that the client can poll the application to see if the file has been processed and uploaded to S3.</p> <p>I can handle the polling easily enough, but I am not sure where the appropriate location is to store the process state. It needs to be writable by the Pyro process and readable by my polling view.</p> <ul> <li>I am hesitant to add columns to the database for data which should really only persist for 30 to 60 seconds. </li> <li>I have considered using Django's <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">low-level cache API</a> and using a file id as the key, however, I don't believe this is really what the cache framework is designed for and I'm not sure what unforeseen problems there might be with going this route.</li> <li>Lastly, I have considered storing state in the Pyro object doing the processing, but then it still seems like I would need to add a boolean "processing_complete" database column so that the view knows whether or not to query state from the Pyro object.</li> </ul> <p>Of course, there are also some data integrity concerns with decoupling state from the database (what happens if the server goes down and all this data is in-memory?). I am to hear how more seasoned web application developers would handle this sort of stateful processing.</p>
5
2009-05-12T15:39:05Z
854,088
<p>So, it's a job queue that you need. For your case, I would absolutely go with the DB to save state, even if those states are short lived. It sounds like that will meet all of your requirements, and isn't terribly difficult to implement since you already have all of the moving parts there, available to you. Keep it simple unless you <em>need</em> something more complex.</p> <p>If you need something more powerful or more sophisticated, I'd look at something like <a href="http://www.gearman.org" rel="nofollow">Gearman</a>.</p>
1
2009-05-12T18:13:47Z
[ "python", "django", "asynchronous", "amazon-s3", "pyro" ]
How should I store state for a long-running process invoked from Django?
853,421
<p>I am working on a Django application which allows a user to upload files. I need to perform some server-side processing on these files before sending them on to <a href="http://aws.amazon.com/s3/">Amazon S3</a>. After reading the responses to <a href="http://stackoverflow.com/questions/219329/django-fastcgi-how-to-manage-a-long-running-process">this question</a> and <a href="http://iraniweb.com/blog/?p=56">this blog post</a> I decided that the best manner in which to handle this is to have my view handler invoke a method on <a href="http://pyro.sourceforge.net/">Pyro</a> remote object to perform the processing asynchronously and then immediately return an Http 200 to the client. I have this prototyped and it seems to work well, however, I would also like to store the state of the processing so that the client can poll the application to see if the file has been processed and uploaded to S3.</p> <p>I can handle the polling easily enough, but I am not sure where the appropriate location is to store the process state. It needs to be writable by the Pyro process and readable by my polling view.</p> <ul> <li>I am hesitant to add columns to the database for data which should really only persist for 30 to 60 seconds. </li> <li>I have considered using Django's <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">low-level cache API</a> and using a file id as the key, however, I don't believe this is really what the cache framework is designed for and I'm not sure what unforeseen problems there might be with going this route.</li> <li>Lastly, I have considered storing state in the Pyro object doing the processing, but then it still seems like I would need to add a boolean "processing_complete" database column so that the view knows whether or not to query state from the Pyro object.</li> </ul> <p>Of course, there are also some data integrity concerns with decoupling state from the database (what happens if the server goes down and all this data is in-memory?). I am to hear how more seasoned web application developers would handle this sort of stateful processing.</p>
5
2009-05-12T15:39:05Z
1,899,376
<p>I know this is an old question but someone may find my answer useful even after all this time, so here goes.</p> <p>You can of course use database as queue but there are solutions developed exactly for that purpose.</p> <p><a href="http://www.amqp.org/">AMQP</a> is made just for that. Together with <a href="http://ask.github.com/celery/introduction.html">Celery</a> or <a href="http://github.com/ask/carrot">Carrot</a> and a broker server like <a href="http://www.rabbitmq.com/">RabbitMQ</a> or <a href="http://www.zeromq.org/">ZeroMQ</a>.</p> <p>That's what we are using in our latest project and it is working great.</p> <p>For your problem Celery and RabbitMQ seems like a best fit. RabbitMQ provides persistency of your messages, and Celery exposes easy views for polling to check the status of processes run in parallel.</p> <p>You may also be interested in <a href="http://code.google.com/p/octopy/">octopy</a>.</p>
5
2009-12-14T07:06:12Z
[ "python", "django", "asynchronous", "amazon-s3", "pyro" ]
Can I Pass Dictionary Values/Entry and Keys to function
853,483
<p>I am writing a function and intended to use a dictionary key and its value as parameters. For example:</p> <pre><code>testDict={'x':2,'xS':4} def newFunct(key,testDict['key']): newvalue=key+str(testDict['key']) return newValue for key in testDict: newValue=newFunct(key,testDict[key]) print newValue </code></pre> <p>I get a SyntaxError: invalid syntax when I hit the return button after typing the semicolon. I am guessing this is telling me I can't pass a dictionary value in that form. Presumably I can define a new variable</p> <pre><code>for key in testDict: xdixt=testDict[key] newValue=newFunct(key,xdixt) </code></pre> <p>and def the function using xdixt</p> <p>but I am hoping there is some trick that I am missing. I Googled and found some reference to unpacking a dictionary but that didn't seem to work.</p> <p>This Python stuff is really cool. My question was came about because I am trying to use some values I stored in a dictionary to create a new directory. Based on the material I read from Stephan's answer I wondered about how to generalize the information I learned. My directory name has five different pieces to it, each piece is the result of processing the values from myDict. The expression to create the directory name was getting too complicated and in my opinion too complicated to easily read. so I wondered if I could use the same approach to put the pieces into a list and then unpack them when it came time to create the directory name and it worked!</p> <pre><code>def createDirectory(myKey,**myDict): pathList=[] pathList.append(myDict['subKey1']) pathList.append(myDict['subKey2'].lstrip('0')) pathList.append(myDict['subKey3']) etc myPath=os.path.join(*myList) os.makedirs(myPath) return(myPath) </code></pre>
0
2009-05-12T15:50:15Z
853,505
<p>why don't you just do:</p> <pre><code>[k + str(v) for k, v in test_dict.iteritems()] </code></pre> <p>or for py3k:</p> <pre><code>[k + str(v) for k, v in test_dict.items()] </code></pre> <p><strong>edit</strong></p> <pre><code>def f(k, v): print(k, v) # or do something much more complicated for k, v in testDict.items(): f(k, v) </code></pre>
0
2009-05-12T15:53:19Z
[ "python", "function", "dictionary" ]
Can I Pass Dictionary Values/Entry and Keys to function
853,483
<p>I am writing a function and intended to use a dictionary key and its value as parameters. For example:</p> <pre><code>testDict={'x':2,'xS':4} def newFunct(key,testDict['key']): newvalue=key+str(testDict['key']) return newValue for key in testDict: newValue=newFunct(key,testDict[key]) print newValue </code></pre> <p>I get a SyntaxError: invalid syntax when I hit the return button after typing the semicolon. I am guessing this is telling me I can't pass a dictionary value in that form. Presumably I can define a new variable</p> <pre><code>for key in testDict: xdixt=testDict[key] newValue=newFunct(key,xdixt) </code></pre> <p>and def the function using xdixt</p> <p>but I am hoping there is some trick that I am missing. I Googled and found some reference to unpacking a dictionary but that didn't seem to work.</p> <p>This Python stuff is really cool. My question was came about because I am trying to use some values I stored in a dictionary to create a new directory. Based on the material I read from Stephan's answer I wondered about how to generalize the information I learned. My directory name has five different pieces to it, each piece is the result of processing the values from myDict. The expression to create the directory name was getting too complicated and in my opinion too complicated to easily read. so I wondered if I could use the same approach to put the pieces into a list and then unpack them when it came time to create the directory name and it worked!</p> <pre><code>def createDirectory(myKey,**myDict): pathList=[] pathList.append(myDict['subKey1']) pathList.append(myDict['subKey2'].lstrip('0')) pathList.append(myDict['subKey3']) etc myPath=os.path.join(*myList) os.makedirs(myPath) return(myPath) </code></pre>
0
2009-05-12T15:50:15Z
853,508
<p>Is this what you want?</p> <pre><code>def func(**kwargs): for key, value in kwargs.items(): pass # Do something func(**myDict) # Call func with the given dict as key/value parameters </code></pre> <p>(See the <a href="http://docs.python.org/tutorial/controlflow.html#keyword-arguments" rel="nofollow">documentation</a> for more about keyword arguments. The keys in <code>myDict</code> must be strings.)</p> <p><hr /></p> <p><strong>Edit</strong>: you edited your question to include the following:</p> <blockquote> <p>I think the ** notation in front of myDict instructs the function to expect a dictionary and to unpack the key (the first *) and the value, the second *</p> </blockquote> <p>This is not correct. To understand what is happening, you must consider the following:</p> <ul> <li>A function can have multiple <em>formal parameters</em> (<code>a</code> and <code>b</code> in this case):</li> </ul> <pre>def f1(a, b): pass</pre> <ul> <li>We can pass <em>positional arguments</em> to such function (like in most other languages):</li> </ul> <pre>f1(2, 3)</pre> <ul> <li>We can also pass <em>keyword arguments</em>:</li> </ul> <pre>f1(a=2, b=3)</pre> <ul> <li>We can also mix these, <em>but the positional arguments must come first</em>:</li> </ul> <pre>f1(2, b=3) f1(a=2, 3) # SyntaxError: non-keyword arg after keyword arg</pre> <ul> <li>There is a way to let a function accept an arbitrary number of positional arguments, which it can access as a tuple (<code>args</code> in this case):</li> </ul> <pre>def f2(*args): assert isinstance(args, tuple)</pre> <ul> <li>Now we can call <code>f2</code> using separately specified arguments, or using a list whose contents first need to be <em>unpacked</em>, using a syntax similar to the notation used for <code>*args</code>:</li> </ul> <pre>f2(2, 3) f2(*[2, 3])</pre> <ul> <li>Likewise, an arbitrary number of keyword arguments may be accepted:</li> </ul> <pre>def f3(**kwargs): pass</pre> <ul> <li>Note that <code>f3</code> <em>does not</em> ask for a single argument of type <code>dict</code>. This is the kind of invocations it expects:</li> </ul> <pre>f3(a=2, b=3) f3(**{'a': 2, 'b': 3})</pre> <ul> <li>All arguments to <code>f3</code> must be named:</li> </ul> <pre>f3(2, 3) # TypeError: f3() takes exactly 0 arguments (2 given)</pre> <p>Putting all of this together, and remembering that positional arguments must come first, we may have:</p> <pre><code>&gt;&gt;&gt; def f4(a, b, *args, **kwargs): ... print('%r, %r' % (args, kwargs)) ... &gt;&gt;&gt; f4(2, 3) (), {} &gt;&gt;&gt; f4(2, 3, 4, 5) (4, 5), {} &gt;&gt;&gt; f4(2, 3, x=4, y=5) (), {'y': 5, 'x': 4} &gt;&gt;&gt; f4(2, 3, 4, 5, x=6, y=7) (4, 5), {'y': 7, 'x': 6} &gt;&gt;&gt; f4(2, *[3, 4, 5], **{'x': 6, 'y': 7}) (4, 5), {'y': 7, 'x': 6} </code></pre> <p>Pay special attention to the following two errors:</p> <pre><code>&gt;&gt;&gt; f4(2) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: f4() takes at least 2 arguments (1 given) &gt;&gt;&gt; f4(2, 3, a=4) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: f4() got multiple values for keyword argument 'a' </code></pre> <p>The second error should help you explain this behavior:</p> <pre><code>&gt;&gt;&gt; f4(**{'foo': 0, 'a': 2, 'b': 3, 'c': 4}) (), {'c': 4, 'foo': 0} </code></pre>
5
2009-05-12T15:53:30Z
[ "python", "function", "dictionary" ]
Can I Pass Dictionary Values/Entry and Keys to function
853,483
<p>I am writing a function and intended to use a dictionary key and its value as parameters. For example:</p> <pre><code>testDict={'x':2,'xS':4} def newFunct(key,testDict['key']): newvalue=key+str(testDict['key']) return newValue for key in testDict: newValue=newFunct(key,testDict[key]) print newValue </code></pre> <p>I get a SyntaxError: invalid syntax when I hit the return button after typing the semicolon. I am guessing this is telling me I can't pass a dictionary value in that form. Presumably I can define a new variable</p> <pre><code>for key in testDict: xdixt=testDict[key] newValue=newFunct(key,xdixt) </code></pre> <p>and def the function using xdixt</p> <p>but I am hoping there is some trick that I am missing. I Googled and found some reference to unpacking a dictionary but that didn't seem to work.</p> <p>This Python stuff is really cool. My question was came about because I am trying to use some values I stored in a dictionary to create a new directory. Based on the material I read from Stephan's answer I wondered about how to generalize the information I learned. My directory name has five different pieces to it, each piece is the result of processing the values from myDict. The expression to create the directory name was getting too complicated and in my opinion too complicated to easily read. so I wondered if I could use the same approach to put the pieces into a list and then unpack them when it came time to create the directory name and it worked!</p> <pre><code>def createDirectory(myKey,**myDict): pathList=[] pathList.append(myDict['subKey1']) pathList.append(myDict['subKey2'].lstrip('0')) pathList.append(myDict['subKey3']) etc myPath=os.path.join(*myList) os.makedirs(myPath) return(myPath) </code></pre>
0
2009-05-12T15:50:15Z
854,162
<p>Not sure why we are bringing in kwargs, this is much simpler than that. You said you're new to Python, I think you just need some Python fundamentals here.</p> <pre><code>def newFunct(key,testDict['key']): </code></pre> <p>Should be:</p> <pre><code>def newFunct(key, val): </code></pre> <p>There's no reason to use any special syntax on your second parameter to indicate that it's coming from a dictionary. It's just a parameter, you just happen to be passing the value from a dictionary item into it.</p> <p>Further, once it's in the function, there's no reason to treat it in a special way either. At this point it's just a value. Which means that:</p> <pre><code>newvalue=key+str(testDict[key]) </code></pre> <p>Can now just be:</p> <pre><code>newvalue=key+str(val) </code></pre> <p>So when you call it like this (as you did):</p> <pre><code>newValue=newFunct(key,testDict[key]) </code></pre> <p>testDict[key] resolves to the value at 'key', which just becomes "val" in the function.</p> <p><hr /></p> <p>An alternate way, if you see it fit for whatever reason (and this is just something that's good to know), you could define the function thusly:</p> <pre><code>def newFunct(key, testDict): </code></pre> <p>Again, the second parameter is just a parameter, so we use the same syntax, but now we're expecting it to be a dict, so we should use it like one:</p> <pre><code>newvalue=key+str(testDict[key]) </code></pre> <p>(Note: don't put quotes around 'key' in this case. We're referring to the variable called 'key', not a key called 'key'). When you call the function, it looks like this:</p> <pre><code>newValue=newFunct(key,testDict) </code></pre> <p>So unlike the first case where you're just passing one variable from the dictionary, you're passing a reference to the whole dictionary into the function this time.</p> <p>Hope that helps.</p>
2
2009-05-12T18:30:57Z
[ "python", "function", "dictionary" ]
Can I Pass Dictionary Values/Entry and Keys to function
853,483
<p>I am writing a function and intended to use a dictionary key and its value as parameters. For example:</p> <pre><code>testDict={'x':2,'xS':4} def newFunct(key,testDict['key']): newvalue=key+str(testDict['key']) return newValue for key in testDict: newValue=newFunct(key,testDict[key]) print newValue </code></pre> <p>I get a SyntaxError: invalid syntax when I hit the return button after typing the semicolon. I am guessing this is telling me I can't pass a dictionary value in that form. Presumably I can define a new variable</p> <pre><code>for key in testDict: xdixt=testDict[key] newValue=newFunct(key,xdixt) </code></pre> <p>and def the function using xdixt</p> <p>but I am hoping there is some trick that I am missing. I Googled and found some reference to unpacking a dictionary but that didn't seem to work.</p> <p>This Python stuff is really cool. My question was came about because I am trying to use some values I stored in a dictionary to create a new directory. Based on the material I read from Stephan's answer I wondered about how to generalize the information I learned. My directory name has five different pieces to it, each piece is the result of processing the values from myDict. The expression to create the directory name was getting too complicated and in my opinion too complicated to easily read. so I wondered if I could use the same approach to put the pieces into a list and then unpack them when it came time to create the directory name and it worked!</p> <pre><code>def createDirectory(myKey,**myDict): pathList=[] pathList.append(myDict['subKey1']) pathList.append(myDict['subKey2'].lstrip('0')) pathList.append(myDict['subKey3']) etc myPath=os.path.join(*myList) os.makedirs(myPath) return(myPath) </code></pre>
0
2009-05-12T15:50:15Z
854,750
<p>From your description is seems like testDict is some sort of global variable with respect to the function. If this is the case - why do you even need to pass it to the function?</p> <p>Instead of your code:</p> <pre><code>testDict={'x':2,'xS':4} def newFunct(key,testDict[key]): newvalue=key+str(testDict[key]) return newValue for key in testDict: newValue=newFunct(key,testDict[key]) print newValue </code></pre> <p>You can simply use:</p> <pre><code>testDict={'x':2,'xS':4} def newFunct(key): newvalue=key+str(testDict[key]) return newValue for key in testDict: newValue=newFunct(key) print newValue </code></pre> <p>If testDict is not meant to be in the global scope (which makes sense...), I would recommend simply passing a name for the dictionary and not "messing around" with variable length argument lists in this case:</p> <pre><code>testDict={'x':2,'xS':4} def newFunct(key,dictionary): newvalue=key+str(dictionary[key]) return newValue for key in testDict: newValue=newFunct(key,testDict) print newValue </code></pre>
0
2009-05-12T20:38:54Z
[ "python", "function", "dictionary" ]
Do I need PyISAPIe to run Django on IIS6?
853,755
<p>It seems that all roads lead to having to use <a href="http://pypi.python.org/pypi/PyISAPIe/1.0.130" rel="nofollow">PyISAPIe</a> to get <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> running on IIS6. This becomes a problem for us because it appears <a href="http://groups.google.com/group/pyisapie/web/multiple-instances-of-django-on-iis-with-pyisapie?hl=en" rel="nofollow">you need separate application pools per PyISAPIe/Django instance</a> which is something we'd prefer not to do.</p> <p>Does anyone have any advice/guidance, or can share their experiences (particularly in a shared Windows hosting environment)?</p>
0
2009-05-12T16:50:46Z
856,894
<p>Django runs well on any WSGI infrastructure (much like any other modern Python web app framework) and there are several ways to run WSGI on IIS, e.g. see <a href="http://code.google.com/p/isapi-wsgi/" rel="nofollow">http://code.google.com/p/isapi-wsgi/</a> .</p>
1
2009-05-13T09:05:52Z
[ "python", "django", "iis-6", "pyisapie" ]
Do I need PyISAPIe to run Django on IIS6?
853,755
<p>It seems that all roads lead to having to use <a href="http://pypi.python.org/pypi/PyISAPIe/1.0.130" rel="nofollow">PyISAPIe</a> to get <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> running on IIS6. This becomes a problem for us because it appears <a href="http://groups.google.com/group/pyisapie/web/multiple-instances-of-django-on-iis-with-pyisapie?hl=en" rel="nofollow">you need separate application pools per PyISAPIe/Django instance</a> which is something we'd prefer not to do.</p> <p>Does anyone have any advice/guidance, or can share their experiences (particularly in a shared Windows hosting environment)?</p>
0
2009-05-12T16:50:46Z
927,299
<p>You need separate application pools no matter what extension you use. This is because application pools split the handler DLLs into different w3wp.exe process instances. You might wonder why this is necessary:</p> <p>Look at Django's module setting: <code>os.environ["DJANGO_SETTINGS_MODULE"]</code>. That's the environment of the process, so if you change it for one ISAPI handler and then later another within the same application pool, they both point to the new <code>DJANGO_SETTINGS_MODULE</code>.</p> <p>There isn't any meaningful reason for this, so feel free to convince the Django developers they don't need to do it :)</p> <p>There are a few ways to hack around it but nothing works as cleanly as separate app pools.</p> <p>Unfortunately, isapi-wsgi won't fix the Django problem, and I'd recommend that you keep using PyISAPIe (disclaimer: I'm the developer! ;)</p>
3
2009-05-29T17:56:49Z
[ "python", "django", "iis-6", "pyisapie" ]
Creating a SQL Server database from Python
854,008
<p>I'm using Python with pywin32's adodbapi to write a script to create a SQL Server database and all its associated tables, views, and procedures. The problem is that Python's DBAPI requires that cursor.execute() be wrapped in a transaction that is only committed by cursor.commit(), and you can't execute a drop or create database statement in a user transaction. Any ideas on how to get around that?</p> <p>EDIT:</p> <p>There does not seem to be anything analogous to an autocommit parameter to either the connect() method of adodbapi or its cursor() method. I'd be happy to use pymssql instead of adodbapi, except that it truncates char and varchar datatypes at 255 characters.</p> <p>I did try this before posting; here's the traceback.</p> <pre><code>Traceback (most recent call last): File "demo.py", line 39, in &lt;module&gt; cur.execute("create database dummydatabase") File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 713, in execute self._executeHelper(operation,False,parameters) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 664, in _executeHelper self._raiseCursorError(DatabaseError,tracebackhistory) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 474, in _raiseCursorError eh(self.conn,self,errorclass,errorvalue) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 60, in standardErrorHandler raise errorclass(errorvalue) adodbapi.adodbapi.DatabaseError: --ADODBAPI Traceback (most recent call last): File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 650, in _executeHelper adoRetVal=self.cmd.Execute() File "&lt;COMObject ADODB.Command&gt;", line 3, in Execute File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 258, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft SQL Native Client', u'CREATE DATABASE statement not allowed within multi-statement transaction.', None, 0, -2147217900), None) -- on command: "create database dummydatabase" -- with parameters: None </code></pre>
2
2009-05-12T17:55:47Z
854,151
<p>create the actual db outside the transaction. I'm not familiar with python, but there has to be a way to execute a user given string on a database, use that with the actual create db command. Then use the adodbapi to do all the tables, etc and commit that transaction.</p>
0
2009-05-12T18:28:29Z
[ "python", "sql-server", "pywin32", "adodbapi" ]
Creating a SQL Server database from Python
854,008
<p>I'm using Python with pywin32's adodbapi to write a script to create a SQL Server database and all its associated tables, views, and procedures. The problem is that Python's DBAPI requires that cursor.execute() be wrapped in a transaction that is only committed by cursor.commit(), and you can't execute a drop or create database statement in a user transaction. Any ideas on how to get around that?</p> <p>EDIT:</p> <p>There does not seem to be anything analogous to an autocommit parameter to either the connect() method of adodbapi or its cursor() method. I'd be happy to use pymssql instead of adodbapi, except that it truncates char and varchar datatypes at 255 characters.</p> <p>I did try this before posting; here's the traceback.</p> <pre><code>Traceback (most recent call last): File "demo.py", line 39, in &lt;module&gt; cur.execute("create database dummydatabase") File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 713, in execute self._executeHelper(operation,False,parameters) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 664, in _executeHelper self._raiseCursorError(DatabaseError,tracebackhistory) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 474, in _raiseCursorError eh(self.conn,self,errorclass,errorvalue) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 60, in standardErrorHandler raise errorclass(errorvalue) adodbapi.adodbapi.DatabaseError: --ADODBAPI Traceback (most recent call last): File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 650, in _executeHelper adoRetVal=self.cmd.Execute() File "&lt;COMObject ADODB.Command&gt;", line 3, in Execute File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 258, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft SQL Native Client', u'CREATE DATABASE statement not allowed within multi-statement transaction.', None, 0, -2147217900), None) -- on command: "create database dummydatabase" -- with parameters: None </code></pre>
2
2009-05-12T17:55:47Z
854,284
<p>"The problem is that Python's DBAPI requires that cursor.execute() be wrapped in a transaction that is only committed by cursor.commit()"</p> <p>"and you can't execute a drop or create database statement in a user transaction."</p> <p>I'm not sure all of this is actually true for all DBAPI interfaces.</p> <p>Since you don't show the error messages, it may turn out that this is not true for ADODBAPI interface. Have you actually tried it? If so, what error message are you getting?</p> <p>A connection may not <em>always</em> be creating a "user transaction". You can often open connections with <code>autocommit=True</code> to get DDL-style autocommit.</p> <p>Also, you might want to consider using a different connection to do run DDL. </p> <p><a href="http://pymssql.sourceforge.net/" rel="nofollow">http://pymssql.sourceforge.net/</a> for example, shows DDL being executed like this.</p> <pre><code>import pymssql conn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase') cur = conn.cursor() cur.execute('CREATE TABLE persons(id INT, name VARCHAR(100))') </code></pre>
1
2009-05-12T18:55:13Z
[ "python", "sql-server", "pywin32", "adodbapi" ]
Creating a SQL Server database from Python
854,008
<p>I'm using Python with pywin32's adodbapi to write a script to create a SQL Server database and all its associated tables, views, and procedures. The problem is that Python's DBAPI requires that cursor.execute() be wrapped in a transaction that is only committed by cursor.commit(), and you can't execute a drop or create database statement in a user transaction. Any ideas on how to get around that?</p> <p>EDIT:</p> <p>There does not seem to be anything analogous to an autocommit parameter to either the connect() method of adodbapi or its cursor() method. I'd be happy to use pymssql instead of adodbapi, except that it truncates char and varchar datatypes at 255 characters.</p> <p>I did try this before posting; here's the traceback.</p> <pre><code>Traceback (most recent call last): File "demo.py", line 39, in &lt;module&gt; cur.execute("create database dummydatabase") File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 713, in execute self._executeHelper(operation,False,parameters) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 664, in _executeHelper self._raiseCursorError(DatabaseError,tracebackhistory) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 474, in _raiseCursorError eh(self.conn,self,errorclass,errorvalue) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 60, in standardErrorHandler raise errorclass(errorvalue) adodbapi.adodbapi.DatabaseError: --ADODBAPI Traceback (most recent call last): File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 650, in _executeHelper adoRetVal=self.cmd.Execute() File "&lt;COMObject ADODB.Command&gt;", line 3, in Execute File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 258, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft SQL Native Client', u'CREATE DATABASE statement not allowed within multi-statement transaction.', None, 0, -2147217900), None) -- on command: "create database dummydatabase" -- with parameters: None </code></pre>
2
2009-05-12T17:55:47Z
854,346
<p>The adodbapi connection object <code>conn</code> does automatically start a new transaction after every commit if the database supports transactions. DB-API requires autocommit to be turned off by default and it allows an API method to turn it back on, but I don't see one in adodbapi.</p> <p>You might be able to use the <code>conn.adoConn</code> property to hack around this, using the ADO api instead of DB-API to take you out of any transaction. Let me know if this works:</p> <pre><code>conn.adoConn.CommitTrans() cursor.execute('CREATE DATABASE ...') conn.adoConn.BeginTrans() </code></pre> <p>Here's the source for the <a href="http://pywin32.cvs.sourceforge.net/viewvc/pywin32/pywin32/adodbapi/adodbapi.py?revision=1.9&amp;view=markup#l%5F411" rel="nofollow">adodbapi commit() method</a>.</p>
1
2009-05-12T19:10:19Z
[ "python", "sql-server", "pywin32", "adodbapi" ]
Creating a SQL Server database from Python
854,008
<p>I'm using Python with pywin32's adodbapi to write a script to create a SQL Server database and all its associated tables, views, and procedures. The problem is that Python's DBAPI requires that cursor.execute() be wrapped in a transaction that is only committed by cursor.commit(), and you can't execute a drop or create database statement in a user transaction. Any ideas on how to get around that?</p> <p>EDIT:</p> <p>There does not seem to be anything analogous to an autocommit parameter to either the connect() method of adodbapi or its cursor() method. I'd be happy to use pymssql instead of adodbapi, except that it truncates char and varchar datatypes at 255 characters.</p> <p>I did try this before posting; here's the traceback.</p> <pre><code>Traceback (most recent call last): File "demo.py", line 39, in &lt;module&gt; cur.execute("create database dummydatabase") File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 713, in execute self._executeHelper(operation,False,parameters) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 664, in _executeHelper self._raiseCursorError(DatabaseError,tracebackhistory) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 474, in _raiseCursorError eh(self.conn,self,errorclass,errorvalue) File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 60, in standardErrorHandler raise errorclass(errorvalue) adodbapi.adodbapi.DatabaseError: --ADODBAPI Traceback (most recent call last): File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 650, in _executeHelper adoRetVal=self.cmd.Execute() File "&lt;COMObject ADODB.Command&gt;", line 3, in Execute File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 258, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft SQL Native Client', u'CREATE DATABASE statement not allowed within multi-statement transaction.', None, 0, -2147217900), None) -- on command: "create database dummydatabase" -- with parameters: None </code></pre>
2
2009-05-12T17:55:47Z
4,656,450
<p>I had this same issue while trying run commands over adodbapi (e.g. DBCC CHECKDB...) and joeforker's advice helped a bit. The problem I still had was that adodbapi automatically starts a transaction, so there was no way to execute something outside of a transaction.</p> <p>In the end I ended up disabling adodbapi's commit behaviour like this:</p> <pre><code>self.conn = adodbapi.connect(conn_str) # rollback the transaction that was started in Connection.__init__() self.conn.adoConn.RollbackTrans() # prevent adodbapi from trying to rollback a transaction in Connection.close() self.conn.supportsTransactions = False </code></pre> <p>As far as I can tell, this re-enables the standard SQL Server auto-commit functionality, i.e. each SQL statement is automatically committed. The downside is that there is no way for me to enabled transactions again (at the moment) if I wan't to run something within a transaction, since <code>Connection.commit()</code> will do nothing when <code>supportsTransactions == False</code>.</p>
0
2011-01-11T10:11:36Z
[ "python", "sql-server", "pywin32", "adodbapi" ]
How to establish communication between flex and python code build on Google App Engine
854,353
<p>I want to communicate using flex client with GAE, I am able to communicate using XMl from GAE to FLex but how should I post from flex3 to python code present on App Engine.</p> <p>Can anyone give me a hint about how to send login information from Flex to python Any ideas suggest me some examples.....please provide me some help </p> <p>Regards, Radhika</p>
0
2009-05-12T19:11:49Z
854,403
<p>Do a HTTP post from Flex to your AppEngine app using the URLRequest class.</p>
0
2009-05-12T19:22:11Z
[ "python", "flex", "google-app-engine" ]
How to establish communication between flex and python code build on Google App Engine
854,353
<p>I want to communicate using flex client with GAE, I am able to communicate using XMl from GAE to FLex but how should I post from flex3 to python code present on App Engine.</p> <p>Can anyone give me a hint about how to send login information from Flex to python Any ideas suggest me some examples.....please provide me some help </p> <p>Regards, Radhika</p>
0
2009-05-12T19:11:49Z
854,409
<p>Your question is somewhat vague, but this <a href="http://code.google.com/appengine/kb/general.html#auth" rel="nofollow">FAQ entry</a> might be a good start.</p>
0
2009-05-12T19:22:58Z
[ "python", "flex", "google-app-engine" ]
How to establish communication between flex and python code build on Google App Engine
854,353
<p>I want to communicate using flex client with GAE, I am able to communicate using XMl from GAE to FLex but how should I post from flex3 to python code present on App Engine.</p> <p>Can anyone give me a hint about how to send login information from Flex to python Any ideas suggest me some examples.....please provide me some help </p> <p>Regards, Radhika</p>
0
2009-05-12T19:11:49Z
854,560
<p>I've been able to use flex on GAE using the examples found at <a href="http://gaeswf.appspot.com/" rel="nofollow">The GAE SWF Project</a> which uses <a href="http://pyamf.org/" rel="nofollow">PyAMF</a>.</p>
2
2009-05-12T19:54:38Z
[ "python", "flex", "google-app-engine" ]
Change keyboard locks in Python
854,393
<p>Is there any way, in Python, to programmatically <em>change</em> the CAPS LOCK/NUM LOCK/SCROLL LOCK states?</p> <p>This isn't really a joke question - more like a real question for a joke program. I intend to use it for making the lights do funny things...</p>
16
2009-05-12T19:19:37Z
854,442
<p>If you're using windows you can use <a href="https://pypi.python.org/pypi/SendKeys/" rel="nofollow">SendKeys</a> for this I believe.</p> <p><a href="https://web.archive.org/web/20121125032946/http://www.rutherfurd.net/python/sendkeys" rel="nofollow">http://www.rutherfurd.net/python/sendkeys</a></p> <pre><code>import SendKeys SendKeys.SendKeys(""" {CAPSLOCK} {SCROLLOCK} {NUMLOCK} """) </code></pre>
14
2009-05-12T19:28:17Z
[ "python", "windows" ]
Change keyboard locks in Python
854,393
<p>Is there any way, in Python, to programmatically <em>change</em> the CAPS LOCK/NUM LOCK/SCROLL LOCK states?</p> <p>This isn't really a joke question - more like a real question for a joke program. I intend to use it for making the lights do funny things...</p>
16
2009-05-12T19:19:37Z
858,992
<p>On Linux here's a Python program to blink all the keyboard LEDs on and off:</p> <pre><code>import fcntl import os import time KDSETLED = 0x4B32 SCR_LED = 0x01 NUM_LED = 0x02 CAP_LED = 0x04 console_fd = os.open('/dev/console', os.O_NOCTTY) all_on = SCR_LED | NUM_LED | CAP_LED all_off = 0 while 1: fcntl.ioctl(console_fd, KDSETLED, all_on) time.sleep(1) fcntl.ioctl(console_fd, KDSETLED, all_off) time.sleep(1) </code></pre>
14
2009-05-13T16:32:23Z
[ "python", "windows" ]
Change keyboard locks in Python
854,393
<p>Is there any way, in Python, to programmatically <em>change</em> the CAPS LOCK/NUM LOCK/SCROLL LOCK states?</p> <p>This isn't really a joke question - more like a real question for a joke program. I intend to use it for making the lights do funny things...</p>
16
2009-05-12T19:19:37Z
21,021,632
<p>To set CAPS LOCK to a specific value using SendKeys it is important to first detect the state of CAPS LOCK. Here's how to do that in python (under windows):</p> <pre><code>import win32api,win32con def IsCapsLockOn(): # return 1 if CAPSLOCK is ON return win32api.GetKeyState(win32con.VK_CAPITAL) </code></pre>
2
2014-01-09T13:30:03Z
[ "python", "windows" ]
Change keyboard locks in Python
854,393
<p>Is there any way, in Python, to programmatically <em>change</em> the CAPS LOCK/NUM LOCK/SCROLL LOCK states?</p> <p>This isn't really a joke question - more like a real question for a joke program. I intend to use it for making the lights do funny things...</p>
16
2009-05-12T19:19:37Z
38,284,507
<p>For Windows:</p> <pre><code>#http://stackoverflow.com/questions/21549847/send-key-combination-with-python #https://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx import win32com.client as comclt wsh= comclt.Dispatch("WScript.Shell") wsh.SendKeys("abc") #types out abc directly into wherever you have your cursor (ex: right into this editor itself!) wsh.SendKeys("{NUMLOCK}{CAPSLOCK}{SCROLLLOCK}") #toggles the state of NumLock, CapsLock, and ScrollLock; remove whichever one you don't want to toggle </code></pre> <p>Sources:</p> <ol> <li><a href="http://stackoverflow.com/questions/21549847/send-key-combination-with-python">Send key combination with python</a></li> <li><a href="https://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx</a> </li> </ol> <p>Also, pay careful attention to Uri's answer about how to read the CapsLock state. To set an LED state specifically to true or false, you can't just blindly toggle, you have to know what the current state is first. He shows you how to read the CapsLock state. Here's how to read all 3 LED states:</p> <pre><code>#http://stackoverflow.com/questions/854393/change-keyboard-locks-in-python/854442#854442abc #https://support.microsoft.com/en-us/kb/177674 import win32api,win32con def isCapsLockOn(): "return 1 if CapsLock is ON" return win32api.GetKeyState(win32con.VK_CAPITAL) def isNumLockOn(): "return 1 if NumLock is ON" return win32api.GetKeyState(win32con.VK_NUMLOCK) def isScrollLockOn(): "return 1 if ScrollLock is ON" return win32api.GetKeyState(win32con.VK_SCROLL) print("IsCapsLockOn = ", IsCapsLockOn()) print("isNumLockOn = ", isNumLockOn()) print("isScrollLockOn = ", isScrollLockOn()) </code></pre>
0
2016-07-09T17:37:38Z
[ "python", "windows" ]
Is this Python producer-consumer lockless approach thread-safe?
854,906
<p>I recently wrote a program that used a simple producer/consumer pattern. It initially had a bug related to improper use of threading.Lock that I eventually fixed. But it made me think whether it's possible to implement producer/consumer pattern in a lockless manner.</p> <p>Requirements in my case were simple:</p> <ul> <li>One producer thread.</li> <li>One consumer thread.</li> <li>Queue has place for only one item.</li> <li>Producer can produce next item before the current one is consumed. The current item is therefore lost, but that's OK for me.</li> <li>Consumer can consume current item before the next one is produced. The current item is therefore consumed twice (or more), but that's OK for me.</li> </ul> <p>So I wrote this:</p> <pre><code>QUEUE_ITEM = None # this is executed in one threading.Thread object def producer(): global QUEUE_ITEM while True: i = produce_item() QUEUE_ITEM = i # this is executed in another threading.Thread object def consumer(): global QUEUE_ITEM while True: i = QUEUE_ITEM consume_item(i) </code></pre> <p>My question is: Is this code thread-safe?</p> <p>Immediate comment: this code isn't really lockless - I use CPython and it has GIL.</p> <p>I tested the code a little and it seems to work. It translates to some LOAD and STORE ops which are atomic because of GIL. But I also know that <code>del x</code> operation isn't atomic when x implements <code>__del__</code> method. So if my item has a <code>__del__</code> method and some nasty scheduling happens, things may break. Or not?</p> <p>Another question is: What kind of restrictions (for example on produced items' type) do I have to impose to make the above code work fine?</p> <p>My questions are only about theoretical possibility to exploit CPython's and GIL's quirks in order to come up with lockless (i.e. no locks like threading.Lock explicitly in code) solution.</p>
6
2009-05-12T21:15:48Z
854,963
<p>This is not <em>really</em> thread safe because producer could overwrite <code>QUEUE_ITEM</code> before consumer has consumed it and consumer could consume <code>QUEUE_ITEM</code> twice. As you mentioned, you're OK with that but most people aren't.</p> <p>Someone with more knowledge of cpython internals will have to answer you more theoretical questions.</p>
1
2009-05-12T21:31:55Z
[ "python", "locking", "thread-safety", "producer-consumer" ]
Is this Python producer-consumer lockless approach thread-safe?
854,906
<p>I recently wrote a program that used a simple producer/consumer pattern. It initially had a bug related to improper use of threading.Lock that I eventually fixed. But it made me think whether it's possible to implement producer/consumer pattern in a lockless manner.</p> <p>Requirements in my case were simple:</p> <ul> <li>One producer thread.</li> <li>One consumer thread.</li> <li>Queue has place for only one item.</li> <li>Producer can produce next item before the current one is consumed. The current item is therefore lost, but that's OK for me.</li> <li>Consumer can consume current item before the next one is produced. The current item is therefore consumed twice (or more), but that's OK for me.</li> </ul> <p>So I wrote this:</p> <pre><code>QUEUE_ITEM = None # this is executed in one threading.Thread object def producer(): global QUEUE_ITEM while True: i = produce_item() QUEUE_ITEM = i # this is executed in another threading.Thread object def consumer(): global QUEUE_ITEM while True: i = QUEUE_ITEM consume_item(i) </code></pre> <p>My question is: Is this code thread-safe?</p> <p>Immediate comment: this code isn't really lockless - I use CPython and it has GIL.</p> <p>I tested the code a little and it seems to work. It translates to some LOAD and STORE ops which are atomic because of GIL. But I also know that <code>del x</code> operation isn't atomic when x implements <code>__del__</code> method. So if my item has a <code>__del__</code> method and some nasty scheduling happens, things may break. Or not?</p> <p>Another question is: What kind of restrictions (for example on produced items' type) do I have to impose to make the above code work fine?</p> <p>My questions are only about theoretical possibility to exploit CPython's and GIL's quirks in order to come up with lockless (i.e. no locks like threading.Lock explicitly in code) solution.</p>
6
2009-05-12T21:15:48Z
854,968
<p>I think it's possible that a thread is interrupted while producing/consuming, especially if the items are big objects. Edit: this is just a wild guess. I'm no expert.</p> <p>Also the threads may produce/consume any number of items before the other one starts running.</p>
0
2009-05-12T21:32:56Z
[ "python", "locking", "thread-safety", "producer-consumer" ]
Is this Python producer-consumer lockless approach thread-safe?
854,906
<p>I recently wrote a program that used a simple producer/consumer pattern. It initially had a bug related to improper use of threading.Lock that I eventually fixed. But it made me think whether it's possible to implement producer/consumer pattern in a lockless manner.</p> <p>Requirements in my case were simple:</p> <ul> <li>One producer thread.</li> <li>One consumer thread.</li> <li>Queue has place for only one item.</li> <li>Producer can produce next item before the current one is consumed. The current item is therefore lost, but that's OK for me.</li> <li>Consumer can consume current item before the next one is produced. The current item is therefore consumed twice (or more), but that's OK for me.</li> </ul> <p>So I wrote this:</p> <pre><code>QUEUE_ITEM = None # this is executed in one threading.Thread object def producer(): global QUEUE_ITEM while True: i = produce_item() QUEUE_ITEM = i # this is executed in another threading.Thread object def consumer(): global QUEUE_ITEM while True: i = QUEUE_ITEM consume_item(i) </code></pre> <p>My question is: Is this code thread-safe?</p> <p>Immediate comment: this code isn't really lockless - I use CPython and it has GIL.</p> <p>I tested the code a little and it seems to work. It translates to some LOAD and STORE ops which are atomic because of GIL. But I also know that <code>del x</code> operation isn't atomic when x implements <code>__del__</code> method. So if my item has a <code>__del__</code> method and some nasty scheduling happens, things may break. Or not?</p> <p>Another question is: What kind of restrictions (for example on produced items' type) do I have to impose to make the above code work fine?</p> <p>My questions are only about theoretical possibility to exploit CPython's and GIL's quirks in order to come up with lockless (i.e. no locks like threading.Lock explicitly in code) solution.</p>
6
2009-05-12T21:15:48Z
854,977
<p>You can use a list as the queue as long as you stick to append/pop since both are atomic.</p> <pre><code>QUEUE = [] # this is executed in one threading.Thread object def producer(): global QUEUE while True: i = produce_item() QUEUE.append(i) # this is executed in another threading.Thread object def consumer(): global QUEUE while True: try: i = QUEUE.pop(0) except IndexError: # queue is empty continue consume_item(i) </code></pre> <p>In a class scope like below, you can even clear the queue.</p> <pre><code>class Atomic(object): def __init__(self): self.queue = [] # this is executed in one threading.Thread object def producer(self): while True: i = produce_item() self.queue.append(i) # this is executed in another threading.Thread object def consumer(self): while True: try: i = self.queue.pop(0) except IndexError: # queue is empty continue consume_item(i) # There's the possibility producer is still working on it's current item. def clear_queue(self): self.queue = [] </code></pre> <p>You'll have to find out which list operations are atomic by looking at the bytecode generated.</p>
0
2009-05-12T21:34:05Z
[ "python", "locking", "thread-safety", "producer-consumer" ]
Is this Python producer-consumer lockless approach thread-safe?
854,906
<p>I recently wrote a program that used a simple producer/consumer pattern. It initially had a bug related to improper use of threading.Lock that I eventually fixed. But it made me think whether it's possible to implement producer/consumer pattern in a lockless manner.</p> <p>Requirements in my case were simple:</p> <ul> <li>One producer thread.</li> <li>One consumer thread.</li> <li>Queue has place for only one item.</li> <li>Producer can produce next item before the current one is consumed. The current item is therefore lost, but that's OK for me.</li> <li>Consumer can consume current item before the next one is produced. The current item is therefore consumed twice (or more), but that's OK for me.</li> </ul> <p>So I wrote this:</p> <pre><code>QUEUE_ITEM = None # this is executed in one threading.Thread object def producer(): global QUEUE_ITEM while True: i = produce_item() QUEUE_ITEM = i # this is executed in another threading.Thread object def consumer(): global QUEUE_ITEM while True: i = QUEUE_ITEM consume_item(i) </code></pre> <p>My question is: Is this code thread-safe?</p> <p>Immediate comment: this code isn't really lockless - I use CPython and it has GIL.</p> <p>I tested the code a little and it seems to work. It translates to some LOAD and STORE ops which are atomic because of GIL. But I also know that <code>del x</code> operation isn't atomic when x implements <code>__del__</code> method. So if my item has a <code>__del__</code> method and some nasty scheduling happens, things may break. Or not?</p> <p>Another question is: What kind of restrictions (for example on produced items' type) do I have to impose to make the above code work fine?</p> <p>My questions are only about theoretical possibility to exploit CPython's and GIL's quirks in order to come up with lockless (i.e. no locks like threading.Lock explicitly in code) solution.</p>
6
2009-05-12T21:15:48Z
855,054
<p>Trickery will bite you. Just use Queue to communicate between threads.</p>
5
2009-05-12T21:50:51Z
[ "python", "locking", "thread-safety", "producer-consumer" ]
Is this Python producer-consumer lockless approach thread-safe?
854,906
<p>I recently wrote a program that used a simple producer/consumer pattern. It initially had a bug related to improper use of threading.Lock that I eventually fixed. But it made me think whether it's possible to implement producer/consumer pattern in a lockless manner.</p> <p>Requirements in my case were simple:</p> <ul> <li>One producer thread.</li> <li>One consumer thread.</li> <li>Queue has place for only one item.</li> <li>Producer can produce next item before the current one is consumed. The current item is therefore lost, but that's OK for me.</li> <li>Consumer can consume current item before the next one is produced. The current item is therefore consumed twice (or more), but that's OK for me.</li> </ul> <p>So I wrote this:</p> <pre><code>QUEUE_ITEM = None # this is executed in one threading.Thread object def producer(): global QUEUE_ITEM while True: i = produce_item() QUEUE_ITEM = i # this is executed in another threading.Thread object def consumer(): global QUEUE_ITEM while True: i = QUEUE_ITEM consume_item(i) </code></pre> <p>My question is: Is this code thread-safe?</p> <p>Immediate comment: this code isn't really lockless - I use CPython and it has GIL.</p> <p>I tested the code a little and it seems to work. It translates to some LOAD and STORE ops which are atomic because of GIL. But I also know that <code>del x</code> operation isn't atomic when x implements <code>__del__</code> method. So if my item has a <code>__del__</code> method and some nasty scheduling happens, things may break. Or not?</p> <p>Another question is: What kind of restrictions (for example on produced items' type) do I have to impose to make the above code work fine?</p> <p>My questions are only about theoretical possibility to exploit CPython's and GIL's quirks in order to come up with lockless (i.e. no locks like threading.Lock explicitly in code) solution.</p>
6
2009-05-12T21:15:48Z
855,122
<p>The <code>__del__</code> could be a problem as You said. It could be avoided, if only there was a way to prevent the garbage collector from invoking the <code>__del__</code> method on the old object before We finish assigning the new one to the <code>QUEUE_ITEM</code>. We would need something like:</p> <pre><code>increase the reference counter on the old object assign a new one to `QUEUE_ITEM` decrease the reference counter on the old object </code></pre> <p>I'm afraid, I don't know if it is possible, though.</p>
0
2009-05-12T22:07:49Z
[ "python", "locking", "thread-safety", "producer-consumer" ]
Is this Python producer-consumer lockless approach thread-safe?
854,906
<p>I recently wrote a program that used a simple producer/consumer pattern. It initially had a bug related to improper use of threading.Lock that I eventually fixed. But it made me think whether it's possible to implement producer/consumer pattern in a lockless manner.</p> <p>Requirements in my case were simple:</p> <ul> <li>One producer thread.</li> <li>One consumer thread.</li> <li>Queue has place for only one item.</li> <li>Producer can produce next item before the current one is consumed. The current item is therefore lost, but that's OK for me.</li> <li>Consumer can consume current item before the next one is produced. The current item is therefore consumed twice (or more), but that's OK for me.</li> </ul> <p>So I wrote this:</p> <pre><code>QUEUE_ITEM = None # this is executed in one threading.Thread object def producer(): global QUEUE_ITEM while True: i = produce_item() QUEUE_ITEM = i # this is executed in another threading.Thread object def consumer(): global QUEUE_ITEM while True: i = QUEUE_ITEM consume_item(i) </code></pre> <p>My question is: Is this code thread-safe?</p> <p>Immediate comment: this code isn't really lockless - I use CPython and it has GIL.</p> <p>I tested the code a little and it seems to work. It translates to some LOAD and STORE ops which are atomic because of GIL. But I also know that <code>del x</code> operation isn't atomic when x implements <code>__del__</code> method. So if my item has a <code>__del__</code> method and some nasty scheduling happens, things may break. Or not?</p> <p>Another question is: What kind of restrictions (for example on produced items' type) do I have to impose to make the above code work fine?</p> <p>My questions are only about theoretical possibility to exploit CPython's and GIL's quirks in order to come up with lockless (i.e. no locks like threading.Lock explicitly in code) solution.</p>
6
2009-05-12T21:15:48Z
855,735
<p>Yes this will work in the way that you described:</p> <ol> <li>That the producer may produce a skippable element.</li> <li>That the consumer may consume the same element.</li> </ol> <blockquote> <p>But I also know that del x operation isn't atomic when x implements <strong>del</strong> method. So if my item has a <strong>del</strong> method and some nasty scheduling happens, things may break. </p> </blockquote> <p>I don't see a "del" here. If a del happens in consume_item then the <strong>del</strong> may occur in the producer thread. I don't think this would be a "problem".</p> <p>Don't bother using this though. You will end up using up CPU on pointless polling cycles, and it is not any faster than using a queue with locks since Python already has a global lock.</p>
2
2009-05-13T02:03:19Z
[ "python", "locking", "thread-safety", "producer-consumer" ]
Error with Beautiful Soup's extract()
855,087
<p>I'm working on some screen scraping software and have run into an issue with Beautiful Soup. I'm using python 2.4.3 and Beautiful Soup 3.0.7a.</p> <p>I need to remove an <code>&lt;hr&gt;</code> tag, but it can have many different attributes, so a simple replace() call won't cut it.</p> <p>Given the following html:</p> <pre><code>&lt;h1&gt;foo&lt;/h1&gt; &lt;h2&gt;&lt;hr/&gt;bar&lt;/h2&gt; </code></pre> <p>And the following code:</p> <pre><code>soup = BeautifulSoup(string) bad_tags = soup.findAll('hr'); [tag.extract() for tag in bad_tags] for i in soup.findAll(['h1', 'h2']): print i print i.string </code></pre> <p>The output is:</p> <pre><code>&lt;h1&gt;foo&lt;/h1&gt; foo &lt;h2&gt;bar&lt;/h2&gt; None </code></pre> <p>Am I misunderstanding the extract function, or is this a bug with Beautiful Soup?</p>
0
2009-05-12T22:00:29Z
855,474
<p>It may be a bug. But fortunately for you, there is another way to get the string:</p> <pre><code>from BeautifulSoup import BeautifulSoup string = \ """&lt;h1&gt;foo&lt;/h1&gt; &lt;h2&gt;&lt;hr/&gt;bar&lt;/h2&gt;""" soup = BeautifulSoup(string) bad_tags = soup.findAll('hr'); [tag.extract() for tag in bad_tags] for i in soup.findAll(['h1', 'h2']): print i, i.next # &lt;h1&gt;foo&lt;/h1&gt; foo # &lt;h2&gt;bar&lt;/h2&gt; bar </code></pre>
2
2009-05-12T23:58:12Z
[ "python", "beautifulsoup" ]
Error with Beautiful Soup's extract()
855,087
<p>I'm working on some screen scraping software and have run into an issue with Beautiful Soup. I'm using python 2.4.3 and Beautiful Soup 3.0.7a.</p> <p>I need to remove an <code>&lt;hr&gt;</code> tag, but it can have many different attributes, so a simple replace() call won't cut it.</p> <p>Given the following html:</p> <pre><code>&lt;h1&gt;foo&lt;/h1&gt; &lt;h2&gt;&lt;hr/&gt;bar&lt;/h2&gt; </code></pre> <p>And the following code:</p> <pre><code>soup = BeautifulSoup(string) bad_tags = soup.findAll('hr'); [tag.extract() for tag in bad_tags] for i in soup.findAll(['h1', 'h2']): print i print i.string </code></pre> <p>The output is:</p> <pre><code>&lt;h1&gt;foo&lt;/h1&gt; foo &lt;h2&gt;bar&lt;/h2&gt; None </code></pre> <p>Am I misunderstanding the extract function, or is this a bug with Beautiful Soup?</p>
0
2009-05-12T22:00:29Z
36,795,070
<p>I've got the same problem. I do not know why, but i guess it has to do with the empty elements created by BS.</p> <p>For example if i have the following code:</p> <pre><code>from bs4 import BeautifulSoup html =' \ &lt;a&gt; \ &lt;b test="help"&gt; \ hello there! \ &lt;d&gt; \ now what? \ &lt;/d&gt; \ &lt;e&gt; \ &lt;f&gt; \ &lt;/f&gt; \ &lt;/e&gt; \ &lt;/b&gt; \ &lt;c&gt; \ &lt;/c&gt; \ &lt;/a&gt; \ ' soup = BeautifulSoup(html,'lxml') #print(soup.find('b').attrs) print(soup.find('b').contents) t = soup.find('b').findAll() #t.reverse() for c in t: gb = c.extract() print(soup.find('b').contents) soup.find('b').text.strip() </code></pre> <p>I got the following error:</p> <blockquote> <p>'NoneType' object has no attribute 'next_element'</p> </blockquote> <p>On the first print i got:</p> <pre><code>&gt;&gt;&gt; print(soup.find('b').contents) [u' ', &lt;d&gt; &lt;/d&gt;, u' ', &lt;e&gt; &lt;f&gt; &lt;/f&gt; &lt;/e&gt;, u' '] </code></pre> <p>and on the second i got:</p> <pre><code>&gt;&gt;&gt; print(soup.find('b').contents) [u' ', u' ', u' '] </code></pre> <p>I'm pretty sure it is the empty element in the middle creating the problem.</p> <p>A workaround i found is to just recreate the soup:</p> <pre><code>soup = BeautifulSoup(str(soup)) soup.find('b').text.strip() </code></pre> <p>Now it prints:</p> <pre><code>&gt;&gt;&gt; soup.find('b').text.strip() u'hello there!' </code></pre> <p>I hope that helps.</p>
0
2016-04-22T13:23:06Z
[ "python", "beautifulsoup" ]
Can I restrict nose coverage output to directory (rather than package)?
855,114
<p>My SUT looks like:</p> <pre><code>foo.py bar.py tests/__init__.py [empty] tests/foo_tests.py tests/bar_tests.py tests/integration/__init__.py [empty] tests/integration/foo_tests.py tests/integration/bar_tests.py </code></pre> <p>When I run <code>nosetests --with-coverage</code>, I get details for all sorts of modules that I'd rather ignore. But I can't use the <code>--cover-package=PACKAGE</code> option because <code>foo.py</code> &amp; <code>bar.py</code> are not in a package. (See the thread after <a href="http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html">http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html</a> for my reasons for not putting them in a package.)</p> <p>Can I restrict coverage output to just foo.py &amp; bar.py?</p> <p><strong>Update</strong> - Assuming that there isn't a better answer than <a href="http://stackoverflow.com/users/97828/nadia">Nadia</a>'s below, I've asked a follow up question: <a href="http://stackoverflow.com/questions/855265/how-do-i-write-some-bash-shell-script-to-convert-all-matching-filenames-in-dire">"How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?"</a></p>
13
2009-05-12T22:06:28Z
855,172
<p>You can use it like this:</p> <pre><code>--cover-package=foo --cover-package=bar </code></pre> <p>I had a quick look at nose source code to confirm: <a href="https://github.com/nose-devs/nose/blob/master/nose/plugins/cover.py">This is the line</a></p> <pre><code> if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]: </code></pre>
15
2009-05-12T22:23:05Z
[ "python", "code-coverage", "nose", "nosetests" ]
Can I restrict nose coverage output to directory (rather than package)?
855,114
<p>My SUT looks like:</p> <pre><code>foo.py bar.py tests/__init__.py [empty] tests/foo_tests.py tests/bar_tests.py tests/integration/__init__.py [empty] tests/integration/foo_tests.py tests/integration/bar_tests.py </code></pre> <p>When I run <code>nosetests --with-coverage</code>, I get details for all sorts of modules that I'd rather ignore. But I can't use the <code>--cover-package=PACKAGE</code> option because <code>foo.py</code> &amp; <code>bar.py</code> are not in a package. (See the thread after <a href="http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html">http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html</a> for my reasons for not putting them in a package.)</p> <p>Can I restrict coverage output to just foo.py &amp; bar.py?</p> <p><strong>Update</strong> - Assuming that there isn't a better answer than <a href="http://stackoverflow.com/users/97828/nadia">Nadia</a>'s below, I've asked a follow up question: <a href="http://stackoverflow.com/questions/855265/how-do-i-write-some-bash-shell-script-to-convert-all-matching-filenames-in-dire">"How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?"</a></p>
13
2009-05-12T22:06:28Z
855,341
<p>If you use <a href="http://nedbatchelder.com/blog/200904/coverage%5Fv30%5Fbeta%5F2.html" rel="nofollow">coverage:py 3.0</a>, then code in the Python directory is ignored by default, including the standard library and all installed packages.</p>
3
2009-05-12T23:10:06Z
[ "python", "code-coverage", "nose", "nosetests" ]
Can I restrict nose coverage output to directory (rather than package)?
855,114
<p>My SUT looks like:</p> <pre><code>foo.py bar.py tests/__init__.py [empty] tests/foo_tests.py tests/bar_tests.py tests/integration/__init__.py [empty] tests/integration/foo_tests.py tests/integration/bar_tests.py </code></pre> <p>When I run <code>nosetests --with-coverage</code>, I get details for all sorts of modules that I'd rather ignore. But I can't use the <code>--cover-package=PACKAGE</code> option because <code>foo.py</code> &amp; <code>bar.py</code> are not in a package. (See the thread after <a href="http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html">http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html</a> for my reasons for not putting them in a package.)</p> <p>Can I restrict coverage output to just foo.py &amp; bar.py?</p> <p><strong>Update</strong> - Assuming that there isn't a better answer than <a href="http://stackoverflow.com/users/97828/nadia">Nadia</a>'s below, I've asked a follow up question: <a href="http://stackoverflow.com/questions/855265/how-do-i-write-some-bash-shell-script-to-convert-all-matching-filenames-in-dire">"How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?"</a></p>
13
2009-05-12T22:06:28Z
6,273,255
<pre><code>touch __init__.py; nosetests --with-coverage --cover-package=`pwd | sed 's@.*/@@g'` </code></pre>
1
2011-06-08T01:11:45Z
[ "python", "code-coverage", "nose", "nosetests" ]
Can I restrict nose coverage output to directory (rather than package)?
855,114
<p>My SUT looks like:</p> <pre><code>foo.py bar.py tests/__init__.py [empty] tests/foo_tests.py tests/bar_tests.py tests/integration/__init__.py [empty] tests/integration/foo_tests.py tests/integration/bar_tests.py </code></pre> <p>When I run <code>nosetests --with-coverage</code>, I get details for all sorts of modules that I'd rather ignore. But I can't use the <code>--cover-package=PACKAGE</code> option because <code>foo.py</code> &amp; <code>bar.py</code> are not in a package. (See the thread after <a href="http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html">http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html</a> for my reasons for not putting them in a package.)</p> <p>Can I restrict coverage output to just foo.py &amp; bar.py?</p> <p><strong>Update</strong> - Assuming that there isn't a better answer than <a href="http://stackoverflow.com/users/97828/nadia">Nadia</a>'s below, I've asked a follow up question: <a href="http://stackoverflow.com/questions/855265/how-do-i-write-some-bash-shell-script-to-convert-all-matching-filenames-in-dire">"How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?"</a></p>
13
2009-05-12T22:06:28Z
7,691,689
<p>You can use:</p> <pre><code>--cover-package=. </code></pre> <p>or even set environment variable</p> <pre><code>NOSE_COVER_PACKAGE=. </code></pre> <p>Tested with nose 1.1.2</p>
9
2011-10-07T18:58:42Z
[ "python", "code-coverage", "nose", "nosetests" ]
Can I restrict nose coverage output to directory (rather than package)?
855,114
<p>My SUT looks like:</p> <pre><code>foo.py bar.py tests/__init__.py [empty] tests/foo_tests.py tests/bar_tests.py tests/integration/__init__.py [empty] tests/integration/foo_tests.py tests/integration/bar_tests.py </code></pre> <p>When I run <code>nosetests --with-coverage</code>, I get details for all sorts of modules that I'd rather ignore. But I can't use the <code>--cover-package=PACKAGE</code> option because <code>foo.py</code> &amp; <code>bar.py</code> are not in a package. (See the thread after <a href="http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html">http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html</a> for my reasons for not putting them in a package.)</p> <p>Can I restrict coverage output to just foo.py &amp; bar.py?</p> <p><strong>Update</strong> - Assuming that there isn't a better answer than <a href="http://stackoverflow.com/users/97828/nadia">Nadia</a>'s below, I've asked a follow up question: <a href="http://stackoverflow.com/questions/855265/how-do-i-write-some-bash-shell-script-to-convert-all-matching-filenames-in-dire">"How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?"</a></p>
13
2009-05-12T22:06:28Z
16,101,923
<p>I would do this:</p> <pre><code>nosetests --with-coverage --cover-package=foo,bar tests/* </code></pre> <p>I prefer this solution to the others suggested; it's simple yet you are explicit about which packages you wish to have coverage for. Nadia's answer involves a lot more redundant typing, Stuart's answer uses sed and still creates a package by invoking <code>touch __init__.py</code>, and <code>--cover-package=.</code> doesn't work for me.</p>
2
2013-04-19T09:54:24Z
[ "python", "code-coverage", "nose", "nosetests" ]
Can I restrict nose coverage output to directory (rather than package)?
855,114
<p>My SUT looks like:</p> <pre><code>foo.py bar.py tests/__init__.py [empty] tests/foo_tests.py tests/bar_tests.py tests/integration/__init__.py [empty] tests/integration/foo_tests.py tests/integration/bar_tests.py </code></pre> <p>When I run <code>nosetests --with-coverage</code>, I get details for all sorts of modules that I'd rather ignore. But I can't use the <code>--cover-package=PACKAGE</code> option because <code>foo.py</code> &amp; <code>bar.py</code> are not in a package. (See the thread after <a href="http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html">http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html</a> for my reasons for not putting them in a package.)</p> <p>Can I restrict coverage output to just foo.py &amp; bar.py?</p> <p><strong>Update</strong> - Assuming that there isn't a better answer than <a href="http://stackoverflow.com/users/97828/nadia">Nadia</a>'s below, I've asked a follow up question: <a href="http://stackoverflow.com/questions/855265/how-do-i-write-some-bash-shell-script-to-convert-all-matching-filenames-in-dire">"How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?"</a></p>
13
2009-05-12T22:06:28Z
22,674,615
<p>I have a lot of top-level Python files/packages and find it annoying to list them all manually using --cover-package, so I made two aliases for myself. Alias <code>nosetests_cover</code> will run coverage with all your top-level Python files/packages listed in --cover-package. Alias <code>nosetests_cover_sort</code> will do the same and additionally sort your results by coverage percentage.</p> <pre><code>nosetests_cover_cmd="nosetests --with-coverage --cover-erase --cover-inclusive --cover-package=\$( ls | sed -r 's/[.]py$//' | fgrep -v '.' | paste -s -d ',' )" alias nosetests_cover=$nosetests_cover_cmd alias nosetests_cover_sort="$nosetests_cover_cmd 2&gt;&amp;1 | fgrep '%' | sort -nr -k 4" </code></pre> <p>Notes:</p> <ul> <li>This is from my .bashrc file. Modify appropriately if you don't use bash.</li> <li>These must be run from your top-level directory. Otherwise, the package names will be incorrect and coverage will silently fail to process them (i.e. instead of telling you your --cover-package is incorrect, it will act like you didn't supply the option at all).</li> <li>I'm currently using Python 2.7.6 on Ubuntu 13.10, with nose version 1.3.0 and coverage version 3.7.1. This is the only setup in which I've tested these commands.</li> <li>In your usage, remove --cover-erase and --cover-inclusive if they don't match your needs.</li> <li>If you want to sort in normal order instead of reverse order, replace <code>-nr</code> with <code>-n</code> in the sort command.</li> <li>These commands assume that all of your top-level Python files/packages are named without a dot (other than the dot in ".py"). If this is not true for you, read Details section below to understand the command parts, then modify the commands as appropriate.</li> </ul> <p>Details:</p> <p>I don't claim that these are the most efficient commands to achieve the results I want. They're just the commands I happened to come up with. =P</p> <p>The main thing to explain would be the argument to --cover-package. It builds the comma-separated list of top-level Python file/package names (with ".py" stripped from file names) as follows:</p> <ul> <li><code>\$</code> -- Escapes the <code>$</code> character in a double-quoted string.</li> <li><code>$( )</code> -- Inserts the result of the command contained within.</li> <li><code>ls</code> -- Lists all names in current directory (must be top-level Python directory).</li> <li><code>| sed -r 's/[.]py$//'</code> -- In the list, replaces "foo_bar.py" with "foo_bar".</li> <li><code>| fgrep -v '.'</code> -- In the list, removes all names without a dot (e.g. removes foo_bar.pyc and notes.txt).</li> <li><code>| paste -s -d ','</code> -- Changes the list from newline-separated to comma-separated. </li> </ul> <p>I should also explain the sorting.</p> <ul> <li><code>2&gt;&amp;1</code> -- Joins stderr and stdout.</li> <li><code>| fgrep '%'</code> -- Removes all output lines without a <code>%</code> character.</li> <li><code>| sort -nr -k 4</code> -- Sorts the remaining lines in reverse numerical order by the 4th column (which is the column for coverage percentage). If you want normal order instead of reverse order, replace <code>-nr</code> with <code>-n</code>.</li> </ul> <p>Hope this helps someone! =)</p>
4
2014-03-26T22:44:04Z
[ "python", "code-coverage", "nose", "nosetests" ]
Can I restrict nose coverage output to directory (rather than package)?
855,114
<p>My SUT looks like:</p> <pre><code>foo.py bar.py tests/__init__.py [empty] tests/foo_tests.py tests/bar_tests.py tests/integration/__init__.py [empty] tests/integration/foo_tests.py tests/integration/bar_tests.py </code></pre> <p>When I run <code>nosetests --with-coverage</code>, I get details for all sorts of modules that I'd rather ignore. But I can't use the <code>--cover-package=PACKAGE</code> option because <code>foo.py</code> &amp; <code>bar.py</code> are not in a package. (See the thread after <a href="http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html">http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html</a> for my reasons for not putting them in a package.)</p> <p>Can I restrict coverage output to just foo.py &amp; bar.py?</p> <p><strong>Update</strong> - Assuming that there isn't a better answer than <a href="http://stackoverflow.com/users/97828/nadia">Nadia</a>'s below, I've asked a follow up question: <a href="http://stackoverflow.com/questions/855265/how-do-i-write-some-bash-shell-script-to-convert-all-matching-filenames-in-dire">"How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?"</a></p>
13
2009-05-12T22:06:28Z
32,377,465
<p>For anyone trying to do this with setup.cfg, the following works. I had some trouble figuring out how to specify multiple packages.</p> <pre><code>[nosetests] with-coverage=1 cover-html=1 cover-package=module1,module2 </code></pre>
2
2015-09-03T13:47:08Z
[ "python", "code-coverage", "nose", "nosetests" ]
Can I restrict nose coverage output to directory (rather than package)?
855,114
<p>My SUT looks like:</p> <pre><code>foo.py bar.py tests/__init__.py [empty] tests/foo_tests.py tests/bar_tests.py tests/integration/__init__.py [empty] tests/integration/foo_tests.py tests/integration/bar_tests.py </code></pre> <p>When I run <code>nosetests --with-coverage</code>, I get details for all sorts of modules that I'd rather ignore. But I can't use the <code>--cover-package=PACKAGE</code> option because <code>foo.py</code> &amp; <code>bar.py</code> are not in a package. (See the thread after <a href="http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html">http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html</a> for my reasons for not putting them in a package.)</p> <p>Can I restrict coverage output to just foo.py &amp; bar.py?</p> <p><strong>Update</strong> - Assuming that there isn't a better answer than <a href="http://stackoverflow.com/users/97828/nadia">Nadia</a>'s below, I've asked a follow up question: <a href="http://stackoverflow.com/questions/855265/how-do-i-write-some-bash-shell-script-to-convert-all-matching-filenames-in-dire">"How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?"</a></p>
13
2009-05-12T22:06:28Z
37,620,563
<p>You can improve the accepted answer like so <code>--cover-package=foo,bar</code></p>
0
2016-06-03T17:46:00Z
[ "python", "code-coverage", "nose", "nosetests" ]
How Big can a Python Array Get?
855,191
<p>In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc?</p>
70
2009-05-12T22:27:33Z
855,195
<p>12000 elements is nothing in Python... and actually the number of elements can go as far as the Python interpreter has memory on your system.</p>
3
2009-05-12T22:29:11Z
[ "python", "arrays", "size" ]
How Big can a Python Array Get?
855,191
<p>In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc?</p>
70
2009-05-12T22:27:33Z
855,200
<p>I'd say you're only limited by the total amount of RAM available. Obviously the larger the array the longer operations on it will take.</p>
1
2009-05-12T22:30:24Z
[ "python", "arrays", "size" ]
How Big can a Python Array Get?
855,191
<p>In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc?</p>
70
2009-05-12T22:27:33Z
855,213
<p>Sure it is OK. Actually you can see for yourself easily:</p> <pre><code>l = range(12000) l = sorted(l, reverse=True) </code></pre> <p>Running the those lines on my machine took:</p> <pre><code>real 0m0.036s user 0m0.024s sys 0m0.004s </code></pre> <p>But sure as everyone else said. The larger the array the slower the operations will be.</p>
21
2009-05-12T22:33:28Z
[ "python", "arrays", "size" ]
How Big can a Python Array Get?
855,191
<p>In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc?</p>
70
2009-05-12T22:27:33Z
855,221
<p>In casual code I've created lists with millions of elements. I believe that Python's implementation of lists are only bound by the amount of memory on your system. </p> <p>In addition, the list methods / functions should continue to work despite the size of the list. </p> <p>If you care about performance, it might be worthwhile to look into a library such as <a href="http://numpy.scipy.org/">NumPy</a>.</p>
5
2009-05-12T22:36:12Z
[ "python", "arrays", "size" ]
How Big can a Python Array Get?
855,191
<p>In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc?</p>
70
2009-05-12T22:27:33Z
855,455
<p>According to the <a href="http://svn.python.org/view/python/trunk/Objects/listobject.c?revision=69227&amp;view=markup">source code</a>, the maximum size of a list is <code>PY_SSIZE_T_MAX/sizeof(PyObject*)</code>.</p> <p><code>PY_SSIZE_T_MAX</code> is defined in <a href="http://svn.python.org/view/python/trunk/Include/pyport.h?revision=70489&amp;view=markup">pyport.h</a> to be <code>((size_t) -1)&gt;&gt;1</code></p> <p>On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912.</p> <p>Therefore the maximum size of a python list on a 32 bit system is <strong>536,870,912</strong> elements. </p> <p>As long as the number of elements you have is equal or below this, all list functions should operate correctly.</p>
124
2009-05-12T23:48:21Z
[ "python", "arrays", "size" ]
How Big can a Python Array Get?
855,191
<p>In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc?</p>
70
2009-05-12T22:27:33Z
855,465
<p><a href="http://effbot.org/zone/python-list.htm#performance" rel="nofollow">Performance characteristics for lists</a> are described on Effbot.</p> <p>Python lists are actually implemented as vector for fast random access, so the container will basically hold as many items as there is space for in memory. (You need space for pointers contained in the list as well as space in memory for the object(s) being pointed to.)</p> <p>Appending is <code>O(1)</code> (amortized constant complexity), however, inserting into/deleting from the middle of the sequence will require an <code>O(n)</code> (linear complexity) reordering, which will get slower as the number of elements in your list.</p> <p>Your sorting question is more nuanced, since the comparison operation can take an unbounded amount of time. If you're performing really slow comparisons, it will take a long time, though it's no fault of <a href="http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange" rel="nofollow">Python's list data type</a>.</p> <p>Reversal just takes the amount of time it required to swap all the pointers in the list (necessarily <code>O(n)</code> (linear complexity), since you touch each pointer once).</p>
4
2009-05-12T23:53:34Z
[ "python", "arrays", "size" ]
How Big can a Python Array Get?
855,191
<p>In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc?</p>
70
2009-05-12T22:27:33Z
15,739,630
<p>As the <a href="http://docs.python.org/2/library/sys.html#sys.maxsize">Python documentation says</a>:</p> <p><strong>sys.maxsize</strong></p> <blockquote> <p>The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.</p> </blockquote> <p>In my computer (Linux x86_64):</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.maxsize 9223372036854775807 </code></pre>
20
2013-04-01T07:45:18Z
[ "python", "arrays", "size" ]
How Big can a Python Array Get?
855,191
<p>In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc?</p>
70
2009-05-12T22:27:33Z
22,240,449
<p>There is no limitation of list number. The main reason which causes your error is the RAM. Please upgrade your memory size.</p>
-5
2014-03-07T02:44:06Z
[ "python", "arrays", "size" ]
Getting local dictionary for function scope only in Python
855,259
<p>I keep ending up at this situation where I want to use a dictionary very much like the one 'locals' gives back, but that only contains the variables in the limited scope of the function. Is there a way to do this in python? </p> <p>A bit more about why I want to do this: I'm playing with Django and when I go to give my templates context, I am forced either to either manually make a dictionary (In violation with DRY principles) or pass in locals() which contains far more entries then are needed (wasteful). Is there perhaps something I'm missing with django which would alleviate the need of a python level solution?</p> <p>To Clarify:</p> <p>So, the case that I've hit repeatedly is where I have: </p> <pre><code>@render_to('my_template.html') def myview(request): var1 = #blahblah var2 = #... # do stuff with vars return {'var1': val1,'var2':val2} </code></pre> <p>So instead of repeating those variables and naming conventions, I'll do: </p> <pre><code>@render_to('my_template.html') def myview(request): var1 = #blahblah var2 = #... # do stuff with vars return locals() </code></pre> <p>Which I find cleaner, but I know its kind of sloppy since there are about 30 more entries in locals() then I actually need. </p>
0
2009-05-12T22:49:01Z
855,277
<p>How is passing a dictionary a violation of DRY? <a href="http://docs.djangoproject.com/en/dev/misc/design-philosophies/#don-t-repeat-yourself-dry" rel="nofollow">Django is all about DRY</a>, so I doubt the standard behavior of it would directly violate it. In either case, however, I use a modified version of <a href="http://bitbucket.org/offline/django-annoying/wiki/Home" rel="nofollow">django-annoying</a> to make the whole thing easier:</p> <pre><code>@render_to('my_template.html') def myview(request): # figure stuff out... return {'var1':'val1','var2','val2'} </code></pre> <p>The <code>render_to</code> decorator takes care of the request context and all that good stuff. Works well.</p> <p>If this doesn't help, I suggest rephrasing your question. Whatever you want to do messing around with <code>locals()</code> and such is rarely necessary especially in this kind of situation with Django.</p>
4
2009-05-12T22:54:22Z
[ "python", "django", "scope", "django-views", "locals" ]
Getting local dictionary for function scope only in Python
855,259
<p>I keep ending up at this situation where I want to use a dictionary very much like the one 'locals' gives back, but that only contains the variables in the limited scope of the function. Is there a way to do this in python? </p> <p>A bit more about why I want to do this: I'm playing with Django and when I go to give my templates context, I am forced either to either manually make a dictionary (In violation with DRY principles) or pass in locals() which contains far more entries then are needed (wasteful). Is there perhaps something I'm missing with django which would alleviate the need of a python level solution?</p> <p>To Clarify:</p> <p>So, the case that I've hit repeatedly is where I have: </p> <pre><code>@render_to('my_template.html') def myview(request): var1 = #blahblah var2 = #... # do stuff with vars return {'var1': val1,'var2':val2} </code></pre> <p>So instead of repeating those variables and naming conventions, I'll do: </p> <pre><code>@render_to('my_template.html') def myview(request): var1 = #blahblah var2 = #... # do stuff with vars return locals() </code></pre> <p>Which I find cleaner, but I know its kind of sloppy since there are about 30 more entries in locals() then I actually need. </p>
0
2009-05-12T22:49:01Z
855,284
<p>I'm not sure I agree that making a dictionary is a violation of DRY, but if you really don't want to repeat anything at all, you could just define a 'context' dictionary at the top of the view and use dictionary keys instead of variables throughout the view.</p> <pre><code>def my_view(request): context = {} context['items'] = Item.objects.all() context['anothervalue'] = context['items'][2].name return render_to_response('template.html', context) </code></pre>
5
2009-05-12T22:57:12Z
[ "python", "django", "scope", "django-views", "locals" ]
Getting local dictionary for function scope only in Python
855,259
<p>I keep ending up at this situation where I want to use a dictionary very much like the one 'locals' gives back, but that only contains the variables in the limited scope of the function. Is there a way to do this in python? </p> <p>A bit more about why I want to do this: I'm playing with Django and when I go to give my templates context, I am forced either to either manually make a dictionary (In violation with DRY principles) or pass in locals() which contains far more entries then are needed (wasteful). Is there perhaps something I'm missing with django which would alleviate the need of a python level solution?</p> <p>To Clarify:</p> <p>So, the case that I've hit repeatedly is where I have: </p> <pre><code>@render_to('my_template.html') def myview(request): var1 = #blahblah var2 = #... # do stuff with vars return {'var1': val1,'var2':val2} </code></pre> <p>So instead of repeating those variables and naming conventions, I'll do: </p> <pre><code>@render_to('my_template.html') def myview(request): var1 = #blahblah var2 = #... # do stuff with vars return locals() </code></pre> <p>Which I find cleaner, but I know its kind of sloppy since there are about 30 more entries in locals() then I actually need. </p>
0
2009-05-12T22:49:01Z
855,363
<p>You say you don't like using locals() because it is "wasteful". Wasteful of what? I believe the dictionary it returns already exists, it's just giving you a reference to it. And even if it has to create the dictionary, this is one of the most highly optimized operations in Python, so don't worry about it.</p> <p>You should focus on the code structure that best expresses your intention, with the fewest possibilities for error. The waste you are worried about is nothing to worry about.</p>
2
2009-05-12T23:14:39Z
[ "python", "django", "scope", "django-views", "locals" ]
Getting local dictionary for function scope only in Python
855,259
<p>I keep ending up at this situation where I want to use a dictionary very much like the one 'locals' gives back, but that only contains the variables in the limited scope of the function. Is there a way to do this in python? </p> <p>A bit more about why I want to do this: I'm playing with Django and when I go to give my templates context, I am forced either to either manually make a dictionary (In violation with DRY principles) or pass in locals() which contains far more entries then are needed (wasteful). Is there perhaps something I'm missing with django which would alleviate the need of a python level solution?</p> <p>To Clarify:</p> <p>So, the case that I've hit repeatedly is where I have: </p> <pre><code>@render_to('my_template.html') def myview(request): var1 = #blahblah var2 = #... # do stuff with vars return {'var1': val1,'var2':val2} </code></pre> <p>So instead of repeating those variables and naming conventions, I'll do: </p> <pre><code>@render_to('my_template.html') def myview(request): var1 = #blahblah var2 = #... # do stuff with vars return locals() </code></pre> <p>Which I find cleaner, but I know its kind of sloppy since there are about 30 more entries in locals() then I actually need. </p>
0
2009-05-12T22:49:01Z
856,880
<p>While I agree with many other respondents that passing either <code>locals()</code> or a fully specified dict <code>{'var1':var1, 'var2': var2}</code> is most likely OK, if you specifically want to "subset" a dict such as <code>locals()</code> that's far from hard either, e.g.:</p> <pre><code>loc = locals() return dict((k,loc[k]) for k in 'var1 var2'.split()) </code></pre>
2
2009-05-13T09:02:09Z
[ "python", "django", "scope", "django-views", "locals" ]
Running django on OSX
855,408
<p>I've just completed the very very nice django tutorial and it all went swimmingly. One of the first parts of the tutorial is that it says not to use their example server thingie in production, my first act after the tutorial was thus to try to run my app on apache.</p> <p>I'm running OSX 10.5 and have the standard apache (which refuses to run python) and MAMP (which begrudgingly allows it in cgi-bin). The problem is that I've no idea which script to call, in the tutorial it was always localhost:8000/polls but I've no idea how that's meant to map to a specific file.</p> <p>Have I missed something blatantly obvious about what to do with a .htaccess file or does the tutorial not actually explain how to use it somewhere else?</p>
0
2009-05-12T23:29:12Z
855,573
<p>You probably won't find much joy using <code>.htaccess</code> to configure Django through Apache (though I confess you probably could do it if you're determined enough... but for production I suspect it will be more complicated than necessary). I develop and run Django in OS X, and it works quite seamlessly.</p> <p>The secret is that you must configure <code>httpd.conf</code> to pass requests to Django via one of three options: <code>mod_wsgi</code> (the most modern approach), <code>mod_python</code> (second best, but works fine on OS X's Python 2.5), <code>fastcgi</code> (well... if you must to match your production environment).</p> <p>Django's <a href="http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index">deployment docs</a> have good advice and instruction for all three options.</p> <p>If you are using the default OS X apache install, edit <code>/etc/apache2/httpd.conf</code> with the directives found in the Django docs above. I can't speak for MAMP, but if you build Apache from source (which is so easy on OS X I do wonder why anyone bothers with MAMP... my insecurities are showing), edit <code>/usr/local/apache2/conf/httpd.conf</code>.</p>
5
2009-05-13T00:55:15Z
[ "python", "django", "osx" ]
Running django on OSX
855,408
<p>I've just completed the very very nice django tutorial and it all went swimmingly. One of the first parts of the tutorial is that it says not to use their example server thingie in production, my first act after the tutorial was thus to try to run my app on apache.</p> <p>I'm running OSX 10.5 and have the standard apache (which refuses to run python) and MAMP (which begrudgingly allows it in cgi-bin). The problem is that I've no idea which script to call, in the tutorial it was always localhost:8000/polls but I've no idea how that's meant to map to a specific file.</p> <p>Have I missed something blatantly obvious about what to do with a .htaccess file or does the tutorial not actually explain how to use it somewhere else?</p>
0
2009-05-12T23:29:12Z
856,033
<p>Unless you are planning on going to production with OS X you might not want to bother. If you must do it, go straight to mod_wsgi. Don't bother with mod_python or older solutions. I did mod_python on Apache and while it runs great now, it took countless hours to set up.</p> <p>Also, just to clarify something based on what you said: You're not going to find a mapping between the url path (like /polls) and a script that is being called. Django doesn't work like that. With Django your application is loaded into memory waiting for requests. Once a request comes in it gets dispatched through the url map that you created in urls.py. That boils down to a function call somewhere in your code.</p> <p>That's why for a webserver like Apache you need a module like mod_wsgi, which gives your app a spot in memory in which to live. Compare that with something like CGI where the webserver executes a specific script on demand at a location that is physically mapped between the url and the filesystem.</p> <p>I hope that's helpful and not telling you something you already knew. :)</p>
4
2009-05-13T04:14:09Z
[ "python", "django", "osx" ]
Running django on OSX
855,408
<p>I've just completed the very very nice django tutorial and it all went swimmingly. One of the first parts of the tutorial is that it says not to use their example server thingie in production, my first act after the tutorial was thus to try to run my app on apache.</p> <p>I'm running OSX 10.5 and have the standard apache (which refuses to run python) and MAMP (which begrudgingly allows it in cgi-bin). The problem is that I've no idea which script to call, in the tutorial it was always localhost:8000/polls but I've no idea how that's meant to map to a specific file.</p> <p>Have I missed something blatantly obvious about what to do with a .htaccess file or does the tutorial not actually explain how to use it somewhere else?</p>
0
2009-05-12T23:29:12Z
856,037
<p>If you're planning on running it for production (or non-development) mode another option is to do away with Apache and go with something lightweight like nginx. But if you're doing development work, you'll want to stick with the built-in server and PyDev in Eclipse. It's so much easier to walk through the server code line-by-line in the Eclipse debugger.</p> <p>Installation instructions for nginx/Django here: <a href="http://snippets.dzone.com/tag/nginx" rel="nofollow">http://snippets.dzone.com/tag/nginx</a></p>
3
2009-05-13T04:16:04Z
[ "python", "django", "osx" ]
Running django on OSX
855,408
<p>I've just completed the very very nice django tutorial and it all went swimmingly. One of the first parts of the tutorial is that it says not to use their example server thingie in production, my first act after the tutorial was thus to try to run my app on apache.</p> <p>I'm running OSX 10.5 and have the standard apache (which refuses to run python) and MAMP (which begrudgingly allows it in cgi-bin). The problem is that I've no idea which script to call, in the tutorial it was always localhost:8000/polls but I've no idea how that's meant to map to a specific file.</p> <p>Have I missed something blatantly obvious about what to do with a .htaccess file or does the tutorial not actually explain how to use it somewhere else?</p>
0
2009-05-12T23:29:12Z
856,986
<p>Yet another option is to consider using a virtual machine for your development. You can install a full version of whatever OS your production server will be running - say, Debian - and run your Apache and DB in the VM.</p> <p>You can connect to the virtual disk in the Finder, so you can still use TextMate (or whatever) on OSX to do your editing.</p> <p>I've had good experiences doing this via VMWare Fusion.</p>
2
2009-05-13T09:32:16Z
[ "python", "django", "osx" ]
referenced before assignment error in python
855,493
<p>In Python I'm getting the following error:</p> <pre><code>UnboundLocalError: local variable 'total' referenced before assignment </code></pre> <p>At the start of the file (before the function where the error comes from), I declare 'total' using the global keyword. Then, in the body of the program, before the function that uses 'total' is called, I assign it to 0. I've tried setting it to 0 in various places (including the top of the file, just after it is declared), but I can't get it to work. Does anyone see what I'm doing wrong?</p>
32
2009-05-13T00:08:33Z
855,511
<p>I think you are using 'global' incorrectly. See <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-global-statement">Python reference</a>. You should declare variable without global and then inside the function when you want to access global variable you declare it 'global yourvar'.</p> <pre><code>#!/usr/bin/python total def checkTotal(): global total total = 0 </code></pre> <p>See this example:</p> <pre><code>#!/usr/bin/env python total = 0 def doA(): # not accessing global total total = 10 def doB(): global total total = total + 1 def checkTotal(): # global total - not required as global is required # only for assignment - thanks for comment Greg print total def main(): doA() doB() checkTotal() if __name__ == '__main__': main() </code></pre> <p>Because doA() does not modify the <em>global total</em> the output is 1 not 11.</p>
70
2009-05-13T00:24:28Z
[ "python" ]
Why can't I pass a direct reference to a dictionary value to a function?
855,514
<p>Earlier today I asked a <a href="http://stackoverflow.com/questions/853483/can-i-pass-dictionary-values-entry-and-keys-to-function">question</a> about passing dictionary values to a function. While I understand now how to accomplish what I was trying to accomplish the why question (which was not asked) was never answered. So my follow up is why can't I </p> <pre><code>def myFunction(newDict['bubba']): some code to process the parameter </code></pre> <p>Is it simply because the parser rules do not allow this? I Googled for +Python +function +"allowable parameters" and did not find anything useful so I would appreciate any information. </p> <p>I am oversimplifying what is going on. I have a dictionary that is structured like</p> <pre><code>myDict={outerkey1:(innerkey1:value,innerkey2:value,. . .innerkeyn:value),outerkey2:(innerkey1:value,innerkey2:value,. . .innerkeyn:value),. . .} </code></pre> <p>As I said, I know how to do what I wanted-I got a very helpful answer. But I started wondering why </p> <pre><code> def myFunction(outerkey,myDict[outerkey]): </code></pre> <p>gives a syntax error which finely it occurred to me that it has to be a parsing problem.</p>
1
2009-05-13T00:25:53Z
855,521
<p>Yes, the parser will reject this code.</p> <p>Parameter lists are used in function definitions to bind identifiers within the function to arguments that are passed in from the outside <strong>on invocation</strong>.</p> <p>Since <code>newDict['bubba']</code> is not a valid identifier, this doesn't make any sense -- you need to provide it as an invocation argument instead of a function parameter, since function parameters can only be identifiers.</p> <p>Because you seem interested in the <a href="https://docs.python.org/2/reference/grammar.html" rel="nofollow">formal grammar</a>, here are the relevant parts:</p> <pre><code>funcdef ::= [decorators] "def" funcname "(" [parameter_list] ")" ":" suite parameter_list ::= (defparameter ",")* (~~"*" identifier [, "**" identifier] | "**" identifier | defparameter [","] ) defparameter ::= parameter ["=" expression] identifier ::= (letter|"_") (letter | digit | "_")* </code></pre> <p>In fact, the construct you are trying to use as an identifier is a subscription:</p> <pre><code>subscription ::= primary "[" expression_list "]" </code></pre>
6
2009-05-13T00:31:12Z
[ "python", "function", "dictionary", "parameters" ]
Why can't I pass a direct reference to a dictionary value to a function?
855,514
<p>Earlier today I asked a <a href="http://stackoverflow.com/questions/853483/can-i-pass-dictionary-values-entry-and-keys-to-function">question</a> about passing dictionary values to a function. While I understand now how to accomplish what I was trying to accomplish the why question (which was not asked) was never answered. So my follow up is why can't I </p> <pre><code>def myFunction(newDict['bubba']): some code to process the parameter </code></pre> <p>Is it simply because the parser rules do not allow this? I Googled for +Python +function +"allowable parameters" and did not find anything useful so I would appreciate any information. </p> <p>I am oversimplifying what is going on. I have a dictionary that is structured like</p> <pre><code>myDict={outerkey1:(innerkey1:value,innerkey2:value,. . .innerkeyn:value),outerkey2:(innerkey1:value,innerkey2:value,. . .innerkeyn:value),. . .} </code></pre> <p>As I said, I know how to do what I wanted-I got a very helpful answer. But I started wondering why </p> <pre><code> def myFunction(outerkey,myDict[outerkey]): </code></pre> <p>gives a syntax error which finely it occurred to me that it has to be a parsing problem.</p>
1
2009-05-13T00:25:53Z
855,543
<p>It looks like you might be confused between the <em>definition</em> of a function and <em>calling</em> that function. As a simple example:</p> <pre><code>def f(x): y = x * x print "x squared is", y </code></pre> <p>By itself, this function doesn't do anything (ie. it doesn't print anything). If you put this in a source file and run it, nothing will be output. But then if you add:</p> <pre><code>f(5) </code></pre> <p>you will get the output "x squared is 25". When Python encounters the name of the function followed by <em>actual</em> parameters, it substitutes the value(s) of those actual parameters for the <em>formal</em> parameter(s) in the function definition. In this case, the formal parameter is called <code>x</code>. Then Python runs the function <code>f</code> with the value of <code>x</code> as 5. Now, the big benefit is you can use the same function again with a different value:</p> <pre><code>f(10) </code></pre> <p>prints "x squared is 100".</p> <p>I hope I've understood the source of your difficulty correctly.</p>
2
2009-05-13T00:42:33Z
[ "python", "function", "dictionary", "parameters" ]