title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 33,968,149 | <p>Whitespace includes <strong>space, tabs and CRLF</strong>. So an elegant and <strong>one-liner</strong> string function we can use is <strong>translate</strong>. </p>
<p><code>' hello apple'.translate(None, ' \n\t\r')</code></p>
<p><strong>OR</strong> if you want to be thorough</p>
<pre><code>import string
' hello apple'.translate(None, string.whitespace)
</code></pre>
| 3 | 2015-11-28T05:45:56Z | [
"python",
"string",
"trim",
"strip"
] |
Python loop counter in a for loop | 1,185,545 | <p>In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected (<a href="http://www.python.org/dev/peps/pep-0212/">PEP 212</a> and <a href="http://www.python.org/dev/peps/pep-0281/">PEP 281</a>).</p>
<p>This is a simplified example of my problem. In my real application this is done with graphics and the whole menu has to be repainted each frame. But this demonstrates it in a simple text way that is easy to reproduce.</p>
<p>Maybe I should also add that I'm using Python 2.5, although I'm still interested if there is a way specific to 2.6 or higher.</p>
<pre><code># Draw all the options, but highlight the selected index
def draw_menu(options, selected_index):
counter = 0
for option in options:
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
counter += 1
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(option, 2) # Draw menu with "Option2" selected
</code></pre>
<p>When run, it outputs:</p>
<pre><code> [ ] Option 0
[ ] Option 1
[*] Option 2
[ ] Option 3
</code></pre>
| 101 | 2009-07-26T21:05:26Z | 1,185,557 | <p><strong>Use <a href="http://docs.python.org/library/functions.html#enumerate"><code>enumerate()</code></a> like so:</strong></p>
<pre><code>def draw_menu(options, selected_index):
for counter, option in enumerate(options):
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)
</code></pre>
<p><strong>Note</strong>: You can optionally put parenthesis around <code>counter, option</code>, like <code>(counter, option)</code>, if you want, but they're extraneous and not normally included.</p>
| 188 | 2009-07-26T21:09:15Z | [
"loops",
"for-loop",
"python"
] |
Python loop counter in a for loop | 1,185,545 | <p>In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected (<a href="http://www.python.org/dev/peps/pep-0212/">PEP 212</a> and <a href="http://www.python.org/dev/peps/pep-0281/">PEP 281</a>).</p>
<p>This is a simplified example of my problem. In my real application this is done with graphics and the whole menu has to be repainted each frame. But this demonstrates it in a simple text way that is easy to reproduce.</p>
<p>Maybe I should also add that I'm using Python 2.5, although I'm still interested if there is a way specific to 2.6 or higher.</p>
<pre><code># Draw all the options, but highlight the selected index
def draw_menu(options, selected_index):
counter = 0
for option in options:
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
counter += 1
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(option, 2) # Draw menu with "Option2" selected
</code></pre>
<p>When run, it outputs:</p>
<pre><code> [ ] Option 0
[ ] Option 1
[*] Option 2
[ ] Option 3
</code></pre>
| 101 | 2009-07-26T21:05:26Z | 1,185,564 | <p>You could also do:</p>
<pre><code> for option in options:
if option == options[selected_index]:
#print
else:
#print
</code></pre>
<p>Although you'd run into issues if there are duplicate options.</p>
| 4 | 2009-07-26T21:11:08Z | [
"loops",
"for-loop",
"python"
] |
Python loop counter in a for loop | 1,185,545 | <p>In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected (<a href="http://www.python.org/dev/peps/pep-0212/">PEP 212</a> and <a href="http://www.python.org/dev/peps/pep-0281/">PEP 281</a>).</p>
<p>This is a simplified example of my problem. In my real application this is done with graphics and the whole menu has to be repainted each frame. But this demonstrates it in a simple text way that is easy to reproduce.</p>
<p>Maybe I should also add that I'm using Python 2.5, although I'm still interested if there is a way specific to 2.6 or higher.</p>
<pre><code># Draw all the options, but highlight the selected index
def draw_menu(options, selected_index):
counter = 0
for option in options:
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
counter += 1
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(option, 2) # Draw menu with "Option2" selected
</code></pre>
<p>When run, it outputs:</p>
<pre><code> [ ] Option 0
[ ] Option 1
[*] Option 2
[ ] Option 3
</code></pre>
| 101 | 2009-07-26T21:05:26Z | 1,185,599 | <p>I'll sometimes do this:</p>
<pre><code>def draw_menu(options, selected_index):
for i in range(len(options)):
if i == selected_index:
print " [*] %s" % options[i]
else:
print " [ ] %s" % options[i]
</code></pre>
<p>Though I tend to avoid this if it means I'll be saying <code>options[i]</code> more than a couple of times.</p>
| 3 | 2009-07-26T21:28:17Z | [
"loops",
"for-loop",
"python"
] |
How do I define a unique property for a Model in Google App Engine? | 1,185,628 | <p>I need some properties to be unique. How can I achieve this?</p>
<p>Is there something like <code>unique=True</code>?</p>
<p>I'm using Google App Engine for Python.</p>
| 32 | 2009-07-26T21:41:29Z | 1,185,703 | <p>There's no built-in constraint for making sure a value is unique. You can do this however:</p>
<pre><code>query = MyModel.all(keys_only=True).filter('unique_property', value_to_be_used)
entity = query.get()
if entity:
raise Exception('unique_property must have a unique value!')
</code></pre>
<p>I use <code>keys_only=True</code> because it'll improve the performance slightly by not fetching the data for the entity.</p>
<p>A more efficient method would be to use a separate model with no fields whose key name is made up of property name + value. Then you could use <code>get_by_key_name</code> to fetch one or more of these composite key names and if you get one or more not-<code>None</code> values, you know there are duplicate values (and checking which values were not <code>None</code>, you'll know which ones were not unique.)</p>
<hr>
<p>As <em>onebyone</em> mentioned in the comments, these approaches – by their get first, put later nature – run the risk concurrency issues. Theoretically, an entity could be created just after the check for an existing value, and then the code after the check will still execute, leading to duplicate values. To prevent this, you will have to use transactions: <a href="http://code.google.com/appengine/docs/python/datastore/transactions.html" rel="nofollow">Transactions - Google App Engine</a></p>
<hr>
<p>If you're looking to check for uniqueness across <em>all</em> entities with transactions, you'd have to put all of them in the same group using the first method, which would be very inefficient. For transactions, use the second method like this:</p>
<pre><code>class UniqueConstraint(db.Model):
@classmethod
def check(cls, model, **values):
# Create a pseudo-key for use as an entity group.
parent = db.Key.from_path(model.kind(), 'unique-values')
# Build a list of key names to test.
key_names = []
for key in values:
key_names.append('%s:%s' % (key, values[key]))
def txn():
result = cls.get_by_key_name(key_names, parent)
for test in result:
if test: return False
for key_name in key_names:
uc = cls(key_name=key_name, parent=parent)
uc.put()
return True
return db.run_in_transaction(txn)
</code></pre>
<p><code>UniqueConstraint.check(...)</code> will assume that every single key/value pair must be unique to return success. The transaction will use a single entity group for every model kind. This way, the transaction is reliable for several different fields at once (for only one field, this would be much simpler.) Also, even if you've got fields with the same name in one or more models, they will not conflict with each other.</p>
| 21 | 2009-07-26T22:13:16Z | [
"python",
"google-app-engine",
"google-cloud-datastore"
] |
How do I define a unique property for a Model in Google App Engine? | 1,185,628 | <p>I need some properties to be unique. How can I achieve this?</p>
<p>Is there something like <code>unique=True</code>?</p>
<p>I'm using Google App Engine for Python.</p>
| 32 | 2009-07-26T21:41:29Z | 5,829,926 | <p>Google has provided function to do that:</p>
<p><a href="http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_or_insert">http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_or_insert</a></p>
<pre><code>Model.get_or_insert(key_name, **kwds)
</code></pre>
<p>Attempts to get the entity of the model's kind with the given key name. If it exists, get_or_insert() simply returns it. If it doesn't exist, a new entity with the given kind, name, and parameters in kwds is created, stored, and returned.</p>
<p>The get and subsequent (possible) put are wrapped in a transaction to ensure atomicity. Ths means that get_or_insert() will never overwrite an existing entity, and will insert a new entity if and only if no entity with the given kind and name exists.</p>
<p>In other words, get_or_insert() is equivalent to this Python code:</p>
<pre><code>def txn():
entity = MyModel.get_by_key_name(key_name, parent=kwds.get('parent'))
if entity is None:
entity = MyModel(key_name=key_name, **kwds)
entity.put()
return entity
return db.run_in_transaction(txn)
</code></pre>
<p><strong>Arguments:</strong></p>
<p>key_name
The name for the key of the entity
**kwds
Keyword arguments to pass to the model class's constructor if an instance with the specified key name doesn't exist. The parent argument is required if the desired entity has a parent.</p>
<p><strong>Note: get_or_insert() does not accept an RPC object.</strong></p>
<p>The method returns an instance of the model class that represents the requested entity, whether it existed or was created by the method. As with all datastore operations, this method can raise a TransactionFailedError if the transaction could not be completed.</p>
| 24 | 2011-04-29T08:44:07Z | [
"python",
"google-app-engine",
"google-cloud-datastore"
] |
How to solve the "Mastermind" guessing game? | 1,185,634 | <p>How would you create an algorithm to solve the following puzzle, "Mastermind"?</p>
<p>Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of the colours you guessed were the right colour in the right place ["blacks"] and how many (but not which) were the right colour but in the wrong place ["whites"]. The game ends when you guess correctly (4 blacks, 0 whites).</p>
<p>For example, if your opponent has chosen (blue, green, orange, red), and you guess (yellow, blue, green, red), you will get one "black" (for the red), and two whites (for the blue and green). You would get the same score for guessing (blue, orange, red, purple).</p>
<p>I'm interested in what algorithm you would choose, and (optionally) how you translate that into code (preferably Python). I'm interested in coded solutions that are:</p>
<ol>
<li>Clear (easily understood)</li>
<li>Concise</li>
<li>Efficient (fast in making a guess)</li>
<li>Effective (least number of guesses to solve the puzzle)</li>
<li>Flexible (can easily answer questions about the algorithm, e.g. what is its worst case?)</li>
<li>General (can be easily adapted to other types of puzzle than Mastermind)</li>
</ol>
<p>I'm happy with an algorithm that's very effective but not very efficient (provided it's not just poorly implemented!); however, a very efficient and effective algorithm implemented inflexibly and impenetrably is not of use.</p>
<p>I have my own (detailed) solution in Python which I have posted, but this is by no means the only or best approach, so please post more! I'm not expecting an essay ;)</p>
| 34 | 2009-07-26T21:43:36Z | 1,185,638 | <p>Key tools: entropy, greediness, branch-and-bound; Python, generators, itertools, decorate-undecorate pattern</p>
<p>In answering this question, I wanted to build up a language of useful functions to explore the problem. I will go through these functions, describing them and their intent. Originally, these had extensive docs, with small embedded unit tests tested using doctest; I can't praise this methodology highly enough as a brilliant way to implement test-driven-development. However, it does not translate well to StackOverflow, so I will not present it this way.</p>
<p>Firstly, I will be needing several standard modules and <strong>future</strong> imports (I work with Python 2.6).</p>
<pre><code>from __future__ import division # No need to cast to float when dividing
import collections, itertools, math
</code></pre>
<p>I will need a scoring function. Originally, this returned a tuple (blacks, whites), but I found output a little clearer if I used a namedtuple:</p>
<pre><code>Pegs = collections.namedtuple('Pegs', 'black white')
def mastermindScore(g1,g2):
matching = len(set(g1) & set(g2))
blacks = sum(1 for v1, v2 in itertools.izip(g1,g2) if v1 == v2)
return Pegs(blacks, matching-blacks)
</code></pre>
<p>To make my solution general, I pass in anything specific to the Mastermind problem as keyword arguments. I have therefore made a function that creates these arguments once, and use the **kwargs syntax to pass it around. This also allows me to easily add new attributes if I need them later. Note that I allow guesses to contain repeats, but constrain the opponent to pick distinct colours; to change this, I only need change G below. (If I wanted to allow repeats in the opponent's secret, I would need to change the scoring function as well.)</p>
<pre><code>def mastermind(colours, holes):
return dict(
G = set(itertools.product(colours,repeat=holes)),
V = set(itertools.permutations(colours, holes)),
score = mastermindScore,
endstates = (Pegs(holes, 0),))
def mediumGame():
return mastermind(("Yellow", "Blue", "Green", "Red", "Orange", "Purple"), 4)
</code></pre>
<p>Sometimes I will need to <em>partition</em> a set based on the result of applying a function to each element in the set. For instance, the numbers 1..10 can be partitioned into even and odd numbers by the function n % 2 (odds give 1, evens give 0). The following function returns such a partition, implemented as a map from the result of the function call to the set of elements that gave that result (e.g. { 0: evens, 1: odds }).</p>
<pre><code>def partition(S, func, *args, **kwargs):
partition = collections.defaultdict(set)
for v in S: partition[func(v, *args, **kwargs)].add(v)
return partition
</code></pre>
<p>I decided to explore a solver that uses a <em>greedy entropic approach</em>. At each step, it calculates the information that could be obtained from each possible guess, and selects the most informative guess. As the numbers of possibilities grow, this will scale badly (quadratically), but let's give it a try! First, I need a method to calculate the entropy (information) of a set of probabilities. This is just -âp log p. For convenience, however, I will allow input that are not normalized, i.e. do not add up to 1:</p>
<pre><code>def entropy(P):
total = sum(P)
return -sum(p*math.log(p, 2) for p in (v/total for v in P if v))
</code></pre>
<p>So how am I going to use this function? Well, for a given set of possibilities, V, and a given guess, g, the information we get from that guess can only come from the scoring function: more specifically, how that scoring function partitions our set of possibilities. We want to make a guess that distinguishes best among the remaining possibilites â divides them into the largest number of small sets â because that means we are much closer to the answer. This is exactly what the entropy function above is putting a number to: a large number of small sets will score higher than a small number of large sets. All we need to do is plumb it in.</p>
<pre><code>def decisionEntropy(V, g, score):
return entropy(collections.Counter(score(gi, g) for gi in V).values())
</code></pre>
<p>Of course, at any given step what we will actually have is a set of remaining possibilities, V, and a set of possible guesses we could make, G, and we will need to pick the guess which maximizes the entropy. Additionally, if several guesses have the same entropy, prefer to pick one which could also be a valid solution; this guarantees the approach will terminate. I use the standard python decorate-undecorate pattern together with the built-in max method to do this:</p>
<pre><code>def bestDecision(V, G, score):
return max((decisionEntropy(V, g, score), g in V, g) for g in G)[2]
</code></pre>
<p>Now all I need to do is repeatedly call this function until the right result is guessed. I went through a number of implementations of this algorithm until I found one that seemed right. Several of my functions will want to approach this in different ways: some enumerate all possible sequences of decisions (one per guess the opponent may have made), while others are only interested in a single path through the tree (if the opponent has already chosen a secret, and we are just trying to reach the solution). My solution is a "lazy tree", where each part of the tree is a generator that can be evaluated or not, allowing the user to avoid costly calculations they won't need. I also ended up using two more namedtuples, again for clarity of code.</p>
<pre><code>Node = collections.namedtuple('Node', 'decision branches')
Branch = collections.namedtuple('Branch', 'result subtree')
def lazySolutionTree(G, V, score, endstates, **kwargs):
decision = bestDecision(V, G, score)
branches = (Branch(result, None if result in endstates else
lazySolutionTree(G, pV, score=score, endstates=endstates))
for (result, pV) in partition(V, score, decision).iteritems())
yield Node(decision, branches) # Lazy evaluation
</code></pre>
<p>The following function evaluates a single path through this tree, based on a supplied scoring function:</p>
<pre><code>def solver(scorer, **kwargs):
lazyTree = lazySolutionTree(**kwargs)
steps = []
while lazyTree is not None:
t = lazyTree.next() # Evaluate node
result = scorer(t.decision)
steps.append((t.decision, result))
subtrees = [b.subtree for b in t.branches if b.result == result]
if len(subtrees) == 0:
raise Exception("No solution possible for given scores")
lazyTree = subtrees[0]
assert(result in endstates)
return steps
</code></pre>
<p>This can now be used to build an interactive game of Mastermind where the user scores the computer's guesses. Playing around with this reveals some interesting things. For example, the most informative first guess is of the form (yellow, yellow, blue, green), not (yellow, blue, green, red). Extra information is gained by using exactly half the available colours. This also holds for 6-colour 3-hole Mastermind â (yellow, blue, green) â and 8-colour 5-hole Mastermind â (yellow, yellow, blue, green, red).</p>
<p>But there are still many questions that are not easily answered with an interactive solver. For instance, what is the most number of steps needed by the greedy entropic approach? And how many inputs take this many steps? To make answering these questions easier, I first produce a simple function that turns the lazy tree of above into a set of paths through this tree, i.e. for each possible secret, a list of guesses and scores.</p>
<pre><code>def allSolutions(**kwargs):
def solutions(lazyTree):
return ((((t.decision, b.result),) + solution
for t in lazyTree for b in t.branches
for solution in solutions(b.subtree))
if lazyTree else ((),))
return solutions(lazySolutionTree(**kwargs))
</code></pre>
<p>Finding the worst case is a simple matter of finding the longest solution:</p>
<pre><code>def worstCaseSolution(**kwargs):
return max((len(s), s) for s in allSolutions(**kwargs)) [1]
</code></pre>
<p>It turns out that this solver will always complete in 5 steps or fewer. Five steps! I know that when I played Mastermind as a child, I often took longer than this. However, since creating this solver and playing around with it, I have greatly improved my technique, and 5 steps is indeed an achievable goal even when you don't have time to calculate the entropically ideal guess at each step ;)</p>
<p>How likely is it that the solver will take 5 steps? Will it ever finish in 1, or 2, steps? To find that out, I created another simple little function that calculates the solution length distribution:</p>
<pre><code>def solutionLengthDistribution(**kwargs):
return collections.Counter(len(s) for s in allSolutions(**kwargs))
</code></pre>
<p>For the greedy entropic approach, with repeats allowed: 7 cases take 2 steps; 55 cases take 3 steps; 229 cases take 4 steps; and 69 cases take the maximum of 5 steps.</p>
<p>Of course, there's no guarantee that the greedy entropic approach minimizes the worst-case number of steps. The final part of my general-purpose language is an algorithm that decides whether or not there are <em>any</em> solutions for a given worst-case bound. This will tell us whether greedy entropic is ideal or not. To do this, I adopt a branch-and-bound strategy:</p>
<pre><code>def solutionExists(maxsteps, G, V, score, **kwargs):
if len(V) == 1: return True
partitions = [partition(V, score, g).values() for g in G]
maxSize = max(len(P) for P in partitions) ** (maxsteps - 2)
partitions = (P for P in partitions if max(len(s) for s in P) <= maxSize)
return any(all(solutionExists(maxsteps-1,G,s,score) for l,s in
sorted((-len(s), s) for s in P)) for i,P in
sorted((-entropy(len(s) for s in P), P) for P in partitions))
</code></pre>
<p>This is definitely a complex function, so a bit more explanation is in order. The first step is to partition the remaining solutions based on their score after a guess, as before, but this time we don't know what guess we're going to make, so we store all partitions. Now we <em>could</em> just recurse into every one of these, effectively enumerating the entire universe of possible decision trees, but this would take a horrifically long time. Instead I observe that, if at this point there is no partition that divides the remaining solutions into more than n sets, then there can be no such partition at any future step either. If we have k steps left, that means we can distinguish between at most n<sup>k-1</sup> solutions before we run out of guesses (on the last step, we must always guess correctly). Thus we can discard any partitions that contain a score mapped to more than this many solutions. This is the next two lines of code.</p>
<p>The final line of code does the recursion, using Python's any and all functions for clarity, and trying the highest-entropy decisions first to hopefully minimize runtime in the positive case. It also recurses into the largest part of the partition first, as this is the most likely to fail quickly if the decision was wrong. Once again, I use the standard decorate-undecorate pattern, this time to wrap Python's <em>sorted</em> function.</p>
<pre><code>def lowerBoundOnWorstCaseSolution(**kwargs):
for steps in itertools.count(1):
if solutionExists(maxsteps=steps, **kwargs):
return steps
</code></pre>
<p>By calling solutionExists repeatedly with an increasing number of steps, we get a strict lower bound on the number of steps needed in the worst case for a Mastermind solution: 5 steps. The greedy entropic approach is indeed optimal.</p>
<p>Out of curiosity, I invented another guessing game, which I nicknamed "twoD". In this, you try to guess a pair of numbers; at each step, you get told if your answer is correct, if the numbers you guessed are no less than the corresponding ones in the secret, and if the numbers are no greater.</p>
<pre><code>Comparison = collections.namedtuple('Comparison', 'less greater equal')
def twoDScorer(x, y):
return Comparison(all(r[0] <= r[1] for r in zip(x, y)),
all(r[0] >= r[1] for r in zip(x, y)),
x == y)
def twoD():
G = set(itertools.product(xrange(5), repeat=2))
return dict(G = G, V = G, score = twoDScorer,
endstates = set(Comparison(True, True, True)))
</code></pre>
<p>For this game, the greedy entropic approach has a worst case of five steps, but there is a better solution possible with a worst case of four steps, confirming my intuition that myopic greediness is only coincidentally ideal for Mastermind. More importantly, this has shown how flexible my language is: all the same methods work for this new guessing game as did for Mastermind, letting me explore other games with a minimum of extra coding.</p>
<p>What about performance? Obviously, being implemented in Python, this code is not going to be blazingly fast. I've also dropped some possible optimizations in favour of clear code.</p>
<p>One cheap optimization is to observe that, on the first move, most guesses are basically identical: (yellow, blue, green, red) is really no different from (blue, red, green, yellow), or (orange, yellow, red, purple). This greatly reduces the number of guesses we need consider on the first step â otherwise the most costly decision in the game.</p>
<p>However, because of the large runtime growth rate of this problem, I was not able to solve the 8-colour, 5-hole Mastermind problem, even with this optimization. Instead, I ported the algorithms to C++, keeping the general structure the same and employing bitwise operations to boost performance in the critical inner loops, for a speedup of many orders of magnitude. I leave this as an exercise to the reader :)</p>
| 39 | 2009-07-26T21:44:24Z | [
"python",
"algorithm"
] |
How to solve the "Mastermind" guessing game? | 1,185,634 | <p>How would you create an algorithm to solve the following puzzle, "Mastermind"?</p>
<p>Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of the colours you guessed were the right colour in the right place ["blacks"] and how many (but not which) were the right colour but in the wrong place ["whites"]. The game ends when you guess correctly (4 blacks, 0 whites).</p>
<p>For example, if your opponent has chosen (blue, green, orange, red), and you guess (yellow, blue, green, red), you will get one "black" (for the red), and two whites (for the blue and green). You would get the same score for guessing (blue, orange, red, purple).</p>
<p>I'm interested in what algorithm you would choose, and (optionally) how you translate that into code (preferably Python). I'm interested in coded solutions that are:</p>
<ol>
<li>Clear (easily understood)</li>
<li>Concise</li>
<li>Efficient (fast in making a guess)</li>
<li>Effective (least number of guesses to solve the puzzle)</li>
<li>Flexible (can easily answer questions about the algorithm, e.g. what is its worst case?)</li>
<li>General (can be easily adapted to other types of puzzle than Mastermind)</li>
</ol>
<p>I'm happy with an algorithm that's very effective but not very efficient (provided it's not just poorly implemented!); however, a very efficient and effective algorithm implemented inflexibly and impenetrably is not of use.</p>
<p>I have my own (detailed) solution in Python which I have posted, but this is by no means the only or best approach, so please post more! I'm not expecting an essay ;)</p>
| 34 | 2009-07-26T21:43:36Z | 1,185,776 | <p>Have you seem Raymond Hettingers <a href="http://code.activestate.com/recipes/496907/">attempt</a>? They certainly match up to some of your requirements.</p>
<p>I wonder how his solutions compares to yours.</p>
| 7 | 2009-07-26T22:47:24Z | [
"python",
"algorithm"
] |
How to solve the "Mastermind" guessing game? | 1,185,634 | <p>How would you create an algorithm to solve the following puzzle, "Mastermind"?</p>
<p>Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of the colours you guessed were the right colour in the right place ["blacks"] and how many (but not which) were the right colour but in the wrong place ["whites"]. The game ends when you guess correctly (4 blacks, 0 whites).</p>
<p>For example, if your opponent has chosen (blue, green, orange, red), and you guess (yellow, blue, green, red), you will get one "black" (for the red), and two whites (for the blue and green). You would get the same score for guessing (blue, orange, red, purple).</p>
<p>I'm interested in what algorithm you would choose, and (optionally) how you translate that into code (preferably Python). I'm interested in coded solutions that are:</p>
<ol>
<li>Clear (easily understood)</li>
<li>Concise</li>
<li>Efficient (fast in making a guess)</li>
<li>Effective (least number of guesses to solve the puzzle)</li>
<li>Flexible (can easily answer questions about the algorithm, e.g. what is its worst case?)</li>
<li>General (can be easily adapted to other types of puzzle than Mastermind)</li>
</ol>
<p>I'm happy with an algorithm that's very effective but not very efficient (provided it's not just poorly implemented!); however, a very efficient and effective algorithm implemented inflexibly and impenetrably is not of use.</p>
<p>I have my own (detailed) solution in Python which I have posted, but this is by no means the only or best approach, so please post more! I'm not expecting an essay ;)</p>
| 34 | 2009-07-26T21:43:36Z | 1,339,515 | <p>There is a great site about MasterMind strategy <a href="http://home.pacific.net.hk/~kfzhou/mmh.html#Tutor" rel="nofollow">here</a>. The author starts off with very simple MasterMind problems (using numbers rather than letters, and ignoring order and repetition) and gradually builds up to a full MasterMind problem (using colours, which can be repeated, in any order, <em>even</em> with the possibility of errors in the clues).</p>
<p>The seven tutorials that are presented are as follows:</p>
<ul>
<li><a href="http://home.pacific.net.hk/~kfzhou/Mmtutor1e.html" rel="nofollow">Tutorial 1 - The simplest game setting (<em>no errors, fixed order, no repetition</em>)</a></li>
<li><a href="http://home.pacific.net.hk/~kfzhou/Mmtutor2e.html" rel="nofollow">Tutorial 2 - Code may contain blank spaces (<em>no errors, fixed order, no repetition</em>)</a></li>
<li><a href="http://home.pacific.net.hk/~kfzhou/Mmtutor3e.html" rel="nofollow">Tutorial 3 - Hints may contain errors (<em>fixed order, no repetition</em>)</a></li>
<li><a href="http://home.pacific.net.hk/~kfzhou/Mmtutor4e.html" rel="nofollow">Tutorial 4 - Game started from the middle (<em>no errors, fixed order, no repetition</em>)</a></li>
<li><a href="http://home.pacific.net.hk/~kfzhou/Mmtutor5e.html" rel="nofollow">Tutorial 5 - Digits / colours may be repeated (<em>no errors, fixed order, each colour repeated at most 4 times</em>)</a></li>
<li><a href="http://home.pacific.net.hk/~kfzhou/Mmtutor6e.html" rel="nofollow">Tutorial 6 - Digits / colours arranged in random order (<em>no errors, random order, no repetition</em>)</a></li>
<li><a href="http://home.pacific.net.hk/~kfzhou/Mmtutor7e.html" rel="nofollow">Tutorial 7 - Putting it all together (<em>no errors, random order, each colour repeated at most 4 times</em>)</a></li>
</ul>
| 4 | 2009-08-27T07:54:17Z | [
"python",
"algorithm"
] |
How to solve the "Mastermind" guessing game? | 1,185,634 | <p>How would you create an algorithm to solve the following puzzle, "Mastermind"?</p>
<p>Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of the colours you guessed were the right colour in the right place ["blacks"] and how many (but not which) were the right colour but in the wrong place ["whites"]. The game ends when you guess correctly (4 blacks, 0 whites).</p>
<p>For example, if your opponent has chosen (blue, green, orange, red), and you guess (yellow, blue, green, red), you will get one "black" (for the red), and two whites (for the blue and green). You would get the same score for guessing (blue, orange, red, purple).</p>
<p>I'm interested in what algorithm you would choose, and (optionally) how you translate that into code (preferably Python). I'm interested in coded solutions that are:</p>
<ol>
<li>Clear (easily understood)</li>
<li>Concise</li>
<li>Efficient (fast in making a guess)</li>
<li>Effective (least number of guesses to solve the puzzle)</li>
<li>Flexible (can easily answer questions about the algorithm, e.g. what is its worst case?)</li>
<li>General (can be easily adapted to other types of puzzle than Mastermind)</li>
</ol>
<p>I'm happy with an algorithm that's very effective but not very efficient (provided it's not just poorly implemented!); however, a very efficient and effective algorithm implemented inflexibly and impenetrably is not of use.</p>
<p>I have my own (detailed) solution in Python which I have posted, but this is by no means the only or best approach, so please post more! I'm not expecting an essay ;)</p>
| 34 | 2009-07-26T21:43:36Z | 1,353,367 | <p>I once wrote a "<a href="http://en.wikipedia.org/wiki/Jotto" rel="nofollow">Jotto</a>" solver which is essentially "Master Mind" with words. (We each pick a word and we take turns guessing at each other's word, scoring "right on" (exact) matches and "elsewhere" (correct letter/color, but wrong placement).</p>
<p><strong>The key to solving such a problem is the realization that the scoring function is symmetric.</strong></p>
<p>In other words if <code>score(myguess) == (1,2)</code> then I can use the same <code>score()</code> function to compare my previous guess with any other possibility and eliminate any that don't give exactly the same score.</p>
<p>Let me give an example: The hidden word (target) is "score" ... the current guess is "fools" --- the score is 1,1 (one letter, 'o', is "right on"; another letter, 's', is "elsewhere"). I can eliminate the word "guess" because the `score("guess") (against "fools") returns (1,0) (the final 's' matches, but nothing else does). So the word "guess" is not consistent with "fools" and a score against some unknown word that gave returned a score of (1,1).</p>
<p>So I now can walk through every five letter word (or combination of five colors/letters/digits etc) and eliminate anything that doesn't score 1,1 against "fools." Do that at each iteration and you'll very rapidly converge on the target. (For five letter words I was able to get within 6 tries every time ... and usually only 3 or 4). Of course there's only 6000 or so "words" and you're eliminating close to 95% for each guess.</p>
<p>Note: for the following discussion I'm talking about five letter "combination" rather than four elements of six colors. The same algorithms apply; however, the problem is orders of magnitude smaller for the old "Master Mind" game ... there are only 1296 combinations (6**4) of colored pegs in the classic "Master Mind" program, assuming duplicates are allowed. The line of reasoning that leads to the convergence involves some combinatorics: there are 20 non-winning possible scores for a five element target (<code>n = [(a,b) for a in range(5) for b in range(6) if a+b <= 5]</code> to see all of them if you're curious. We would, therefore, expect that any random valid selection would have a roughly 5% chance of matching our score ... the other 95% won't and therefore will be eliminated for each scored guess. This doesn't account for possible clustering in word patterns but the real world behavior is close enough for words and definitely even closer for "Master Mind" rules. However, with only 6 colors in 4 slots we only have 14 possible non-winning scores so our convergence isn't quite as fast).</p>
<p>For Jotto the two minor challenges are: generating a good world list (<code>awk -f 'length($0)==5' /usr/share/dict/words</code> or similar on a UNIX system) and what to do if the user has picked a word that not in our dictionary (generate every letter combination, 'aaaaa' through 'zzzzz' --- which is 26 ** 5 ... or ~1.1 million). A trivial combination generator in Python takes about 1 minute to generate all those strings ... an optimized one should to far better. (I can also add a requirement that every "word" have at least one vowel ... but this constraint doesn't help much --- 5 vowels * 5 possible locations for that and then multiplied by 26 ** 4 other combinations).</p>
<p>For Master Mind you use the same combination generator ... but with only 4 or 5 "letters" (colors). Every 6-color combination (15,625 of them) can be generated in under a second (using the same combination generator as I used above).</p>
<p>If I was writing this "Jotto" program today, in Python for example, I would "cheat" by having a thread generating all the letter combos in the background while I was still eliminated words from the dictionary (while my opponent was scoring me, guessing, etc). As I generated them I'd also eliminate against all guesses thus far. Thus I would, after I'd eliminated all known words, have a relatively small list of possibilities and against a human player I've "hidden" most of my computation lag by doing it in parallel to their input. (And, if I wrote a web server version of such a program I'd have my web engine talk to a local daemon to ask for sequences consistent with a set of scores. The daemon would keep a locally generated list of all letter combinations and would use a <code>select.select()</code> model to feed possibilities back to each of the running instances of the game --- each would feed my daemon word/score pairs which my daemon would apply as a filter on the possibilities it feeds back to that client).</p>
<p>(By comparison I wrote my version of "Jotto" about 20 years ago on an XT using Borland TurboPascal ... and it could do each elimination iteration --- starting with its compiled in list of a few thousand words --- in well under a second. I build its word list by writing a simple letter combination generator (see below) ... saving the results to a moderately large file, then running my word processor's spell check on that with a macro to delete everything that was "mis-spelled" --- then I used another macro to wrap all the remaining lines in the correct punctuation to make them valid static assignments to my array, which was a #include file to my program. All that let me build a standalone game program that "knew" just about every valid English 5 letter word; the program was a .COM --- less than 50KB if I recall correctly).</p>
<p>For other reasons I've recently written a simple arbitrary combination generator in Python. It's about 35 lines of code and I've posted that to my "trite snippets" wiki on bitbucket.org ... it's not a "generator" in the Python sense ... but a class you can instantiate to an infinite sequence of "numeric" or "symbolic" combination of elements (essentially counting in any positive integer base).</p>
<p>You can find it at: <a href="http://bitbucket.org/jimd/trite-snippets/wiki/Arbitrary_Sequence_Combination_Generator" rel="nofollow">Trite Snippets: Arbitrary Sequence Combination Generator</a></p>
<p>For the exact match part of our <code>score()</code> function you can just use this:</p>
<pre><code>def score(this, that):
'''Simple "Master Mind" scoring function'''
exact = len([x for x,y in zip(this, that) if x==y])
### Calculating "other" (white pegs) goes here:
### ...
###
return (exact,other)
</code></pre>
<p>I think this exemplifies some of the beauty of Python: <code>zip()</code> up the two sequences,
return any that match, and take the length of the results).</p>
<p>Finding the matches in "other" locations is deceptively more complicated. If no repeats were allowed then you could simply use sets to find the intersections.</p>
<p>[In my earlier edit of this message, when I realized how I could use <code>zip()</code> for exact matches, I erroneously thought we could get away with <code>other = len([x for x,y in zip(sorted(x), sorted(y)) if x==y]) - exact</code> ... but it was late and I was tired. As I slept on it I realized that the method was flawed. <strong>Bad, Jim! Don't post without <em>adequate</em> testing!* (Tested several cases that happened to work)</strong>].</p>
<p>In the past the approach I used was to sort both lists, compare the heads of each: if the heads are equal, increment the count and pop new items from both lists. otherwise pop a new value into the lesser of the two heads and try again. Break as soon as either list is empty.</p>
<p>This does work; but it's fairly verbose. The best I can come up with using that approach is just over a dozen lines of code:</p>
<pre><code>other = 0
x = sorted(this) ## Implicitly converts to a list!
y = sorted(that)
while len(x) and len(y):
if x[0] == y[0]:
other += 1
x.pop(0)
y.pop(0)
elif x[0] < y[0]:
x.pop(0)
else:
y.pop(0)
other -= exact
</code></pre>
<p>Using a dictionary I can trim that down to about nine:</p>
<pre><code>other = 0
counters = dict()
for i in this:
counters[i] = counters.get(i,0) + 1
for i in that:
if counters.get(i,0) > 0:
other += 1
counters[i] -= 1
other -= exact
</code></pre>
<p>(Using the new "collections.Counter" class (Python3 and slated for Python 2.7?) I could presumably reduce this a little more; three lines here are initializing the counters collection).</p>
<p>It's important to decrement the "counter" when we find a match and it's vital to test for counter greater than zero in our test. If a given letter/symbol appears in "this" once and "that" twice then it must only be counted as a match once.</p>
<p>The first approach is definitely a bit trickier to write (one must be careful to avoid boundaries). Also in a couple of quick benchmarks (testing a million randomly generated pairs of letter patterns) the first approach takes about 70% longer as the one using dictionaries. (Generating the million pairs of strings using <code>random.shuffle()</code> took over twice as long as the slower of the scoring functions, on the other hand).</p>
<p>A formal analysis of the performance of these two functions would be complicated. The first method has two sorts, so that would be 2 * O(n<em>log(n)) ... and it iterates through at least one of the two strings and possibly has to iterate all the way to the end of the other string (best case O(n), worst case O(2n)) -- force I'm mis-using big-O notation here, but this is just a rough estimate. The second case depends entirely on the perfomance characteristics of the dictionary. If we were using b-trees then the performance would be roughly O(n</em>log(n) for creation and finding each element from the other string therein would be another O(n*log(n)) operation. However, Python dictionaries are very efficient and these operations should be close to constant time (very few hash collisions). Thus we'd expect a performance of roughly O(2n) ... which of course simplifies to O(n). That roughly matches my benchmark results.</p>
<p>Glancing over the Wikipedia article on "<a href="http://en.wikipedia.org/wiki/Mastermind_%28board_game%29" rel="nofollow">Master Mind</a>" I see that Donald Knuth used an approach which starts similarly to mine (and 10 years earlier) but he added one significant optimization. After gathering every remaining possibility he selects which ever one would eliminate the largest number of possibilities on the next round. I considered such an enhancement to my own program and rejected the idea for practical reasons. In his case he was searching for an optimal (mathematical) solution. In my case I was concerned about playability (on an XT, preferably using less than 64KB of RAM, though I could switch to .EXE format and use up to 640KB). I wanted to keep the response time down in the realm of one or two seconds (which was easy with my approach but which would be much more difficult with the further speculative scoring). (Remember I was working in Pascal, under MS-DOS ... no threads, though I did implement support for crude asynchronous polling of the UI which turned out to be unnecessary)</p>
<p>If I were writing such a thing today I'd add a thread to do the better selection, too. This would allow me to give the best guess I'd found within a certain time constraint, to guarantee that my player didn't have to wait too long for my guess. Naturally my selection/elimination would be running while waiting for my opponent's guesses.</p>
| 10 | 2009-08-30T07:41:54Z | [
"python",
"algorithm"
] |
How to solve the "Mastermind" guessing game? | 1,185,634 | <p>How would you create an algorithm to solve the following puzzle, "Mastermind"?</p>
<p>Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of the colours you guessed were the right colour in the right place ["blacks"] and how many (but not which) were the right colour but in the wrong place ["whites"]. The game ends when you guess correctly (4 blacks, 0 whites).</p>
<p>For example, if your opponent has chosen (blue, green, orange, red), and you guess (yellow, blue, green, red), you will get one "black" (for the red), and two whites (for the blue and green). You would get the same score for guessing (blue, orange, red, purple).</p>
<p>I'm interested in what algorithm you would choose, and (optionally) how you translate that into code (preferably Python). I'm interested in coded solutions that are:</p>
<ol>
<li>Clear (easily understood)</li>
<li>Concise</li>
<li>Efficient (fast in making a guess)</li>
<li>Effective (least number of guesses to solve the puzzle)</li>
<li>Flexible (can easily answer questions about the algorithm, e.g. what is its worst case?)</li>
<li>General (can be easily adapted to other types of puzzle than Mastermind)</li>
</ol>
<p>I'm happy with an algorithm that's very effective but not very efficient (provided it's not just poorly implemented!); however, a very efficient and effective algorithm implemented inflexibly and impenetrably is not of use.</p>
<p>I have my own (detailed) solution in Python which I have posted, but this is by no means the only or best approach, so please post more! I'm not expecting an essay ;)</p>
| 34 | 2009-07-26T21:43:36Z | 7,828,779 | <p>Just thought I'd contribute my 90 odd lines of code. I've build upon <a href="http://stackoverflow.com/questions/1185634/how-to-solve-the-mastermind-guessing-game/1353367#1353367">@Jim Dennis</a>' answer, mostly taking away the hint on symetric scoring. I've implemented the minimax algorithm as described on the <a href="http://en.wikipedia.org/wiki/Mastermind_%28board_game%29" rel="nofollow">Mastermind wikipedia article</a> by Knuth, with one exception: I restrict my next move to current list of possible solutions, as I found performance deteriorated badly when taking all possible solutions into account at each step. The current approach leaves me with a worst case of 6 guesses for any combination, each found in well under a second.</p>
<p>It's perhaps important to note that I make no restriction whatsoever on the hidden sequence, allowing for any number of repeats.</p>
<pre><code>from itertools import product, tee
from random import choice
COLORS = 'red ', 'green', 'blue', 'yellow', 'purple', 'pink'#, 'grey', 'white', 'black', 'orange', 'brown', 'mauve', '-gap-'
HOLES = 4
def random_solution():
"""Generate a random solution."""
return tuple(choice(COLORS) for i in range(HOLES))
def all_solutions():
"""Generate all possible solutions."""
for solution in product(*tee(COLORS, HOLES)):
yield solution
def filter_matching_result(solution_space, guess, result):
"""Filter solutions for matches that produce a specific result for a guess."""
for solution in solution_space:
if score(guess, solution) == result:
yield solution
def score(actual, guess):
"""Calculate score of guess against actual."""
result = []
#Black pin for every color at right position
actual_list = list(actual)
guess_list = list(guess)
black_positions = [number for number, pair in enumerate(zip(actual_list, guess_list)) if pair[0] == pair[1]]
for number in reversed(black_positions):
del actual_list[number]
del guess_list[number]
result.append('black')
#White pin for every color at wrong position
for color in guess_list:
if color in actual_list:
#Remove the match so we can't score it again for duplicate colors
actual_list.remove(color)
result.append('white')
#Return a tuple, which is suitable as a dictionary key
return tuple(result)
def minimal_eliminated(solution_space, solution):
"""For solution calculate how many possibilities from S would be eliminated for each possible colored/white score.
The score of the guess is the least of such values."""
result_counter = {}
for option in solution_space:
result = score(solution, option)
if result not in result_counter.keys():
result_counter[result] = 1
else:
result_counter[result] += 1
return len(solution_space) - max(result_counter.values())
def best_move(solution_space):
"""Determine the best move in the solution space, being the one that restricts the number of hits the most."""
elim_for_solution = dict((minimal_eliminated(solution_space, solution), solution) for solution in solution_space)
max_elimintated = max(elim_for_solution.keys())
return elim_for_solution[max_elimintated]
def main(actual = None):
"""Solve a game of mastermind."""
#Generate random 'hidden' sequence if actual is None
if actual == None:
actual = random_solution()
#Start the game of by choosing n unique colors
current_guess = COLORS[:HOLES]
#Initialize solution space to all solutions
solution_space = all_solutions()
guesses = 1
while True:
#Calculate current score
current_score = score(actual, current_guess)
#print '\t'.join(current_guess), '\t->\t', '\t'.join(current_score)
if current_score == tuple(['black'] * HOLES):
print guesses, 'guesses for\t', '\t'.join(actual)
return guesses
#Restrict solution space to exactly those hits that have current_score against current_guess
solution_space = tuple(filter_matching_result(solution_space, current_guess, current_score))
#Pick the candidate that will limit the search space most
current_guess = best_move(solution_space)
guesses += 1
if __name__ == '__main__':
print max(main(sol) for sol in all_solutions())
</code></pre>
<p>Should anyone spot any possible improvements to the above code than I would be very much interested in your suggestions. </p>
| 1 | 2011-10-19T22:03:33Z | [
"python",
"algorithm"
] |
How to solve the "Mastermind" guessing game? | 1,185,634 | <p>How would you create an algorithm to solve the following puzzle, "Mastermind"?</p>
<p>Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of the colours you guessed were the right colour in the right place ["blacks"] and how many (but not which) were the right colour but in the wrong place ["whites"]. The game ends when you guess correctly (4 blacks, 0 whites).</p>
<p>For example, if your opponent has chosen (blue, green, orange, red), and you guess (yellow, blue, green, red), you will get one "black" (for the red), and two whites (for the blue and green). You would get the same score for guessing (blue, orange, red, purple).</p>
<p>I'm interested in what algorithm you would choose, and (optionally) how you translate that into code (preferably Python). I'm interested in coded solutions that are:</p>
<ol>
<li>Clear (easily understood)</li>
<li>Concise</li>
<li>Efficient (fast in making a guess)</li>
<li>Effective (least number of guesses to solve the puzzle)</li>
<li>Flexible (can easily answer questions about the algorithm, e.g. what is its worst case?)</li>
<li>General (can be easily adapted to other types of puzzle than Mastermind)</li>
</ol>
<p>I'm happy with an algorithm that's very effective but not very efficient (provided it's not just poorly implemented!); however, a very efficient and effective algorithm implemented inflexibly and impenetrably is not of use.</p>
<p>I have my own (detailed) solution in Python which I have posted, but this is by no means the only or best approach, so please post more! I'm not expecting an essay ;)</p>
| 34 | 2009-07-26T21:43:36Z | 9,515,347 | <p>To work out the "worst" case, instead of using entropic I am looking to the partition that has the maximum number of elements, then select the try that is a minimum for this maximum => This will give me the minimum number of remaining possibility when I am not lucky (which happens in the worst case).</p>
<p>This always solve standard case in 5 attempts, but it is not a full proof that 5 attempts are really needed because it could happen that for next step a bigger set possibilities would have given a better result than a smaller one (because easier to distinguish between).</p>
<p>Though for the "Standard game" with 1680 I have a simple formal proof:
For the first step the try that gives the minimum for the partition with the maximum number is 0,0,1,1: 256. Playing 0,0,1,2 is not as good: 276.
For each subsequent try there are 14 outcomes (1 not placed and 3 placed is impossible) and 4 placed is giving a partition of 1. This means that in the best case (all partition same size) we will get a maximum partition that is a minimum of (number of possibilities - 1)/13 (rounded up because we have integer so necessarily some will be less and other more, so that the maximum is rounded up).</p>
<p>If I apply this:</p>
<p>After first play (0,0,1,1) I am getting 256 left.</p>
<p>After second try: 20 = (256-1)/13</p>
<p>After third try : 2 = (20-1)/13</p>
<p>Then I have no choice but to try one of the two left for the 4th try. </p>
<p>If I am unlucky a fifth try is needed.</p>
<p>This proves we need at least 5 tries (but not that this is enough).</p>
| 0 | 2012-03-01T11:28:31Z | [
"python",
"algorithm"
] |
How to solve the "Mastermind" guessing game? | 1,185,634 | <p>How would you create an algorithm to solve the following puzzle, "Mastermind"?</p>
<p>Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of the colours you guessed were the right colour in the right place ["blacks"] and how many (but not which) were the right colour but in the wrong place ["whites"]. The game ends when you guess correctly (4 blacks, 0 whites).</p>
<p>For example, if your opponent has chosen (blue, green, orange, red), and you guess (yellow, blue, green, red), you will get one "black" (for the red), and two whites (for the blue and green). You would get the same score for guessing (blue, orange, red, purple).</p>
<p>I'm interested in what algorithm you would choose, and (optionally) how you translate that into code (preferably Python). I'm interested in coded solutions that are:</p>
<ol>
<li>Clear (easily understood)</li>
<li>Concise</li>
<li>Efficient (fast in making a guess)</li>
<li>Effective (least number of guesses to solve the puzzle)</li>
<li>Flexible (can easily answer questions about the algorithm, e.g. what is its worst case?)</li>
<li>General (can be easily adapted to other types of puzzle than Mastermind)</li>
</ol>
<p>I'm happy with an algorithm that's very effective but not very efficient (provided it's not just poorly implemented!); however, a very efficient and effective algorithm implemented inflexibly and impenetrably is not of use.</p>
<p>I have my own (detailed) solution in Python which I have posted, but this is by no means the only or best approach, so please post more! I'm not expecting an essay ;)</p>
| 34 | 2009-07-26T21:43:36Z | 13,945,649 | <p>Here is a generic algorithm I wrote that uses numbers to represent the different colours. Easy to change, but I find numbers to be a lot easier to work with than strings. </p>
<p>You can feel free to use any whole or part of this algorithm, as long as credit is given accordingly. </p>
<p>Please note I'm only a Grade 12 Computer Science student, so I am willing to bet that there are definitely more optimized solutions available.</p>
<p>Regardless, here's the code:</p>
<pre><code>import random
def main():
userAns = raw_input("Enter your tuple, and I will crack it in six moves or less: ")
play(ans=eval("("+userAns+")"),guess=(0,0,0,0),previousGuess=[])
def play(ans=(6,1,3,5),guess=(0,0,0,0),previousGuess=[]):
if(guess==(0,0,0,0)):
guess = genGuess(guess,ans)
else:
checker = -1
while(checker==-1):
guess,checker = genLogicalGuess(guess,previousGuess,ans)
print guess, ans
if not(guess==ans):
previousGuess.append(guess)
base = check(ans,guess)
play(ans=ans,guess=base,previousGuess=previousGuess)
else:
print "Found it!"
def genGuess(guess,ans):
guess = []
for i in range(0,len(ans),1):
guess.append(random.randint(1,6))
return tuple(guess)
def genLogicalGuess(guess,previousGuess,ans):
newGuess = list(guess)
count = 0
#Generate guess
for i in range(0,len(newGuess),1):
if(newGuess[i]==-1):
newGuess.insert(i,random.randint(1,6))
newGuess.pop(i+1)
for item in previousGuess:
for i in range(0,len(newGuess),1):
if((newGuess[i]==item[i]) and (newGuess[i]!=ans[i])):
newGuess.insert(i,-1)
newGuess.pop(i+1)
count+=1
if(count>0):
return guess,-1
else:
guess = tuple(newGuess)
return guess,0
def check(ans,guess):
base = []
for i in range(0,len(zip(ans,guess)),1):
if not(zip(ans,guess)[i][0] == zip(ans,guess)[i][1]):
base.append(-1)
else:
base.append(zip(ans,guess)[i][1])
return tuple(base)
main()
</code></pre>
| 0 | 2012-12-19T04:45:00Z | [
"python",
"algorithm"
] |
How to solve the "Mastermind" guessing game? | 1,185,634 | <p>How would you create an algorithm to solve the following puzzle, "Mastermind"?</p>
<p>Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of the colours you guessed were the right colour in the right place ["blacks"] and how many (but not which) were the right colour but in the wrong place ["whites"]. The game ends when you guess correctly (4 blacks, 0 whites).</p>
<p>For example, if your opponent has chosen (blue, green, orange, red), and you guess (yellow, blue, green, red), you will get one "black" (for the red), and two whites (for the blue and green). You would get the same score for guessing (blue, orange, red, purple).</p>
<p>I'm interested in what algorithm you would choose, and (optionally) how you translate that into code (preferably Python). I'm interested in coded solutions that are:</p>
<ol>
<li>Clear (easily understood)</li>
<li>Concise</li>
<li>Efficient (fast in making a guess)</li>
<li>Effective (least number of guesses to solve the puzzle)</li>
<li>Flexible (can easily answer questions about the algorithm, e.g. what is its worst case?)</li>
<li>General (can be easily adapted to other types of puzzle than Mastermind)</li>
</ol>
<p>I'm happy with an algorithm that's very effective but not very efficient (provided it's not just poorly implemented!); however, a very efficient and effective algorithm implemented inflexibly and impenetrably is not of use.</p>
<p>I have my own (detailed) solution in Python which I have posted, but this is by no means the only or best approach, so please post more! I'm not expecting an essay ;)</p>
| 34 | 2009-07-26T21:43:36Z | 20,725,715 | <p>Here's a link to pure Python solver for Mastermind(tm): <a href="http://code.activestate.com/recipes/496907-mastermind-style-code-breaking/" rel="nofollow">http://code.activestate.com/recipes/496907-mastermind-style-code-breaking/</a> It has a simple version, a way to experiment with various guessing strategies, performance measurement, and an optional C accelerator.</p>
<p>The core of the recipe is short and sweet:</p>
<pre><code>import random
from itertools import izip, imap
digits = 4
fmt = '%0' + str(digits) + 'd'
searchspace = tuple([tuple(map(int,fmt % i)) for i in range(0,10**digits)])
def compare(a, b, imap=imap, sum=sum, izip=izip, min=min):
count1 = [0] * 10
count2 = [0] * 10
strikes = 0
for dig1, dig2 in izip(a,b):
if dig1 == dig2:
strikes += 1
count1[dig1] += 1
count2[dig2] += 1
balls = sum(imap(min, count1, count2)) - strikes
return (strikes, balls)
def rungame(target, strategy, verbose=True, maxtries=15):
possibles = list(searchspace)
for i in xrange(maxtries):
g = strategy(i, possibles)
if verbose:
print "Out of %7d possibilities. I'll guess %r" % (len(possibles), g),
score = compare(g, target)
if verbose:
print ' ---> ', score
if score[0] == digits:
if verbose:
print "That's it. After %d tries, I won." % (i+1,)
break
possibles = [n for n in possibles if compare(g, n) == score]
return i+1
def strategy_allrand(i, possibles):
return random.choice(possibles)
if __name__ == '__main__':
hidden_code = random.choice(searchspace)
rungame(hidden_code, strategy_allrand)
</code></pre>
<p>Here is what the output looks like:</p>
<pre><code>Out of 10000 possibilities. I'll guess (6, 4, 0, 9) ---> (1, 0)
Out of 1372 possibilities. I'll guess (7, 4, 5, 8) ---> (1, 1)
Out of 204 possibilities. I'll guess (1, 4, 2, 7) ---> (2, 1)
Out of 11 possibilities. I'll guess (1, 4, 7, 1) ---> (3, 0)
Out of 2 possibilities. I'll guess (1, 4, 7, 4) ---> (4, 0)
That's it. After 5 tries, I won.
</code></pre>
| 0 | 2013-12-22T02:39:33Z | [
"python",
"algorithm"
] |
Python: is os.read() / os.write() on an os.pipe() threadsafe? | 1,185,660 | <p>Consider:</p>
<pre><code>pipe_read, pipe_write = os.pipe()
</code></pre>
<p>Now, I would like to know two things:</p>
<p><strong>(1)</strong> I have two threads. If I guarantee that only one is reading <code>os.read(pipe_read,n)</code> and the other is only writing <code>os.write(pipe_write)</code>, will I have any problem, even if the two threads do it simultaneously? Will I get all data that was written in the correct order? What happens if they do it simultaneously? Is it possible that a single write is read in pieces, like?:</p>
<pre><code>Thread 1: os.write(pipe_write, '1234567')
Thread 2: os.read(pipe_read,big_number) --> '123'
Thread 2: os.read(pipe_read,big_number) --> '4567'
</code></pre>
<p>Or -- again, consider simultaneity -- will a single <code>os.write(some_string)</code> always return entirely by a single <code>os.read(pipe_read, very_big_number)</code>?</p>
<p><strong>(2)</strong> Consider more than one thread writing to the <code>pipe_write</code> end of the pipe using <code>logging.handlers.FileHandler()</code> -- I've read that the logging module is threadsafe. Does this mean that I can do this without losing data? I think I won't be able to control the order of the data in the pipe; but this is not a requirement.
Requirements:</p>
<ul>
<li>all data written by some threads on the write end <strong>must</strong> come out at the read end </li>
<li>a string written by a single <code>logger.info(), logger.error(), ...</code> has to stay in one piece.</li>
</ul>
<p>Are these reqs fulfilled?</p>
<p>Thank you in advance,</p>
<p>Jan-Philip Gehrcke</p>
| 7 | 2009-07-26T21:53:25Z | 1,186,161 | <p><code>os.read</code> and <code>os.write</code> on the two fds returned from <code>os.pipe</code> is threadsafe, but you appear to demand more than that. Sub <code>(1)</code>, yes, there is no "atomicity" guarantee for sinle reads or writes -- the scenario you depict (a single short write ends up producing two reads) is entirely possible. (In general, os.whatever is a thin wrapper on operating system functionality, and it's up to the OS to ensure, or fail to ensure, the kind of functionality you require; in this case, the Posix standard doesn't require the OS to ensure this kind of "atomicity"). You're guaranteed to get all data that was written, and in the correct order, but that's it. A single write of a large piece of data might stall once it's filled the OS-supplied buffer and only proceed once some other thread has read some of the initial data (beware deadlocks, of course!), etc, etc.</p>
<p>Sub <code>(2)</code>, yes, the logging module is threadsafe AND "atomic" in that data produced by a single call to logging.info, logging.warn, logging.error, etc, "stays in one piece" in terms of calls to the underlying handler (however if that handler in turn uses non-atomic means such as os.write, it may still e.g. stall in the kernel until the underlying buffer gets unclogged, etc, etc, as above).</p>
| 8 | 2009-07-27T02:19:07Z | [
"python",
"multithreading",
"thread-safety",
"pipe"
] |
Using a caesarian cipher on a string of text in python? | 1,185,775 | <p>I'm trying to slowly knock out all of the intricacies of python. Basically, I'm looking for some way, in python, to take a string of characters and push them all over by 'x' characters. </p>
<p>For example, inputing abcdefg will give me cdefghi (if x is 2).</p>
| 2 | 2009-07-26T22:47:15Z | 1,185,787 | <p><strong>This solution works for both lowercase and uppercase:</strong></p>
<pre><code>from string import lowercase, uppercase
def caesar(text, key):
result = []
for c in text:
if c in lowercase:
idx = lowercase.index(c)
idx = (idx + key) % 26
result.append(lowercase[idx])
elif c in uppercase:
idx = uppercase.index(c)
idx = (idx + key) % 26
result.append(uppercase[idx])
else:
result.append(c)
return "".join(result)
</code></pre>
<p><strong>Here is a test:</strong></p>
<pre><code>>>> caesar("abcdefg", 2)
'cdefghi'
>>> caesar("z", 1)
'a'
</code></pre>
| 2 | 2009-07-26T22:53:36Z | [
"python",
"encryption"
] |
Using a caesarian cipher on a string of text in python? | 1,185,775 | <p>I'm trying to slowly knock out all of the intricacies of python. Basically, I'm looking for some way, in python, to take a string of characters and push them all over by 'x' characters. </p>
<p>For example, inputing abcdefg will give me cdefghi (if x is 2).</p>
| 2 | 2009-07-26T22:47:15Z | 1,185,808 | <p>I think your best bet is to look at <a href="http://www.tutorialspoint.com/python/string%5Ftranslate.htm">string.translate</a>. You may have to use make_trans to make the mapping you like.</p>
| 5 | 2009-07-26T22:58:16Z | [
"python",
"encryption"
] |
Using a caesarian cipher on a string of text in python? | 1,185,775 | <p>I'm trying to slowly knock out all of the intricacies of python. Basically, I'm looking for some way, in python, to take a string of characters and push them all over by 'x' characters. </p>
<p>For example, inputing abcdefg will give me cdefghi (if x is 2).</p>
| 2 | 2009-07-26T22:47:15Z | 1,185,809 | <p>My first version:</p>
<pre><code>>>> key = 2
>>> msg = "abcdefg"
>>> ''.join( map(lambda c: chr(ord('a') + (ord(c) - ord('a') + key)%26), msg) )
'cdefghi'
>>> msg = "uvwxyz"
>>> ''.join( map(lambda c: chr(ord('a') + (ord(c) - ord('a') + key)%26), msg) )
'wxyzab'
</code></pre>
<p>(Of course it works as expected only if msg is lowercase...)</p>
<p><strong>edit</strong>: I definitely second David Raznick's answer:</p>
<pre><code>>>> import string
>>> alphabet = "abcdefghijklmnopqrstuvwxyz"
>>> key = 2
>>> tr = string.maketrans(alphabet, alphabet[key:] + alphabet[:key])
>>> "abcdefg".translate(tr)
'cdefghi'
</code></pre>
| 7 | 2009-07-26T22:58:39Z | [
"python",
"encryption"
] |
Using a caesarian cipher on a string of text in python? | 1,185,775 | <p>I'm trying to slowly knock out all of the intricacies of python. Basically, I'm looking for some way, in python, to take a string of characters and push them all over by 'x' characters. </p>
<p>For example, inputing abcdefg will give me cdefghi (if x is 2).</p>
| 2 | 2009-07-26T22:47:15Z | 1,185,816 | <p>I would do it this way (for conceptual simplicity):</p>
<pre><code>def encode(s):
l = [ord(i) for i in s]
return ''.join([chr(i + 2) for i in l])
</code></pre>
<p>Point being that you convert the letter to ASCII, add 2 to that code, convert it back, and "cast" it into a string (create a new string object). This also makes no conversions based on "case" (upper vs. lower).</p>
<p>Potential optimizations/research areas:</p>
<ul>
<li>Use of StringIO module for large strings</li>
<li>Apply this to Unicode (not sure how)</li>
</ul>
| 3 | 2009-07-26T23:01:48Z | [
"python",
"encryption"
] |
Using a caesarian cipher on a string of text in python? | 1,185,775 | <p>I'm trying to slowly knock out all of the intricacies of python. Basically, I'm looking for some way, in python, to take a string of characters and push them all over by 'x' characters. </p>
<p>For example, inputing abcdefg will give me cdefghi (if x is 2).</p>
| 2 | 2009-07-26T22:47:15Z | 1,185,820 | <p>Another version. Allows for definition of your own alphabet, and doesn't translate any other characters (such as punctuation). The ugly part here is the loop, which might cause performance problems. I'm not sure about python but appending strings like this is a big no in other languages like Java and C#.</p>
<pre><code>def rotate(data, n):
alphabet = list("abcdefghijklmopqrstuvwxyz")
n = n % len(alphabet)
target = alphabet[n:] + alphabet[:n]
translation = dict(zip(alphabet, target))
result = ""
for c in data:
if translation.has_key(c):
result += translation[c]
else:
result += c
return result
print rotate("foobar", 1)
print rotate("foobar", 2)
print rotate("foobar", -1)
print rotate("foobar", -2)
</code></pre>
<p>Result:</p>
<pre><code>gppcbs
hqqdct
emmazq
dllzyp
</code></pre>
<p>The make_trans() solution suggested by others is the way to go here.</p>
| 1 | 2009-07-26T23:02:46Z | [
"python",
"encryption"
] |
How to associate py extension with python launcher on Mac OS X? | 1,185,817 | <p>Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?</p>
| 4 | 2009-07-26T23:01:51Z | 1,185,827 | <p>Steve, add the following to the top of your python script:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>It must occur as the first line of the file.</p>
<p>Then make the file executable as so:</p>
<pre><code>daves-macbookpro ~: chmod +x foo.py
</code></pre>
<p>Then all you need to do to run this is type </p>
<pre><code>./foo.py
</code></pre>
| 2 | 2009-07-26T23:06:47Z | [
"python",
"osx"
] |
How to associate py extension with python launcher on Mac OS X? | 1,185,817 | <p>Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?</p>
| 4 | 2009-07-26T23:01:51Z | 1,185,893 | <p>The file associations are done with the "Get Info". You select your .PY file, select the File menu; Get Info menu item.</p>
<p>Mid-way down the Get Info page is "Open With".</p>
<p>You can pick the Python Launcher. There's a <strong>Change All..</strong> button that changes the association for all <code>.py</code> files.</p>
| 2 | 2009-07-26T23:37:33Z | [
"python",
"osx"
] |
How to associate py extension with python launcher on Mac OS X? | 1,185,817 | <p>Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?</p>
| 4 | 2009-07-26T23:01:51Z | 1,185,899 | <p>The python.org OS X Python installers include an application called "Python Launcher.app" which does exactly what you want. It gets installed into /Applications /Python n.n/ for n.n > 2.6 or /Applications/MacPython n.n/ for 2.5 and earlier. In its preference panel, you can specify which Python executable to launch; it can be any command-line path, including the Apple-installed one at /usr/bin/python2.5. You will also need to ensure that .py is associated with "Python Launcher"; you can use the Finder's Get Info command to do that as described elsewhere. Be aware, though, that this could be a security risk if downloaded .py scripts are automatically launched by your browser(s). (Note, the Apple-supplied Python in 10.5 does not include "Python Launcher.app").</p>
| 6 | 2009-07-26T23:41:33Z | [
"python",
"osx"
] |
How to associate py extension with python launcher on Mac OS X? | 1,185,817 | <p>Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?</p>
| 4 | 2009-07-26T23:01:51Z | 28,869,258 | <p>The default python installation (atleast on 10.6.8) includes the <code>Python Launcher.app</code> in <code>/System/Library/Frameworks/Python.framework/Resources/</code>, which is aliased to the latest/current version of Python installed on the system. This application launches terminal and sets the right environment to run the script.</p>
| 0 | 2015-03-05T03:02:25Z | [
"python",
"osx"
] |
Parallel SSH in Python | 1,185,855 | <p>I wonder what is the best way to handle parallel SSH connections in python.
I need to open several SSH connections to keep in background and to feed commands in interactive or timed batch way.
Is this possible to do it with the paramiko libraries? It would be nice not to spawn a different SSH process for each connection.</p>
<p>Thanks.</p>
| 3 | 2009-07-26T23:19:27Z | 1,185,871 | <p>You can simply use subprocess.Popen for that purpose, without any problems.</p>
<p>However, you might want to simply install cronjobs on the remote machines. :-)</p>
| 1 | 2009-07-26T23:27:10Z | [
"python",
"ssh",
"parallel-processing"
] |
Parallel SSH in Python | 1,185,855 | <p>I wonder what is the best way to handle parallel SSH connections in python.
I need to open several SSH connections to keep in background and to feed commands in interactive or timed batch way.
Is this possible to do it with the paramiko libraries? It would be nice not to spawn a different SSH process for each connection.</p>
<p>Thanks.</p>
| 3 | 2009-07-26T23:19:27Z | 1,185,880 | <p>Reading the paramiko API docs, it looks like it is possible to open one ssh connection, and multiplex as many ssh tunnels on top of that as are wished. Common ssh clients (openssh) often do things like this automatically behind the scene if there is already a connection open.</p>
| 1 | 2009-07-26T23:30:57Z | [
"python",
"ssh",
"parallel-processing"
] |
Parallel SSH in Python | 1,185,855 | <p>I wonder what is the best way to handle parallel SSH connections in python.
I need to open several SSH connections to keep in background and to feed commands in interactive or timed batch way.
Is this possible to do it with the paramiko libraries? It would be nice not to spawn a different SSH process for each connection.</p>
<p>Thanks.</p>
| 3 | 2009-07-26T23:19:27Z | 1,186,046 | <p>It might be worth checking out what options are available in Twisted. For example, the Twisted.Conch page reports:</p>
<blockquote>
<p><a href="http://twistedmatrix.com/users/z3p/files/conch-talk.html" rel="nofollow">http://twistedmatrix.com/users/z3p/files/conch-talk.html</a></p>
<p>Unlike OpenSSH, the Conch server does not fork a process for each incoming connection. Instead, it uses the Twisted reactor to multiplex the connections. </p>
</blockquote>
| 3 | 2009-07-27T01:14:39Z | [
"python",
"ssh",
"parallel-processing"
] |
Parallel SSH in Python | 1,185,855 | <p>I wonder what is the best way to handle parallel SSH connections in python.
I need to open several SSH connections to keep in background and to feed commands in interactive or timed batch way.
Is this possible to do it with the paramiko libraries? It would be nice not to spawn a different SSH process for each connection.</p>
<p>Thanks.</p>
| 3 | 2009-07-26T23:19:27Z | 1,188,586 | <p>Yes, you can do this with paramiko.</p>
<p>If you're connecting to one server, you can run multiple channels through a single connection. If you're connecting to multiple servers, you can start multiple connections in separate threads. No need to manage multiple processes, although you could substitute the multiprocessing module for the threading module and have the same effect.</p>
<p>I haven't looked into twisted conch in a while, but it looks like it getting updates again, which is nice. I couldn't give you a good feature comparison between the two, but I find paramiko is easier to get going. It takes a little more effort to get into twisted, but it could be well worth it if you're doing other network programming.</p>
| 3 | 2009-07-27T14:45:25Z | [
"python",
"ssh",
"parallel-processing"
] |
Parallel SSH in Python | 1,185,855 | <p>I wonder what is the best way to handle parallel SSH connections in python.
I need to open several SSH connections to keep in background and to feed commands in interactive or timed batch way.
Is this possible to do it with the paramiko libraries? It would be nice not to spawn a different SSH process for each connection.</p>
<p>Thanks.</p>
| 3 | 2009-07-26T23:19:27Z | 1,516,547 | <p>This might not be relevant to your question. But there are tools like pssh, clusterssh etc. that can parallely spawn connections. You can couple Expect with pssh to control them too.</p>
| -1 | 2009-10-04T14:34:34Z | [
"python",
"ssh",
"parallel-processing"
] |
Parallel SSH in Python | 1,185,855 | <p>I wonder what is the best way to handle parallel SSH connections in python.
I need to open several SSH connections to keep in background and to feed commands in interactive or timed batch way.
Is this possible to do it with the paramiko libraries? It would be nice not to spawn a different SSH process for each connection.</p>
<p>Thanks.</p>
| 3 | 2009-07-26T23:19:27Z | 1,604,266 | <p>I've tried clusterssh, and I don't like the multiwindow model. Too confusing in the common case when everything works. </p>
<p>I've tried pssh, and it has a few problems with quotation escaping and password prompting.</p>
<p>The best I've used is <a href="http://packages.debian.org/sid/dsh" rel="nofollow">dsh</a>:</p>
<blockquote>
<pre> Description: dancer's shell, or distributed shell
Executes specified command on a group of computers using remote shell
methods such as rsh or ssh.
.
dsh can parallelise job submission using several algorithms, such as using
fan-out method or opening as much connections as possible, or
using a window of connections at one time.
It also supports "interactive mode" for interactive maintenance of
remote hosts.
.
This tool is handy for administration of PC clusters, and multiple hosts.
</pre>
</blockquote>
<p>Its very flexible in scheduling and topology: you can request something close to a calling tree if need be. But the default is a simple topology of one command node to many leaf nodes.</p>
<p><a href="http://www.netfort.gr.jp/~dancer/software/dsh.html" rel="nofollow">http://www.netfort.gr.jp/~dancer/software/dsh.html</a></p>
| 1 | 2009-10-21T23:45:06Z | [
"python",
"ssh",
"parallel-processing"
] |
How can I execute CGI files from PHP? | 1,185,867 | <p>I'm trying to make a web app that will manage my Mercurial repositories for me.
I want it so that when I tell it to load repository X:</p>
<ul>
<li>Connect to a MySQL server and make sure X exists.</li>
<li>Check if the user is allowed to access the repository.</li>
<li>If above is true, get the location of X from a mysql server.</li>
<li>Run a hgweb cgi script (python) containing the path of the repository.</li>
</ul>
<p>Here is the problem, I want to: take the hgweb script, modify it, and run it.
But I do not want to: take the hgweb script, modify it, write it to a file and redirect there.
I am using Apache to run the httpd process.</p>
| 0 | 2009-07-26T23:24:18Z | 1,185,895 | <p>You can run shell scripts from within PHP. There are various ways to do it, and complications with some hosts not providing the proper permissions, all of which are well-documented on php.net. That said, the simplest way is to simply enclose your command in backticks. So, to unzip a file, I could say:</p>
<pre><code>`unzip /path/to/file`
</code></pre>
<p>SO, if your python script is such that it can be run from a command-line environment (or you could modify it so to run), this would seem to be the preferred method.</p>
| 2 | 2009-07-26T23:39:31Z | [
"php",
"python",
"mercurial",
"cgi"
] |
How can I execute CGI files from PHP? | 1,185,867 | <p>I'm trying to make a web app that will manage my Mercurial repositories for me.
I want it so that when I tell it to load repository X:</p>
<ul>
<li>Connect to a MySQL server and make sure X exists.</li>
<li>Check if the user is allowed to access the repository.</li>
<li>If above is true, get the location of X from a mysql server.</li>
<li>Run a hgweb cgi script (python) containing the path of the repository.</li>
</ul>
<p>Here is the problem, I want to: take the hgweb script, modify it, and run it.
But I do not want to: take the hgweb script, modify it, write it to a file and redirect there.
I am using Apache to run the httpd process.</p>
| 0 | 2009-07-26T23:24:18Z | 1,185,909 | <p>As far as you question, no, you're not likely to get php to execute a modified script without writing it somewhere, whether that's a file on the disk, a virtual file mapped to ram, or something similar.</p>
<p>It sounds like you might be trying to pound a railroad spike with a twig. If you're to the point where you're filtering access based on user permissions stored in MySQL, have you looked at existing HG solutions to make sure there isn't something more applicable than hgweb? It's really built for doing exactly one thing well, and this is a fair bit beyond it's normal realm.</p>
<p>I might suggest looking into apache's native authentication as a more convenient method for controlling access to repositories, then just serve the repo without modifying the script.</p>
| 0 | 2009-07-26T23:45:22Z | [
"php",
"python",
"mercurial",
"cgi"
] |
How can I execute CGI files from PHP? | 1,185,867 | <p>I'm trying to make a web app that will manage my Mercurial repositories for me.
I want it so that when I tell it to load repository X:</p>
<ul>
<li>Connect to a MySQL server and make sure X exists.</li>
<li>Check if the user is allowed to access the repository.</li>
<li>If above is true, get the location of X from a mysql server.</li>
<li>Run a hgweb cgi script (python) containing the path of the repository.</li>
</ul>
<p>Here is the problem, I want to: take the hgweb script, modify it, and run it.
But I do not want to: take the hgweb script, modify it, write it to a file and redirect there.
I am using Apache to run the httpd process.</p>
| 0 | 2009-07-26T23:24:18Z | 1,185,918 | <p>Ryan Ballantyne has the right answer posted (I upvoted it). The backtick operator is the way to execute a shell script.</p>
<p>The simplest solution is probably to modify the hgweb script so that it doesn't "contain" the path to the repository, per se. Instead, pass it as a command-line argument. This means you don't have to worry about modifying and writing the hgweb script anywhere. All you'd have to do is:</p>
<pre><code>//do stuff to get location of repository from MySQL into variable $x
//run shell script
$res = `python hgweb.py $x`;
</code></pre>
| 2 | 2009-07-26T23:52:09Z | [
"php",
"python",
"mercurial",
"cgi"
] |
Can I use C++ features while extending Python? | 1,185,878 | <p>The Python manual says that you can create modules for Python in both C and C++. Can you take advantage of things like classes and templates when using C++? Wouldn't it create incompatibilities with the rest of the libraries and with the interpreter?</p>
| 5 | 2009-07-26T23:30:23Z | 1,185,907 | <p>It doesn't matter whether your implementation of the hook functions is implemented in C or in C++. In fact, I've already seen some Python extensions which make active use of C++ templates and even the Boost library. <b>No problem.</b> :-)</p>
| 8 | 2009-07-26T23:44:31Z | [
"c++",
"python",
"c",
"python-c-api",
"python-c-extension"
] |
Can I use C++ features while extending Python? | 1,185,878 | <p>The Python manual says that you can create modules for Python in both C and C++. Can you take advantage of things like classes and templates when using C++? Wouldn't it create incompatibilities with the rest of the libraries and with the interpreter?</p>
| 5 | 2009-07-26T23:30:23Z | 1,185,911 | <p>What you're interested in is a program called <a href="http://www.swig.org" rel="nofollow">SWIG</a>. It will generate Python wrappers and interfaces for C++ code. I use it with templates, inheritance, namespaces, etc. and it works well.</p>
| 2 | 2009-07-26T23:46:42Z | [
"c++",
"python",
"c",
"python-c-api",
"python-c-extension"
] |
Can I use C++ features while extending Python? | 1,185,878 | <p>The Python manual says that you can create modules for Python in both C and C++. Can you take advantage of things like classes and templates when using C++? Wouldn't it create incompatibilities with the rest of the libraries and with the interpreter?</p>
| 5 | 2009-07-26T23:30:23Z | 1,185,954 | <p>The boost folks have a nice automated way to do the wrapping of C++ code for use by python.</p>
<p>It is called: Boost.Python</p>
<p>It deals with some of the constructs of C++ better than SWIG, particularly template metaprogramming.</p>
| 3 | 2009-07-27T00:22:12Z | [
"c++",
"python",
"c",
"python-c-api",
"python-c-extension"
] |
Can I use C++ features while extending Python? | 1,185,878 | <p>The Python manual says that you can create modules for Python in both C and C++. Can you take advantage of things like classes and templates when using C++? Wouldn't it create incompatibilities with the rest of the libraries and with the interpreter?</p>
| 5 | 2009-07-26T23:30:23Z | 1,185,957 | <p>You should be able to use all of the features of the C++ language. The <a href="http://docs.python.org/extending/extending.html" rel="nofollow">Extending Python Documentation (2.6.2)</a> says that you may use C++, but mentions the followings caveats:</p>
<blockquote>
<p>It is possible to write extension
modules in C++. Some restrictions
apply. If the main program (the Python
interpreter) is compiled and linked by
the C compiler, global or static
objects with constructors cannot be
used. This is not a problem if the
main program is linked by the C++
compiler. Functions that will be
called by the Python interpreter (in
particular, module initialization
functions) have to be declared using
extern "C". It is unnecessary to
enclose the Python header files in
extern "C" {...} â they use this form
already if the symbol __cplusplus is
defined (all recent C++ compilers
define this symbol).</p>
</blockquote>
<p>The first restriction, "global or static objects with constructors cannot be used", has to do with the way most C++ compiler initialize objects with this type of storage duration. For example, consider the following code:</p>
<pre><code>class Foo { Foo() { } };
static Foo f;
int main(int argc, char** argv) {}
</code></pre>
<p>The compiler has to emit special code so that the 'Foo' constructor gets invoked for 'f' before main gets executed. If you have objects with static storage duration in your Python extension <strong>and</strong> the Python interpreter is not compiled and linked for C++, then this special initialization code will not be created.</p>
<p>The second restriction, "Functions that will be called by the Python interpreter (in particular, module initialization functions) have to be declared using extern "C"", has to do with C++ name mangling. Most C++ compilers mangle their names so that they can use the same linkers provided for C toolchains. For example say you had:</p>
<pre><code>void a_function_python_calls(void* foo);
</code></pre>
<p>the C++ compiler may convert references to the name 'a_function_python_calls' to something like 'a_function_python_calls@1vga'. In which case you may get an unresolved external when trying to link with the Python library.</p>
| 1 | 2009-07-27T00:23:37Z | [
"c++",
"python",
"c",
"python-c-api",
"python-c-extension"
] |
Read content of RAR file into memory in Python | 1,185,959 | <p>I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible.</p>
<p>That all said, I'd prefer a solution that's cross platform (Windows/Linux) if possible, but Linux is a must. Just as importantly, if you're going to point out a library to handle this for me, please understand that it must be free (as in beer) or OSS.</p>
| 6 | 2009-07-27T00:25:14Z | 1,186,011 | <p>See the rarfile module:</p>
<ul>
<li><strike>http://grue.l-t.ee/~marko/src/rarfile/README.html</strike></li>
<li><a href="http://pypi.python.org/pypi/rarfile/" rel="nofollow">http://pypi.python.org/pypi/rarfile/</a></li>
<li><a href="https://github.com/markokr/rarfile" rel="nofollow">https://github.com/markokr/rarfile</a></li>
</ul>
| 7 | 2009-07-27T00:54:58Z | [
"python",
"linux",
"stream",
"rar"
] |
Read content of RAR file into memory in Python | 1,185,959 | <p>I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible.</p>
<p>That all said, I'd prefer a solution that's cross platform (Windows/Linux) if possible, but Linux is a must. Just as importantly, if you're going to point out a library to handle this for me, please understand that it must be free (as in beer) or OSS.</p>
| 6 | 2009-07-27T00:25:14Z | 1,186,012 | <p>Look at the Python "struct" module. You can then interpret the RAR file format directly in your Python program, allowing you to retrieve the content inside the RAR without depending on external software to do it for you.</p>
<p>EDIT: This is of course vanilla Python - there are alternatives which use third-party modules (as already posted).</p>
<p>EDIT 2: According to <a href="http://en.wikipedia.org/wiki/RAR" rel="nofollow">Wikipedia's article</a> my answer would require you to have permission from the author.</p>
| 0 | 2009-07-27T00:55:33Z | [
"python",
"linux",
"stream",
"rar"
] |
Read content of RAR file into memory in Python | 1,185,959 | <p>I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible.</p>
<p>That all said, I'd prefer a solution that's cross platform (Windows/Linux) if possible, but Linux is a must. Just as importantly, if you're going to point out a library to handle this for me, please understand that it must be free (as in beer) or OSS.</p>
| 6 | 2009-07-27T00:25:14Z | 1,186,014 | <p>The <a href="http://packages.debian.org/source/lenny/p7zip" rel="nofollow">free 7zip library</a> is also able to handle RAR files.</p>
| 0 | 2009-07-27T00:58:02Z | [
"python",
"linux",
"stream",
"rar"
] |
Read content of RAR file into memory in Python | 1,185,959 | <p>I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible.</p>
<p>That all said, I'd prefer a solution that's cross platform (Windows/Linux) if possible, but Linux is a must. Just as importantly, if you're going to point out a library to handle this for me, please understand that it must be free (as in beer) or OSS.</p>
| 6 | 2009-07-27T00:25:14Z | 1,186,041 | <p>The real answer is that there isn't a library, and you can't make one. You can use rarfile, or you can use 7zip unRAR (which is less free than 7zip, but still free as in beer), but both approaches require an external executable. The license for RAR basically requires this, as while you can get source code for unRAR, you cannot modify it in any way, and turning it into a library would constitute illegal modification.</p>
<p>Also, solid RAR archives (the best compressed) can't be randomly accessed, so you have to unarchive the entire thing anyhow. WinRAR presents a UI that seems to avoid this, but really it's just unpacking and repacking the archive in the background.</p>
| 4 | 2009-07-27T01:11:12Z | [
"python",
"linux",
"stream",
"rar"
] |
Read content of RAR file into memory in Python | 1,185,959 | <p>I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible.</p>
<p>That all said, I'd prefer a solution that's cross platform (Windows/Linux) if possible, but Linux is a must. Just as importantly, if you're going to point out a library to handle this for me, please understand that it must be free (as in beer) or OSS.</p>
| 6 | 2009-07-27T00:25:14Z | 1,186,099 | <p>RAR is a proprietary format; I don't think there are any public specs, so third-party tool and library support is poor to non-existant.</p>
<p>You're much better off using ZIP; it's completely free, has an accurate public spec, the compression library is available everywhere (zlib is one of the most widely-deployed libraries in the world), and it's very easy to code for.</p>
<p><a href="http://docs.python.org/library/zipfile.html" rel="nofollow">http://docs.python.org/library/zipfile.html</a></p>
| 1 | 2009-07-27T01:43:50Z | [
"python",
"linux",
"stream",
"rar"
] |
Read content of RAR file into memory in Python | 1,185,959 | <p>I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible.</p>
<p>That all said, I'd prefer a solution that's cross platform (Windows/Linux) if possible, but Linux is a must. Just as importantly, if you're going to point out a library to handle this for me, please understand that it must be free (as in beer) or OSS.</p>
| 6 | 2009-07-27T00:25:14Z | 3,154,780 | <p>The <a href="http://code.google.com/p/py-unrar2/" rel="nofollow">pyUnRAR2</a> library can extract files from RAR archives to memory (and disk if you want). It's available under the MIT license and simply wraps UnRAR.dll on Windows and unrar on Unix. Click "QuickTutorial" for usage examples.</p>
<p>On Windows, it is able to extract to memory (and not disk) with the (included) UnRAR.dll by setting a callback using RARSetCallback() and then calling RARProcessFile() with the RAR_TEST option instead of the RAR_EXTRACT option to avoid extracting any files to disk. The callback then watches for UCM_PROCESSDATA events to read the data. From the documentation for UCM_PROCESSDATA events: "Process unpacked data. It may be used to read a file while it is being extracted or tested without actual extracting file to disk."</p>
<p>On Unix, unrar can simply print the file to stdout, so the library just reads from a pipe connected to unrar's stdout. The unrar binary you need is the one that has the "p" for "Print file to stdout" command. Use "apt-get install unrar" to install it on Ubuntu.</p>
| 1 | 2010-07-01T02:47:34Z | [
"python",
"linux",
"stream",
"rar"
] |
Read content of RAR file into memory in Python | 1,185,959 | <p>I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible.</p>
<p>That all said, I'd prefer a solution that's cross platform (Windows/Linux) if possible, but Linux is a must. Just as importantly, if you're going to point out a library to handle this for me, please understand that it must be free (as in beer) or OSS.</p>
| 6 | 2009-07-27T00:25:14Z | 4,436,131 | <p>It seems like the limitation that rarsoft imposes on derivative works is that you may not use the unrar source code to create a variation of the RAR <em>COMPRESSION</em> algorithm. From the context, it would appear that it's specifically allowing folks to use his code (modified or not) to decompress files, but you cannot use them if you intend to write your own compression code. Here is a direct quote from the license.txt file I just downloaded:</p>
<ol>
<li>The UnRAR sources may be used in any software to handle RAR
archives without limitations free of charge, but cannot be used
to re-create the RAR compression algorithm, which is proprietary.
Distribution of modified UnRAR sources in separate form or as a
part of other software is permitted, provided that it is clearly
stated in the documentation and source comments that the code may
not be used to develop a RAR (WinRAR) compatible archiver.</li>
</ol>
<p>Seeing as everyone seemed to just want something that would allow them to write a comic viewer capable of handling reading images from CBR (rar) files, I don't see why people think there's anything keeping them from using the provided source code.</p>
| 2 | 2010-12-14T05:19:23Z | [
"python",
"linux",
"stream",
"rar"
] |
Are there any examples on python-purple floating around? | 1,186,062 | <p>I want to learn it but I have <strong>no</strong> idea where to start. Everything out there suggests reading the <code>libpurple</code> source but I don't think I understand enough <code>c</code> to really get a grasp of it. </p>
| 8 | 2009-07-27T01:29:29Z | 1,186,138 | <p>Not sure how much help this will be but based on information from <a href="http://developer.pidgin.im/wiki/PythonHowTo" rel="nofollow">here</a>, it seems like you just install python-purple and import and call the functions as normal Python functions.</p>
| 1 | 2009-07-27T02:07:09Z | [
"python",
"libpurple"
] |
Are there any examples on python-purple floating around? | 1,186,062 | <p>I want to learn it but I have <strong>no</strong> idea where to start. Everything out there suggests reading the <code>libpurple</code> source but I don't think I understand enough <code>c</code> to really get a grasp of it. </p>
| 8 | 2009-07-27T01:29:29Z | 1,186,141 | <p>There isn't much about it yet... the <a href="http://brunoabinader.blogspot.com/2009/04/introducing-python-purple.html" rel="nofollow">intro</a>, the <a href="http://developer.pidgin.im/wiki/PythonHowTo" rel="nofollow">howto</a>, and the <a href="https://git.maemo.org/projects/python-purple/?p=python-purple;a=tree" rel="nofollow">sources</a> (here browsing them online but of course you can git clone them) are about it. In particular, the tiny example client you can get from <a href="https://git.maemo.org/projects/python-purple/?p=python-purple;a=blob%5Fplain;f=nullclient.py;hb=HEAD" rel="nofollow">here</a> does have some miniscule example of use of purple's facilities (definitely not enough, but maybe it can get you started with the help of some 'dir', 'help' and the like...?)</p>
| 1 | 2009-07-27T02:07:52Z | [
"python",
"libpurple"
] |
Are there any examples on python-purple floating around? | 1,186,062 | <p>I want to learn it but I have <strong>no</strong> idea where to start. Everything out there suggests reading the <code>libpurple</code> source but I don't think I understand enough <code>c</code> to really get a grasp of it. </p>
| 8 | 2009-07-27T01:29:29Z | 1,237,039 | <p>Can't help you with a concrete example as I decided to use something else. However, one of the first things I wanted to do after I cloned the repo was remove the ecore dependency. Here's a patch submitted to the mailing list to do just that: <a href="https://garage.maemo.org/pipermail/python-purple-devel/2009-March/000000.html" rel="nofollow">https://garage.maemo.org/pipermail/python-purple-devel/2009-March/000000.html</a></p>
<p>Incidentally, if you're looking for AIM take a look at twisted.words. For Yahoo, trying getting the source for curphoo or zinc (both are console YMSG clients). For GTalk/Jabber, I've had good experiences with xmpppy.</p>
| 0 | 2009-08-06T04:54:21Z | [
"python",
"libpurple"
] |
Nested Set Model and SQLAlchemy -- Adding New Nodes | 1,186,086 | <p>How should new nodes be added with SQLAlchemy to a tree implemented using the <a href="http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/" rel="nofollow">Nested Set Model</a>?</p>
<pre><code>class Category(Base):
__tablename__ = 'categories'
id = Column(Integer, primary_key=True)
name = Column(String(128), nullable=False)
lft = Column(Integer, nullable=False, unique=True)
rgt = Column(Integer, nullable=False, unique=True)
</code></pre>
<p>I would need a trigger on the table to assign <code>lft</code> and <code>rgt</code> for the new node and update all other affected nodes, but what is the best way to define the position of the node? I can pass the <code>parent_id</code> of the new node to the constructor, but how would I then communicate the <code>parent_id</code> to the trigger?</p>
| 2 | 2009-07-27T01:38:20Z | 1,194,549 | <p>You might want to look at the <a href="http://docs.sqlalchemy.org/en/latest/_modules/examples/nested_sets/nested_sets.html" rel="nofollow">nested sets example</a> in the examples directory of SQLAlchemy. This implements the model at the Python level.</p>
<p>Doing it at the database level with triggers would need some way to communicate the desired parent, either as an extra column or as a stored procedure.</p>
| 5 | 2009-07-28T14:36:57Z | [
"python",
"sql",
"tree",
"sqlalchemy",
"nested-sets"
] |
Appengine and GWT - feeding the python some java | 1,186,155 | <p>I realize this is a dated question since appengine now comes in java, but I have a python appengine app that I want to access via GWT. Python is just better for server-side text processing (using pyparsing of course!). I have tried to interpret GWT's client-side RPC and that is convoluted since there is no python counterpart (python-gwt-rpc is out of date). I just tried using JSON and RequestBuilder, but that fails when using SSL. Does anyone have a good solution for putting a GWT frontend on a python appengine app?</p>
| 3 | 2009-07-27T02:16:15Z | 1,186,322 | <p>The only alternative (if you can call it that) that I'm familiar with is <a href="http://pyjs.org/" rel="nofollow">Pyjamas</a>. Obviously, this is more of a GWT replacement than a GWT-RPC replacement. Beyond that, I think you would be stuck with writing your own communications layer using some sort of REST-type protocol.</p>
| 1 | 2009-07-27T03:45:09Z | [
"java",
"python",
"google-app-engine",
"gwt"
] |
Appengine and GWT - feeding the python some java | 1,186,155 | <p>I realize this is a dated question since appengine now comes in java, but I have a python appengine app that I want to access via GWT. Python is just better for server-side text processing (using pyparsing of course!). I have tried to interpret GWT's client-side RPC and that is convoluted since there is no python counterpart (python-gwt-rpc is out of date). I just tried using JSON and RequestBuilder, but that fails when using SSL. Does anyone have a good solution for putting a GWT frontend on a python appengine app?</p>
| 3 | 2009-07-27T02:16:15Z | 1,348,919 | <p>You can maybe have a look at the GWT JSON RPC <a href="http://code.google.com/webtoolkit/examples/jsonrpc/" rel="nofollow">example</a>.</p>
<p>If that fails, there are always several XML parser implementations in Python AND Java :)</p>
| 0 | 2009-08-28T19:33:10Z | [
"java",
"python",
"google-app-engine",
"gwt"
] |
Appengine and GWT - feeding the python some java | 1,186,155 | <p>I realize this is a dated question since appengine now comes in java, but I have a python appengine app that I want to access via GWT. Python is just better for server-side text processing (using pyparsing of course!). I have tried to interpret GWT's client-side RPC and that is convoluted since there is no python counterpart (python-gwt-rpc is out of date). I just tried using JSON and RequestBuilder, but that fails when using SSL. Does anyone have a good solution for putting a GWT frontend on a python appengine app?</p>
| 3 | 2009-07-27T02:16:15Z | 1,391,971 | <p>I agree with your evaluation of Python's text processing and GWT's quality. Have you considered using Jython? Googling "pyparsing jython" gives some mixed reviews, but it seems there has been some success with recent versions of Jython.</p>
| 0 | 2009-09-08T04:32:08Z | [
"java",
"python",
"google-app-engine",
"gwt"
] |
Appengine and GWT - feeding the python some java | 1,186,155 | <p>I realize this is a dated question since appengine now comes in java, but I have a python appengine app that I want to access via GWT. Python is just better for server-side text processing (using pyparsing of course!). I have tried to interpret GWT's client-side RPC and that is convoluted since there is no python counterpart (python-gwt-rpc is out of date). I just tried using JSON and RequestBuilder, but that fails when using SSL. Does anyone have a good solution for putting a GWT frontend on a python appengine app?</p>
| 3 | 2009-07-27T02:16:15Z | 3,297,948 | <p>I know I am late to this question...</p>
<p>Have you seen this project?</p>
<p><a href="http://code.google.com/p/python-gwt-rpc/" rel="nofollow">http://code.google.com/p/python-gwt-rpc/</a></p>
<p>It might be useful as a starting point. </p>
| 0 | 2010-07-21T09:41:41Z | [
"java",
"python",
"google-app-engine",
"gwt"
] |
Python: update a list of tuples... fastest method | 1,186,501 | <p>This question is in relation to another question asked here:
<a href="http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python">Sorting 1M records</a></p>
<p>I have since figured out the problem I was having with sorting. I was sorting items from a dictionary into a list every time I updated the data. I have since realized that a lot of the power of Python's sort resides in the fact that it sorts data more quickly that is already partially sorted. </p>
<p>So, here is the question. Suppose I have the following as a sample set:</p>
<pre><code>self.sorted_records = [(1, 1234567890), (20, 1245678903),
(40, 1256789034), (70, 1278903456)]
</code></pre>
<p><code>t[1]</code> of each tuple in the list is a unique id. Now I want to update this list with the follwoing:</p>
<pre><code>updated_records = {1245678903:45, 1278903456:76}
</code></pre>
<p>What is the fastest way for me to do so ending up with </p>
<pre><code>self.sorted_records = [(1, 1234567890), (45, 1245678903),
(40, 1256789034), (76, 1278903456)]
</code></pre>
<p>Currently I am doing something like this:</p>
<pre><code>updated_keys = updated_records.keys()
for i, record in enumerate(self.sorted_data):
if record[1] in updated_keys:
updated_keys.remove(record[1])
self.sorted_data[i] = (updated_records[record[1]], record[1])
</code></pre>
<p>But I am sure there is a faster, more elegant solution out there.</p>
<p>Any help?</p>
<p><strong>* edit <em></strong>
It turns out I used bad exaples for the ids since they end up in sorted order when I do my update. I am actually interested in t[0] being in sorted order. After I do the update I was intending on resorting with the updated data, but it looks like bisect might be the ticket to insert in sorted order.
<strong></em> end edit *</strong></p>
| 1 | 2009-07-27T04:58:42Z | 1,186,518 | <p>You're scanning through all n records. You could instead do a binary search, which would be O(log(n)) instead of O(n). You can use the <a href="http://docs.python.org/library/bisect.html" rel="nofollow"><code>bisect</code></a> module to do this.</p>
| 2 | 2009-07-27T05:07:28Z | [
"python"
] |
Python: update a list of tuples... fastest method | 1,186,501 | <p>This question is in relation to another question asked here:
<a href="http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python">Sorting 1M records</a></p>
<p>I have since figured out the problem I was having with sorting. I was sorting items from a dictionary into a list every time I updated the data. I have since realized that a lot of the power of Python's sort resides in the fact that it sorts data more quickly that is already partially sorted. </p>
<p>So, here is the question. Suppose I have the following as a sample set:</p>
<pre><code>self.sorted_records = [(1, 1234567890), (20, 1245678903),
(40, 1256789034), (70, 1278903456)]
</code></pre>
<p><code>t[1]</code> of each tuple in the list is a unique id. Now I want to update this list with the follwoing:</p>
<pre><code>updated_records = {1245678903:45, 1278903456:76}
</code></pre>
<p>What is the fastest way for me to do so ending up with </p>
<pre><code>self.sorted_records = [(1, 1234567890), (45, 1245678903),
(40, 1256789034), (76, 1278903456)]
</code></pre>
<p>Currently I am doing something like this:</p>
<pre><code>updated_keys = updated_records.keys()
for i, record in enumerate(self.sorted_data):
if record[1] in updated_keys:
updated_keys.remove(record[1])
self.sorted_data[i] = (updated_records[record[1]], record[1])
</code></pre>
<p>But I am sure there is a faster, more elegant solution out there.</p>
<p>Any help?</p>
<p><strong>* edit <em></strong>
It turns out I used bad exaples for the ids since they end up in sorted order when I do my update. I am actually interested in t[0] being in sorted order. After I do the update I was intending on resorting with the updated data, but it looks like bisect might be the ticket to insert in sorted order.
<strong></em> end edit *</strong></p>
| 1 | 2009-07-27T04:58:42Z | 1,186,526 | <p>Since apparently you don't care about the ending value of <code>self.sorted_records</code> actually <em>being</em> sorted (you have values in order 1, 45, 20, 76 -- that's NOT sorted!-), AND you only appear to care about IDs in <code>updated_records</code> that are also in <code>self.sorted_data</code>, a listcomp (with side effects if you want to change the updated_record on the fly) would serve you well, i.e.:</p>
<pre><code>self.sorted_data = [(updated_records.pop(recid, value), recid)
for (value, recid) in self.sorted_data]
</code></pre>
<p>the <code>.pop</code> call removes from <code>updated_records</code> the keys (and corresponding values) that are ending up in the new <code>self.sorted_data</code> (and the "previous value for that <code>recid</code>", <code>value</code>, is supplied as the 2nd argument to pop to ensure no change where a recid is NOT in <code>updated_record</code>); this leaves in <code>updated_record</code> the "new" stuff so you can e.g append it to <code>self.sorted_data</code> before re-sorting, i.e I suspect you want to continue with something like</p>
<pre><code>self.sorted_data.extend(value, recid
for recid, value in updated_records.iteritems())
self.sorted_data.sort()
</code></pre>
<p>though this part DOES go beyond the question you're actually asking (and I'm giving it only because I've seen your <em>previous</em> questions;-).</p>
| 1 | 2009-07-27T05:11:33Z | [
"python"
] |
Python: update a list of tuples... fastest method | 1,186,501 | <p>This question is in relation to another question asked here:
<a href="http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python">Sorting 1M records</a></p>
<p>I have since figured out the problem I was having with sorting. I was sorting items from a dictionary into a list every time I updated the data. I have since realized that a lot of the power of Python's sort resides in the fact that it sorts data more quickly that is already partially sorted. </p>
<p>So, here is the question. Suppose I have the following as a sample set:</p>
<pre><code>self.sorted_records = [(1, 1234567890), (20, 1245678903),
(40, 1256789034), (70, 1278903456)]
</code></pre>
<p><code>t[1]</code> of each tuple in the list is a unique id. Now I want to update this list with the follwoing:</p>
<pre><code>updated_records = {1245678903:45, 1278903456:76}
</code></pre>
<p>What is the fastest way for me to do so ending up with </p>
<pre><code>self.sorted_records = [(1, 1234567890), (45, 1245678903),
(40, 1256789034), (76, 1278903456)]
</code></pre>
<p>Currently I am doing something like this:</p>
<pre><code>updated_keys = updated_records.keys()
for i, record in enumerate(self.sorted_data):
if record[1] in updated_keys:
updated_keys.remove(record[1])
self.sorted_data[i] = (updated_records[record[1]], record[1])
</code></pre>
<p>But I am sure there is a faster, more elegant solution out there.</p>
<p>Any help?</p>
<p><strong>* edit <em></strong>
It turns out I used bad exaples for the ids since they end up in sorted order when I do my update. I am actually interested in t[0] being in sorted order. After I do the update I was intending on resorting with the updated data, but it looks like bisect might be the ticket to insert in sorted order.
<strong></em> end edit *</strong></p>
| 1 | 2009-07-27T04:58:42Z | 1,186,529 | <p>Since you want to replace by dictionary key, but have the array sorted by dictionary value, you definitely need a linear search for the key. In that sense, your algorithm is the best you can hope for.</p>
<p>If you would preserve the old dictionary value, then you could use a binary search for the value, and then locate the key in the proximity of where the binary search lead you.</p>
| 0 | 2009-07-27T05:13:55Z | [
"python"
] |
Python: update a list of tuples... fastest method | 1,186,501 | <p>This question is in relation to another question asked here:
<a href="http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python">Sorting 1M records</a></p>
<p>I have since figured out the problem I was having with sorting. I was sorting items from a dictionary into a list every time I updated the data. I have since realized that a lot of the power of Python's sort resides in the fact that it sorts data more quickly that is already partially sorted. </p>
<p>So, here is the question. Suppose I have the following as a sample set:</p>
<pre><code>self.sorted_records = [(1, 1234567890), (20, 1245678903),
(40, 1256789034), (70, 1278903456)]
</code></pre>
<p><code>t[1]</code> of each tuple in the list is a unique id. Now I want to update this list with the follwoing:</p>
<pre><code>updated_records = {1245678903:45, 1278903456:76}
</code></pre>
<p>What is the fastest way for me to do so ending up with </p>
<pre><code>self.sorted_records = [(1, 1234567890), (45, 1245678903),
(40, 1256789034), (76, 1278903456)]
</code></pre>
<p>Currently I am doing something like this:</p>
<pre><code>updated_keys = updated_records.keys()
for i, record in enumerate(self.sorted_data):
if record[1] in updated_keys:
updated_keys.remove(record[1])
self.sorted_data[i] = (updated_records[record[1]], record[1])
</code></pre>
<p>But I am sure there is a faster, more elegant solution out there.</p>
<p>Any help?</p>
<p><strong>* edit <em></strong>
It turns out I used bad exaples for the ids since they end up in sorted order when I do my update. I am actually interested in t[0] being in sorted order. After I do the update I was intending on resorting with the updated data, but it looks like bisect might be the ticket to insert in sorted order.
<strong></em> end edit *</strong></p>
| 1 | 2009-07-27T04:58:42Z | 1,188,064 | <p>You'd probably be best served by some form of tree here (preserving sorted order while allowing O(log n) replacements.) There is no builtin balanaced tree type, but you can find many third party examples. Alternatively, you could either:</p>
<ol>
<li><p>Use a binary search to find the node. The bisect module will do this, but it compares based on the normal python comparison order, whereas you seem to be sorted based on the second element of each tuple. You could reverse this, or just write your own binary search (or simply take the code from bisect_left and modify it)</p></li>
<li><p>Use both a dict <strong>and</strong> a list. The list contains the sorted <strong>keys</strong> only. You can wrap the dict class easily enough to ensure this is kept in sync. This allows you fast dict updating while maintaining sort order of the keys. This should prevent your problem of losing sort performance due to constant conversion between dict/list. </p></li>
</ol>
<p>Here's a quick implementation of such a thing:</p>
<pre><code>import bisect
class SortedDict(dict):
"""Dictionary which is iterable in sorted order.
O(n) sorted iteration
O(1) lookup
O(log n) replacement ( but O(n) insertion or new items)
"""
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self._keys = sorted(dict.iterkeys(self))
def __setitem__(self, key, val):
if key not in self:
# New key - need to add to list of keys.
pos = bisect.bisect_left(self._keys, key)
self._keys.insert(pos, key)
dict.__setitem__(self, key, val)
def __delitem__(self, key):
if key in self:
pos = bisect.bisect_left(self._keys, key)
del self._keys[pos]
dict.__delitem__(self, key)
def __iter__(self):
for k in self._keys: yield k
iterkeys = __iter__
def iteritems(self):
for k in self._keys: yield (k, self[k])
def itervalues(self):
for k in self._keys: yield self[k]
def update(self, other):
dict.update(self, other)
self._keys = sorted(dict.iterkeys(self)) # Rebuild (faster if lots of changes made - may be slower if only minor changes to large dict)
def keys(self): return list(self.iterkeys())
def values(self): return list(self.itervalues())
def items(self): return list(self.iteritems())
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, ', '.join("%s=%r" % (k, self[k]) for k in self))
</code></pre>
| 1 | 2009-07-27T13:04:32Z | [
"python"
] |
Customizing modelformset fields in Django | 1,186,753 | <p>I'd like to use the following form class in a modelformset. It takes a <em>maps</em> parameter and customizes the form fields accordingly.</p>
<pre><code>class MyModelForm(forms.ModelForm):
def __init__(self, maps, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
#customize fields here
class Meta:
model = MyModel
</code></pre>
<p>My question is, how do I use this form in a modelformset? When I pass it using the <em>form</em> parameter like below, I get an exception.</p>
<pre><code>MyFormSet = modelformset_factory(MyModel, form=MyModelForm(maps))
</code></pre>
<p>I suspect it wants the form class only, if so how do I pass the <em>maps</em> parameter to the form?</p>
| 0 | 2009-07-27T06:41:55Z | 1,186,772 | <p>Keep in mind that Django uses class <em>definition</em> as a sort of DSL to define various things. As such, instantiating at places where it expects the class object will break things.</p>
<p>One approach is to create your own form factory. Something like:</p>
<pre><code> def mymodelform_factory(maps):
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
#use maps to customize form delcaration here
class Meta:
model = myModel
return MyModelForm
</code></pre>
<p>Then you can do:</p>
<pre><code> MyFormSet = modelformset_factory(MyModel, form=mymodelform_factory(maps))
</code></pre>
| 2 | 2009-07-27T06:47:28Z | [
"python",
"django"
] |
What is the best way to call a Python script from another Python script? | 1,186,789 | <p>I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.</p>
<p>For example:</p>
<h3>File test1.py</h3>
<pre><code>print "I am a test"
print "see! I do nothing productive."
</code></pre>
<h3>File service.py</h3>
<pre><code># Lots of stuff here
test1.py # do whatever is in test1.py
</code></pre>
<p>I'm aware of one method which is opening the file, reading the contents, and basically eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.</p>
| 136 | 2009-07-27T06:52:48Z | 1,186,818 | <p>This is possible in Python 2 using</p>
<pre><code>execfile("test2.py")
</code></pre>
<p>See the <a href="https://docs.python.org/2/library/functions.html#execfile" rel="nofollow">documentation</a> for the handling of namespaces, if important in your case.</p>
<p>However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean.</p>
| 78 | 2009-07-27T07:03:19Z | [
"python",
"eval"
] |
What is the best way to call a Python script from another Python script? | 1,186,789 | <p>I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.</p>
<p>For example:</p>
<h3>File test1.py</h3>
<pre><code>print "I am a test"
print "see! I do nothing productive."
</code></pre>
<h3>File service.py</h3>
<pre><code># Lots of stuff here
test1.py # do whatever is in test1.py
</code></pre>
<p>I'm aware of one method which is opening the file, reading the contents, and basically eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.</p>
| 136 | 2009-07-27T06:52:48Z | 1,186,820 | <p>Why not just import test1? every python script is a module. Better way would be to have function e.g. main/run in test1.py , import test1 and run test1.main() or you can execute test1.py as a subprocess.</p>
| 1 | 2009-07-27T07:04:07Z | [
"python",
"eval"
] |
What is the best way to call a Python script from another Python script? | 1,186,789 | <p>I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.</p>
<p>For example:</p>
<h3>File test1.py</h3>
<pre><code>print "I am a test"
print "see! I do nothing productive."
</code></pre>
<h3>File service.py</h3>
<pre><code># Lots of stuff here
test1.py # do whatever is in test1.py
</code></pre>
<p>I'm aware of one method which is opening the file, reading the contents, and basically eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.</p>
| 136 | 2009-07-27T06:52:48Z | 1,186,826 | <p>You should not be doing this. Instead, do:</p>
<p>test1.py:</p>
<pre><code> def print_test():
print "I am a test"
print "see! I do nothing productive."
</code></pre>
<p>service.py</p>
<pre><code>#near the top
from test1 import print_test
#lots of stuff here
print_test()
</code></pre>
| 8 | 2009-07-27T07:06:37Z | [
"python",
"eval"
] |
What is the best way to call a Python script from another Python script? | 1,186,789 | <p>I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.</p>
<p>For example:</p>
<h3>File test1.py</h3>
<pre><code>print "I am a test"
print "see! I do nothing productive."
</code></pre>
<h3>File service.py</h3>
<pre><code># Lots of stuff here
test1.py # do whatever is in test1.py
</code></pre>
<p>I'm aware of one method which is opening the file, reading the contents, and basically eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.</p>
| 136 | 2009-07-27T06:52:48Z | 1,186,840 | <p>Use <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-import-statement"><code>import test1</code></a> for the 1st use - it will execute the script. For later invocations, treat the script as an imported module, and call the <a href="http://docs.python.org/library/functions.html#reload"><code>reload(test1)</code></a> method.</p>
<blockquote>
<p>When <code>reload(module)</code> is executed:</p>
<ul>
<li>Python modulesâ code is recompiled and the <strong>module-level code reexecuted</strong>, defining a new set of objects which are bound to names in the moduleâs dictionary. The init function of extension modules is not called </li>
</ul>
</blockquote>
<p>A simple check of <a href="http://docs.python.org/library/sys.html#sys.modules"><code>sys.modules</code></a> can be used to invoke the appropriate action. To keep referring to the script name as a string (<code>'test1'</code>), use the <a href="http://docs.python.org/library/functions.html#%5F%5Fimport%5F%5F">'<strong>import</strong>()'</a> builtin.</p>
<pre><code>import sys
if sys.modules.has_key['test1']:
reload(sys.modules['test1'])
else:
__import__('test1')
</code></pre>
| 6 | 2009-07-27T07:11:08Z | [
"python",
"eval"
] |
What is the best way to call a Python script from another Python script? | 1,186,789 | <p>I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.</p>
<p>For example:</p>
<h3>File test1.py</h3>
<pre><code>print "I am a test"
print "see! I do nothing productive."
</code></pre>
<h3>File service.py</h3>
<pre><code># Lots of stuff here
test1.py # do whatever is in test1.py
</code></pre>
<p>I'm aware of one method which is opening the file, reading the contents, and basically eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.</p>
| 136 | 2009-07-27T06:52:48Z | 1,186,844 | <p>If you want test1.py to remain executable with the same functionality as when it's called inside service.py, then do something like:</p>
<p>test1.py</p>
<pre><code>def main():
print "I am a test"
print "see! I do nothing productive."
if __name__ == "__main__":
main()
</code></pre>
<p>service.py</p>
<pre><code>import test1
# lots of stuff here
test1.main() # do whatever is in test1.py
</code></pre>
| 14 | 2009-07-27T07:11:51Z | [
"python",
"eval"
] |
What is the best way to call a Python script from another Python script? | 1,186,789 | <p>I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.</p>
<p>For example:</p>
<h3>File test1.py</h3>
<pre><code>print "I am a test"
print "see! I do nothing productive."
</code></pre>
<h3>File service.py</h3>
<pre><code># Lots of stuff here
test1.py # do whatever is in test1.py
</code></pre>
<p>I'm aware of one method which is opening the file, reading the contents, and basically eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.</p>
| 136 | 2009-07-27T06:52:48Z | 1,186,847 | <p>The usual way to do this is something like the following.</p>
<p>test1.py</p>
<pre><code>def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
</code></pre>
<p>service.py</p>
<pre><code>import test1
def service_func():
print 'service func'
if __name__ == '__main__':
# service.py executed as script
# do something
service_func()
test1.some_func()
</code></pre>
| 134 | 2009-07-27T07:12:30Z | [
"python",
"eval"
] |
What is the best way to call a Python script from another Python script? | 1,186,789 | <p>I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.</p>
<p>For example:</p>
<h3>File test1.py</h3>
<pre><code>print "I am a test"
print "see! I do nothing productive."
</code></pre>
<h3>File service.py</h3>
<pre><code># Lots of stuff here
test1.py # do whatever is in test1.py
</code></pre>
<p>I'm aware of one method which is opening the file, reading the contents, and basically eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.</p>
| 136 | 2009-07-27T06:52:48Z | 11,230,471 | <p>Another way:</p>
<h3>File test1.py:</h3>
<pre><code>print "test1.py"
</code></pre>
<h3>File service.py:</h3>
<pre><code>import subprocess
subprocess.call("test1.py", shell=True)
</code></pre>
<p>The advantage to this method is that you don't have to edit an existing Python script to put all its code into a subroutine.</p>
| 34 | 2012-06-27T16:01:06Z | [
"python",
"eval"
] |
jQuery getJSON callback does not work - even with valid JSON - and seems to be using "OPTION" request not "GET" | 1,186,827 | <p>The background is that I've got a celery distributed job server configured with a Django view that returns the status of a running job in JSON. The job server is located at celeryserver.mydomain.com and the page I'm executing the jQuery from is www.mydomain.com so I shouldn't need to consider JSONP for this should I, as the requests aren't being made to different domains?</p>
<p>Watching my server logs I see that jQuery is executing the <code>getJSON</code> call every 3 seconds as it should (with the Javascript setInterval). It does seem to use an OPTION request, but I've confirmed using <code>curl</code> that the JSON is still returned for these request types.</p>
<p>The issue is that the <code>console.log()</code> Firebug call in the jQuery below doesn't ever seem to run! The one before the getJSON call does. Not having a callback work is a problem for me because I was hoping to poll for a celery job status in this manner and do various things based on the status of the job.</p>
<pre><code><script type="text/javascript">
var job_id = 'a8f25420-1faf-4084-bf45-fe3f82200ccb';
// wait for the DOM to be loaded then start polling for conversion status
$(document).ready(function() {
var getConvertStatus = function(){
console.log('getting some status');
$.getJSON("https://celeryserver.mydomain.com/done/" + job_id,
function(data){
console.log('callback works');
});
}
setInterval(getConvertStatus, 3000);
});
</script>
</code></pre>
<p>I've used <code>curl</code> to make sure of what I'm receiving from the server:</p>
<pre><code>$ curl -D - -k -X GET https://celeryserver.mydomain.com/done/a8f25420-1faf-4084-bf45-fe3f82200ccb
HTTP/1.1 200 OK
Server: nginx/0.6.35
Date: Mon, 27 Jul 2009 06:08:42 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
{"task": {"executed": true, "id": "a8f25420-1faf-4084-bf45-fe3f82200ccb"}}
</code></pre>
<p>That JSON looks fine to me and JSONlint.com validates it for me right now... I also simulated the jQuery query with <code>-X OPTION</code> and got exactly the same data back from the server as with a GET (content-type of application/json etc.)</p>
<p>I've been staring at this for ages now, any help greatly appreciated. I'm a pretty new jQuery user but this seems like it should be pretty problem-free so I have no idea what I'm doing wrong!</p>
| 4 | 2009-07-27T07:06:53Z | 1,186,865 | <p>Are you fetching the JSON from another domain? If so, you're most likely running into cross-domain issues. You'll need to use JSONP. jQuery does this automatically, but the server needs to know that. </p>
<p>See:</p>
<p><a href="http://www.ibm.com/developerworks/library/wa-aj-jsonp1/" rel="nofollow">http://www.ibm.com/developerworks/library/wa-aj-jsonp1/</a></p>
| 0 | 2009-07-27T07:19:09Z | [
"jquery",
"python",
"django",
"json"
] |
jQuery getJSON callback does not work - even with valid JSON - and seems to be using "OPTION" request not "GET" | 1,186,827 | <p>The background is that I've got a celery distributed job server configured with a Django view that returns the status of a running job in JSON. The job server is located at celeryserver.mydomain.com and the page I'm executing the jQuery from is www.mydomain.com so I shouldn't need to consider JSONP for this should I, as the requests aren't being made to different domains?</p>
<p>Watching my server logs I see that jQuery is executing the <code>getJSON</code> call every 3 seconds as it should (with the Javascript setInterval). It does seem to use an OPTION request, but I've confirmed using <code>curl</code> that the JSON is still returned for these request types.</p>
<p>The issue is that the <code>console.log()</code> Firebug call in the jQuery below doesn't ever seem to run! The one before the getJSON call does. Not having a callback work is a problem for me because I was hoping to poll for a celery job status in this manner and do various things based on the status of the job.</p>
<pre><code><script type="text/javascript">
var job_id = 'a8f25420-1faf-4084-bf45-fe3f82200ccb';
// wait for the DOM to be loaded then start polling for conversion status
$(document).ready(function() {
var getConvertStatus = function(){
console.log('getting some status');
$.getJSON("https://celeryserver.mydomain.com/done/" + job_id,
function(data){
console.log('callback works');
});
}
setInterval(getConvertStatus, 3000);
});
</script>
</code></pre>
<p>I've used <code>curl</code> to make sure of what I'm receiving from the server:</p>
<pre><code>$ curl -D - -k -X GET https://celeryserver.mydomain.com/done/a8f25420-1faf-4084-bf45-fe3f82200ccb
HTTP/1.1 200 OK
Server: nginx/0.6.35
Date: Mon, 27 Jul 2009 06:08:42 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
{"task": {"executed": true, "id": "a8f25420-1faf-4084-bf45-fe3f82200ccb"}}
</code></pre>
<p>That JSON looks fine to me and JSONlint.com validates it for me right now... I also simulated the jQuery query with <code>-X OPTION</code> and got exactly the same data back from the server as with a GET (content-type of application/json etc.)</p>
<p>I've been staring at this for ages now, any help greatly appreciated. I'm a pretty new jQuery user but this seems like it should be pretty problem-free so I have no idea what I'm doing wrong!</p>
| 4 | 2009-07-27T07:06:53Z | 1,186,874 | <p>I think you have a cross-subdomain issue, <code>sub.domain.tld</code> and <code>domain.ltd</code> are not the same.</p>
<p>I recommend you to install <a href="http://getfirebug.com/" rel="nofollow">Firebug</a> and check if your code is throwing an <em>Permission denied</em> Exception when the request starts, if it's the case, go for JSONP...</p>
| 3 | 2009-07-27T07:22:12Z | [
"jquery",
"python",
"django",
"json"
] |
jQuery getJSON callback does not work - even with valid JSON - and seems to be using "OPTION" request not "GET" | 1,186,827 | <p>The background is that I've got a celery distributed job server configured with a Django view that returns the status of a running job in JSON. The job server is located at celeryserver.mydomain.com and the page I'm executing the jQuery from is www.mydomain.com so I shouldn't need to consider JSONP for this should I, as the requests aren't being made to different domains?</p>
<p>Watching my server logs I see that jQuery is executing the <code>getJSON</code> call every 3 seconds as it should (with the Javascript setInterval). It does seem to use an OPTION request, but I've confirmed using <code>curl</code> that the JSON is still returned for these request types.</p>
<p>The issue is that the <code>console.log()</code> Firebug call in the jQuery below doesn't ever seem to run! The one before the getJSON call does. Not having a callback work is a problem for me because I was hoping to poll for a celery job status in this manner and do various things based on the status of the job.</p>
<pre><code><script type="text/javascript">
var job_id = 'a8f25420-1faf-4084-bf45-fe3f82200ccb';
// wait for the DOM to be loaded then start polling for conversion status
$(document).ready(function() {
var getConvertStatus = function(){
console.log('getting some status');
$.getJSON("https://celeryserver.mydomain.com/done/" + job_id,
function(data){
console.log('callback works');
});
}
setInterval(getConvertStatus, 3000);
});
</script>
</code></pre>
<p>I've used <code>curl</code> to make sure of what I'm receiving from the server:</p>
<pre><code>$ curl -D - -k -X GET https://celeryserver.mydomain.com/done/a8f25420-1faf-4084-bf45-fe3f82200ccb
HTTP/1.1 200 OK
Server: nginx/0.6.35
Date: Mon, 27 Jul 2009 06:08:42 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
{"task": {"executed": true, "id": "a8f25420-1faf-4084-bf45-fe3f82200ccb"}}
</code></pre>
<p>That JSON looks fine to me and JSONlint.com validates it for me right now... I also simulated the jQuery query with <code>-X OPTION</code> and got exactly the same data back from the server as with a GET (content-type of application/json etc.)</p>
<p>I've been staring at this for ages now, any help greatly appreciated. I'm a pretty new jQuery user but this seems like it should be pretty problem-free so I have no idea what I'm doing wrong!</p>
| 4 | 2009-07-27T07:06:53Z | 1,187,595 | <p>change your url to something like:</p>
<p>"https://celeryserver.mydomain.com/done/" + job_id + "?callback=?"</p>
<p>and then on your django view result should be something to the effect of:</p>
<pre><code>'{callback}({json})'.format(callback=request.GET['callback'], json=MyJSON)
</code></pre>
<p>...there are probably plenty of ways of doing that last line, but
basically read in the callback parameter (or name it whatever you want)</p>
<p>and then return it as calling your json object
(jQuery takes care of creating a callback function (it replaces '?' with the generated function))</p>
| 1 | 2009-07-27T11:05:19Z | [
"jquery",
"python",
"django",
"json"
] |
jQuery getJSON callback does not work - even with valid JSON - and seems to be using "OPTION" request not "GET" | 1,186,827 | <p>The background is that I've got a celery distributed job server configured with a Django view that returns the status of a running job in JSON. The job server is located at celeryserver.mydomain.com and the page I'm executing the jQuery from is www.mydomain.com so I shouldn't need to consider JSONP for this should I, as the requests aren't being made to different domains?</p>
<p>Watching my server logs I see that jQuery is executing the <code>getJSON</code> call every 3 seconds as it should (with the Javascript setInterval). It does seem to use an OPTION request, but I've confirmed using <code>curl</code> that the JSON is still returned for these request types.</p>
<p>The issue is that the <code>console.log()</code> Firebug call in the jQuery below doesn't ever seem to run! The one before the getJSON call does. Not having a callback work is a problem for me because I was hoping to poll for a celery job status in this manner and do various things based on the status of the job.</p>
<pre><code><script type="text/javascript">
var job_id = 'a8f25420-1faf-4084-bf45-fe3f82200ccb';
// wait for the DOM to be loaded then start polling for conversion status
$(document).ready(function() {
var getConvertStatus = function(){
console.log('getting some status');
$.getJSON("https://celeryserver.mydomain.com/done/" + job_id,
function(data){
console.log('callback works');
});
}
setInterval(getConvertStatus, 3000);
});
</script>
</code></pre>
<p>I've used <code>curl</code> to make sure of what I'm receiving from the server:</p>
<pre><code>$ curl -D - -k -X GET https://celeryserver.mydomain.com/done/a8f25420-1faf-4084-bf45-fe3f82200ccb
HTTP/1.1 200 OK
Server: nginx/0.6.35
Date: Mon, 27 Jul 2009 06:08:42 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
{"task": {"executed": true, "id": "a8f25420-1faf-4084-bf45-fe3f82200ccb"}}
</code></pre>
<p>That JSON looks fine to me and JSONlint.com validates it for me right now... I also simulated the jQuery query with <code>-X OPTION</code> and got exactly the same data back from the server as with a GET (content-type of application/json etc.)</p>
<p>I've been staring at this for ages now, any help greatly appreciated. I'm a pretty new jQuery user but this seems like it should be pretty problem-free so I have no idea what I'm doing wrong!</p>
| 4 | 2009-07-27T07:06:53Z | 1,191,760 | <p>As several people stated, sub-domains count as domains and I had a cross-domain issue :)</p>
<p>I solved it by creating a little piece of Django Middleware that changes the response from my views if they're returning JSON and the request had a callback attached.</p>
<pre><code>class JSONPMiddleware:
def process_response(self, request, response):
ctype = response.get('content-type', None)
cback = request.GET.get('callback', None)
if ctype == 'application/json' and cback:
jsonp = '{callback}({json})'.format(callback=cback, json=response.content)
return HttpResponse(content=jsonp, mimetype='application/javascript')
return response
</code></pre>
<p>All is now working as planned. Thanks!</p>
| 1 | 2009-07-28T03:14:40Z | [
"jquery",
"python",
"django",
"json"
] |
Real world guide on using and/or setting up REST web services? | 1,186,839 | <p>I've only used XML RPC and I haven't really delved into SOAP but I'm trying to find a good comprehensive guide, with real world examples or even a walkthrough of some minimal REST application.</p>
<p>I'm most comfortable with Python/PHP.</p>
| 0 | 2009-07-27T07:11:06Z | 1,186,876 | <p>I like the examples in the Richardson & Ruby book, "RESTful Web Services" from O'Reilly.</p>
| 1 | 2009-07-27T07:22:47Z | [
"php",
"python",
"xml",
"rest",
"soap"
] |
Real world guide on using and/or setting up REST web services? | 1,186,839 | <p>I've only used XML RPC and I haven't really delved into SOAP but I'm trying to find a good comprehensive guide, with real world examples or even a walkthrough of some minimal REST application.</p>
<p>I'm most comfortable with Python/PHP.</p>
| 0 | 2009-07-27T07:11:06Z | 1,186,879 | <p>There is a good example with the Google App Engine Documentation. <a href="http://code.google.com/appengine/articles/rpc.html" rel="nofollow">http://code.google.com/appengine/articles/rpc.html</a>. It also talks you through some security aspects of doing REST</p>
| 1 | 2009-07-27T07:23:31Z | [
"php",
"python",
"xml",
"rest",
"soap"
] |
Real world guide on using and/or setting up REST web services? | 1,186,839 | <p>I've only used XML RPC and I haven't really delved into SOAP but I'm trying to find a good comprehensive guide, with real world examples or even a walkthrough of some minimal REST application.</p>
<p>I'm most comfortable with Python/PHP.</p>
| 0 | 2009-07-27T07:11:06Z | 1,186,996 | <p>Here are a few links:</p>
<ul>
<li><a href="http://www.infoq.com/articles/webber-rest-workflow" rel="nofollow">http://www.infoq.com/articles/webber-rest-workflow</a></li>
<li><a href="http://microformats.org/wiki/rest/urls" rel="nofollow">http://microformats.org/wiki/rest/urls</a></li>
<li><a href="http://blog.feedly.com/2009/05/06/best-practices-for-building-json-rest-web-services/" rel="nofollow">http://blog.feedly.com/2009/05/06/best-practices-for-building-json-rest-web-services/</a></li>
<li><a href="http://barelyenough.org/blog/2008/05/versioning-rest-web-services/" rel="nofollow">http://barelyenough.org/blog/2008/05/versioning-rest-web-services/</a></li>
<li><a href="http://bitworking.org/news/restful_json/" rel="nofollow">http://bitworking.org/news/restful_json/</a></li>
</ul>
<p>(I should note, that the last one uses relative url's - a practise I don't like. But the rest of the article is very good, so I linked it anyway.)</p>
| 1 | 2009-07-27T08:04:40Z | [
"php",
"python",
"xml",
"rest",
"soap"
] |
How to open python source files using the IDLE shell? | 1,186,884 | <p>If I import a module in IDLE using: </p>
<pre><code>import <module_name>
print <module_name>.__file__
</code></pre>
<p>how can I open it without going through the Menu->File->Open multiple-step procedure?</p>
<p>It would be nice to open it via a command that takes the path and outputs a separate editor like IDLE.</p>
| 1 | 2009-07-27T07:24:48Z | 1,188,735 | <p>I don't think IDLE will do it for you, but if you use Wing, you can mouse over the name of the module, and do a <Ctrl>-<Left Click>, or open the right click context menu on the module name, and select "Goto definition." Simple. You don't even have to know the module's <strong>file</strong> location; you just have to have it on your PYTHONPATH.</p>
<p>Limitation: It doesn't work if you add it to your PYTHONPATH using sys.path.append(). It has to be on the path that exists when the file is opened, though you can configure that on a per-project or per-file basis within Wing.</p>
| 0 | 2009-07-27T15:11:11Z | [
"python",
"file",
"ide"
] |
How to open python source files using the IDLE shell? | 1,186,884 | <p>If I import a module in IDLE using: </p>
<pre><code>import <module_name>
print <module_name>.__file__
</code></pre>
<p>how can I open it without going through the Menu->File->Open multiple-step procedure?</p>
<p>It would be nice to open it via a command that takes the path and outputs a separate editor like IDLE.</p>
| 1 | 2009-07-27T07:24:48Z | 1,196,993 | <ul>
<li>You can use <code>ALT-M</code> and write the name of the module in the popup box</li>
<li>You can use <code>CTRL-O</code> to open a file</li>
</ul>
| 2 | 2009-07-28T21:59:13Z | [
"python",
"file",
"ide"
] |
python SOAPpy problem | 1,186,922 | <p>This my code</p>
<p>service part
<hr /></p>
<pre><code>class Test:
def hello():
return "Hello World"
</code></pre>
<p>server Part
<hr /></p>
<pre><code>import SOAPpy
from first_SOAP import *
host = "127.0.0.1"
port = 5551
SOAPpy.Config.debug = 1
server = SOAPpy.SOAPServer((host, port))
server.registerKWFunction(Test.hello)
print "Server Runing"
server.serve_forever(
</code></pre>
<p>Client part
<hr /></p>
<pre><code>import SOAPpy
SOAPpy.Config.debug = 1
server = SOAPpy.SOAPProxy("http://127.0.0.1:5551/")
print server.Test.hello()
</code></pre>
<p>This the what i am getting error </p>
<pre><code>n build.
*** Outgoing HTTP headers **********************************************
POST / HTTP/1.0
Host: 127.0.0.1:5551
User-agent: SOAPpy 0.12.0 (http://pywebsvcs.sf.net)
Content-type: text/xml; charset="UTF-8"
Content-length: 350
SOAPAction: "Test.hello"
************************************************************************
*** Outgoing SOAP ******************************************************
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
>
<SOAP-ENV:Body>
<Test.hello SOAP-ENC:root="1">
</Test.hello>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
************************************************************************
code= 500
msg= Internal Server Error
headers= Server: <a href="http://pywebsvcs.sf.net">SOAPpy 0.12.0</a> (Python 2.5.2)
Date: Mon, 27 Jul 2009 07:25:40 GMT
Content-type: text/xml; charset="UTF-8"
Content-length: 674
content-type= text/xml; charset="UTF-8"
data= <?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
>
<SOAP-ENV:Body>
<SOAP-ENV:Fault SOAP-ENC:root="1">
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring>Method Not Found</faultstring>
<detail xsi:type="xsd:string">Test.hello : &lt;type 'exceptions.KeyError'&gt; None &lt;traceback object at 0x9fbcb44&gt;</detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*** Incoming HTTP headers **********************************************
HTTP/1.? 500 Internal Server Error
Server: <a href="http://pywebsvcs.sf.net">SOAPpy 0.12.0</a> (Python 2.5.2)
Date: Mon, 27 Jul 2009 07:25:40 GMT
Content-type: text/xml; charset="UTF-8"
Content-length: 674
************************************************************************
*** Incoming SOAP ******************************************************
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
>
<SOAP-ENV:Body>
<SOAP-ENV:Fault SOAP-ENC:root="1">
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring>Method Not Found</faultstring>
<detail xsi:type="xsd:string">Test.hello : &lt;type 'exceptions.KeyError'&gt; None &lt;traceback object at 0x9fbcb44&gt;</detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
************************************************************************
<Fault SOAP-ENV:Client: Method Not Found: Test.hello : <type 'exceptions.KeyError'> None <traceback object at 0x9fbcb44>>
Traceback (most recent call last):
File "/home/rajaneesh/workspace/raju/src/call.py", line 4, in <module>
print server.Test.hello()
File "/var/lib/python-support/python2.5/SOAPpy/Client.py", line 470, in __call__
return self.__r_call(*args, **kw)
File "/var/lib/python-support/python2.5/SOAPpy/Client.py", line 492, in __r_call
self.__hd, self.__ma)
File "/var/lib/python-support/python2.5/SOAPpy/Client.py", line 406, in __call
raise p
SOAPpy.Types.faultType: <Fault SOAP-ENV:Client: Method Not Found: Test.hello : <type 'exceptions.KeyError'> None <traceback object at 0x9fbcb44>>
</code></pre>
| 0 | 2009-07-27T07:39:32Z | 1,187,039 | <p>Do you really want to make test() a class method? I suggest you change your code like this.</p>
<pre><code>class Test:
def hello(self):
return "Hello World"
</code></pre>
<p>Then you must create an instance of the Test class and register:</p>
<pre><code>server.registerObject(Test())
</code></pre>
<p>Then the client can access the hello() method like this:</p>
<pre><code>print server.hello()
</code></pre>
| 0 | 2009-07-27T08:20:01Z | [
"python",
"soappy"
] |
Persistent Python Command-Line History | 1,186,958 | <p>I'd like to be able to "up-arrow" to commands that I input in a previous Python interpreter. I have found the <code>readline</code> module which offers functions like: <code>read_history_file</code>, <code>write_history_file</code>, and <code>set_startup_hook</code>. I'm not quite savvy enough to put this into practice though, so could someone please help? My thoughts on the solution are:</p>
<p>(1) Modify .login PYTHONSTARTUP to run a python script.
(2) In that python script file do something like:</p>
<pre><code>def command_history_hook():
import readline
readline.read_history_file('.python_history')
command_history_hook()
</code></pre>
<p>(3) Whenever the interpreter exits, write the history to the file. I guess the best way to do this is to define a function in your startup script and exit using that function:</p>
<pre><code>def ex():
import readline
readline.write_history_file('.python_history')
exit()
</code></pre>
<p>It's very annoying to have to exit using parentheses, though: <code>ex()</code>. Is there some python sugar that would allow <code>ex</code> (without the parens) to run the <code>ex</code> function?</p>
<p>Is there a better way to cause the history file to write each time? Thanks in advance for all solutions/suggestions.</p>
<p>Also, there are two architectural choices as I can see. One choice is to have a unified command history. The benefit is simplicity (the alternative that follows litters your home directory with a lot of files.) The disadvantage is that interpreters you run in separate terminals will be populated with each other's command histories, and they will overwrite one another's histories. (this is okay for me since I'm usually interested in closing an interpreter and reopening one immediately to reload modules, and in that case that interpreter's commands will have been written to the file.) One possible solution to maintain separate history files per terminal is to write an environment variable for each new terminal you create:</p>
<pre><code>def random_key()
''.join([choice(string.uppercase + string.digits) for i in range(16)])
def command_history_hook():
import readline
key = get_env_variable('command_history_key')
if key:
readline.read_history_file('.python_history_{0}'.format(key))
else:
set_env_variable('command_history_key', random_key())
def ex():
import readline
key = get_env_variable('command_history_key')
if not key:
set_env_variable('command_history_key', random_key())
readline.write_history_file('.python_history_{0}'.format(key))
exit()
</code></pre>
<p>By decreasing the random key length from 16 to say 1 you could decrease the number of files littering your directories to 36 at the expense of possible (2.8% chance) of overlap.</p>
| 14 | 2009-07-27T07:53:11Z | 1,186,975 | <p>Try using <a href="http://ipython.scipy.org/moin/" rel="nofollow">IPython</a> as a python shell. It already has everything you ask for. They have packages for most popular distros, so install should be very easy.</p>
| 4 | 2009-07-27T08:01:30Z | [
"interpreter",
"python"
] |
Persistent Python Command-Line History | 1,186,958 | <p>I'd like to be able to "up-arrow" to commands that I input in a previous Python interpreter. I have found the <code>readline</code> module which offers functions like: <code>read_history_file</code>, <code>write_history_file</code>, and <code>set_startup_hook</code>. I'm not quite savvy enough to put this into practice though, so could someone please help? My thoughts on the solution are:</p>
<p>(1) Modify .login PYTHONSTARTUP to run a python script.
(2) In that python script file do something like:</p>
<pre><code>def command_history_hook():
import readline
readline.read_history_file('.python_history')
command_history_hook()
</code></pre>
<p>(3) Whenever the interpreter exits, write the history to the file. I guess the best way to do this is to define a function in your startup script and exit using that function:</p>
<pre><code>def ex():
import readline
readline.write_history_file('.python_history')
exit()
</code></pre>
<p>It's very annoying to have to exit using parentheses, though: <code>ex()</code>. Is there some python sugar that would allow <code>ex</code> (without the parens) to run the <code>ex</code> function?</p>
<p>Is there a better way to cause the history file to write each time? Thanks in advance for all solutions/suggestions.</p>
<p>Also, there are two architectural choices as I can see. One choice is to have a unified command history. The benefit is simplicity (the alternative that follows litters your home directory with a lot of files.) The disadvantage is that interpreters you run in separate terminals will be populated with each other's command histories, and they will overwrite one another's histories. (this is okay for me since I'm usually interested in closing an interpreter and reopening one immediately to reload modules, and in that case that interpreter's commands will have been written to the file.) One possible solution to maintain separate history files per terminal is to write an environment variable for each new terminal you create:</p>
<pre><code>def random_key()
''.join([choice(string.uppercase + string.digits) for i in range(16)])
def command_history_hook():
import readline
key = get_env_variable('command_history_key')
if key:
readline.read_history_file('.python_history_{0}'.format(key))
else:
set_env_variable('command_history_key', random_key())
def ex():
import readline
key = get_env_variable('command_history_key')
if not key:
set_env_variable('command_history_key', random_key())
readline.write_history_file('.python_history_{0}'.format(key))
exit()
</code></pre>
<p>By decreasing the random key length from 16 to say 1 you could decrease the number of files littering your directories to 36 at the expense of possible (2.8% chance) of overlap.</p>
| 14 | 2009-07-27T07:53:11Z | 1,186,981 | <p>I think the suggestions in the Python documentation pretty much cover what you want. Look at the example pystartup file toward the end of section 13.3:</p>
<ul>
<li><a href="http://docs.python.org/tutorial/interactive.html">http://docs.python.org/tutorial/interactive.html</a></li>
</ul>
<p>or see this page:</p>
<ul>
<li><a href="http://rc98.net/pystartup">http://rc98.net/pystartup</a></li>
</ul>
<p>But, for an out of the box interactive shell that provides all this and more, take a look at using IPython:</p>
<ul>
<li><a href="http://ipython.scipy.org/moin/">http://ipython.scipy.org/moin/</a></li>
</ul>
| 13 | 2009-07-27T08:02:14Z | [
"interpreter",
"python"
] |
Persistent Python Command-Line History | 1,186,958 | <p>I'd like to be able to "up-arrow" to commands that I input in a previous Python interpreter. I have found the <code>readline</code> module which offers functions like: <code>read_history_file</code>, <code>write_history_file</code>, and <code>set_startup_hook</code>. I'm not quite savvy enough to put this into practice though, so could someone please help? My thoughts on the solution are:</p>
<p>(1) Modify .login PYTHONSTARTUP to run a python script.
(2) In that python script file do something like:</p>
<pre><code>def command_history_hook():
import readline
readline.read_history_file('.python_history')
command_history_hook()
</code></pre>
<p>(3) Whenever the interpreter exits, write the history to the file. I guess the best way to do this is to define a function in your startup script and exit using that function:</p>
<pre><code>def ex():
import readline
readline.write_history_file('.python_history')
exit()
</code></pre>
<p>It's very annoying to have to exit using parentheses, though: <code>ex()</code>. Is there some python sugar that would allow <code>ex</code> (without the parens) to run the <code>ex</code> function?</p>
<p>Is there a better way to cause the history file to write each time? Thanks in advance for all solutions/suggestions.</p>
<p>Also, there are two architectural choices as I can see. One choice is to have a unified command history. The benefit is simplicity (the alternative that follows litters your home directory with a lot of files.) The disadvantage is that interpreters you run in separate terminals will be populated with each other's command histories, and they will overwrite one another's histories. (this is okay for me since I'm usually interested in closing an interpreter and reopening one immediately to reload modules, and in that case that interpreter's commands will have been written to the file.) One possible solution to maintain separate history files per terminal is to write an environment variable for each new terminal you create:</p>
<pre><code>def random_key()
''.join([choice(string.uppercase + string.digits) for i in range(16)])
def command_history_hook():
import readline
key = get_env_variable('command_history_key')
if key:
readline.read_history_file('.python_history_{0}'.format(key))
else:
set_env_variable('command_history_key', random_key())
def ex():
import readline
key = get_env_variable('command_history_key')
if not key:
set_env_variable('command_history_key', random_key())
readline.write_history_file('.python_history_{0}'.format(key))
exit()
</code></pre>
<p>By decreasing the random key length from 16 to say 1 you could decrease the number of files littering your directories to 36 at the expense of possible (2.8% chance) of overlap.</p>
| 14 | 2009-07-27T07:53:11Z | 20,718,928 | <p>Use PIP to install the <em>pyreadline</em> package:</p>
<pre><code>pip install pyreadline
</code></pre>
| 0 | 2013-12-21T12:19:12Z | [
"interpreter",
"python"
] |
Persistent Python Command-Line History | 1,186,958 | <p>I'd like to be able to "up-arrow" to commands that I input in a previous Python interpreter. I have found the <code>readline</code> module which offers functions like: <code>read_history_file</code>, <code>write_history_file</code>, and <code>set_startup_hook</code>. I'm not quite savvy enough to put this into practice though, so could someone please help? My thoughts on the solution are:</p>
<p>(1) Modify .login PYTHONSTARTUP to run a python script.
(2) In that python script file do something like:</p>
<pre><code>def command_history_hook():
import readline
readline.read_history_file('.python_history')
command_history_hook()
</code></pre>
<p>(3) Whenever the interpreter exits, write the history to the file. I guess the best way to do this is to define a function in your startup script and exit using that function:</p>
<pre><code>def ex():
import readline
readline.write_history_file('.python_history')
exit()
</code></pre>
<p>It's very annoying to have to exit using parentheses, though: <code>ex()</code>. Is there some python sugar that would allow <code>ex</code> (without the parens) to run the <code>ex</code> function?</p>
<p>Is there a better way to cause the history file to write each time? Thanks in advance for all solutions/suggestions.</p>
<p>Also, there are two architectural choices as I can see. One choice is to have a unified command history. The benefit is simplicity (the alternative that follows litters your home directory with a lot of files.) The disadvantage is that interpreters you run in separate terminals will be populated with each other's command histories, and they will overwrite one another's histories. (this is okay for me since I'm usually interested in closing an interpreter and reopening one immediately to reload modules, and in that case that interpreter's commands will have been written to the file.) One possible solution to maintain separate history files per terminal is to write an environment variable for each new terminal you create:</p>
<pre><code>def random_key()
''.join([choice(string.uppercase + string.digits) for i in range(16)])
def command_history_hook():
import readline
key = get_env_variable('command_history_key')
if key:
readline.read_history_file('.python_history_{0}'.format(key))
else:
set_env_variable('command_history_key', random_key())
def ex():
import readline
key = get_env_variable('command_history_key')
if not key:
set_env_variable('command_history_key', random_key())
readline.write_history_file('.python_history_{0}'.format(key))
exit()
</code></pre>
<p>By decreasing the random key length from 16 to say 1 you could decrease the number of files littering your directories to 36 at the expense of possible (2.8% chance) of overlap.</p>
| 14 | 2009-07-27T07:53:11Z | 31,440,042 | <p>If all you want is to use interactive history substitution without all the file stuff, all you need to do is import readline:</p>
<pre><code>import readline
</code></pre>
<p>And then you can use the up/down keys to navigate past commands. Same for 2 or 3.</p>
<p>This wasn't clear to me from the docs, but maybe I missed it.</p>
| 0 | 2015-07-15T20:07:58Z | [
"interpreter",
"python"
] |
How do I control number formatting in the python interpreter? | 1,187,000 | <p>I often use the python interpreter for doing quick numerical calculations and would like all numerical results to be automatically printed using, e.g., exponential notation. Is there a way to set this for the entire session?</p>
<p>For example, I want:</p>
<pre><code>>>> 1.e12
1.0e+12
</code></pre>
<p>not:</p>
<pre><code>>>> 1.e12
1000000000000.0
</code></pre>
| 2 | 2009-07-27T08:06:00Z | 1,187,012 | <p>As you know you can use <a href="http://www.python.org/doc/2.5.2/lib/typesseq-strings.html" rel="nofollow">the <code>%</code> operator</a> or <a href="http://docs.python.org/library/stdtypes.html#str.format" rel="nofollow"><code>str.format</code></a> to format strings:</p>
<p>For example:</p>
<pre><code>>>> "%e" % 1.e12
'1.000000e+12'
</code></pre>
<p>I was wondering if you could <a href="http://en.wikipedia.org/wiki/Monkey%5Fpatch" rel="nofollow">monkey patch</a> the built-in <code>float</code> class to change the formatting but it seems that Python won't let you:</p>
<pre><code>>>> 1.e12.__class__.__repr__ = lambda x: "%e" % x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'float'
</code></pre>
<p>So the only other thing I can think of is to write your own file-like object which captures output, reformats it and sends it to the standard output. You'd then redirect standard output of the interpreter to this object:</p>
<pre><code>sys.stdout = my_formatting_object
</code></pre>
| 1 | 2009-07-27T08:09:46Z | [
"python",
"ipython"
] |
How do I control number formatting in the python interpreter? | 1,187,000 | <p>I often use the python interpreter for doing quick numerical calculations and would like all numerical results to be automatically printed using, e.g., exponential notation. Is there a way to set this for the entire session?</p>
<p>For example, I want:</p>
<pre><code>>>> 1.e12
1.0e+12
</code></pre>
<p>not:</p>
<pre><code>>>> 1.e12
1000000000000.0
</code></pre>
| 2 | 2009-07-27T08:06:00Z | 1,187,029 | <p>Hm... It's not a 100% solution, but this have come to my mind...</p>
<p>How about defining a subclass of float which would have an overridden <code>__str__</code> method (to print with the exp notation). And then you would have to wrap all the expressions with object construction of this class).
It would be a bit shorter than Dave's solution, you would define the class once and then write something like:</p>
<pre><code>>>> F(1.e12)
1.0e+12
>>> F(3.)
3.0e+0
>>> F(1.+2.+3.+4.)
1.0e+1
...
</code></pre>
| 1 | 2009-07-27T08:17:41Z | [
"python",
"ipython"
] |
How do I control number formatting in the python interpreter? | 1,187,000 | <p>I often use the python interpreter for doing quick numerical calculations and would like all numerical results to be automatically printed using, e.g., exponential notation. Is there a way to set this for the entire session?</p>
<p>For example, I want:</p>
<pre><code>>>> 1.e12
1.0e+12
</code></pre>
<p>not:</p>
<pre><code>>>> 1.e12
1000000000000.0
</code></pre>
| 2 | 2009-07-27T08:06:00Z | 1,187,067 | <p>Create a Python script called whatever you want (say <code>mystartup.py</code>) and then set an environment variable <code>PYTHONSTARTUP</code> to the path of this script. Python will then load this script on startup of an interactive session (but not when running scripts). In this script, define a function similar to this:</p>
<pre><code>def _(v):
if type(v) == type(0.0):
print "%e" % v
else:
print v
</code></pre>
<p>Then, in an interactive session:</p>
<pre>
C:\temp>set PYTHONSTARTUP=mystartup.py
C:\temp>python
ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> _(1e12)
1.000000e+012
>>> _(14)
14
>>> _(14.0)
1.400000e+001
>>>
</pre>
<p>Of course, you can define the function to be called whaetver you want and to work exactly however you want.</p>
<p>Even better than this would be to use <a href="http://ipython.scipy.org/" rel="nofollow">IPython</a>. It's great, and you can set the number formatting how you want by using <code>result_display.when_type(some_type)(my_print_func)</code> (see the IPython site or search for more details on how to use this).</p>
| 4 | 2009-07-27T08:31:41Z | [
"python",
"ipython"
] |
How do I control number formatting in the python interpreter? | 1,187,000 | <p>I often use the python interpreter for doing quick numerical calculations and would like all numerical results to be automatically printed using, e.g., exponential notation. Is there a way to set this for the entire session?</p>
<p>For example, I want:</p>
<pre><code>>>> 1.e12
1.0e+12
</code></pre>
<p>not:</p>
<pre><code>>>> 1.e12
1000000000000.0
</code></pre>
| 2 | 2009-07-27T08:06:00Z | 1,187,309 | <p>Building on Dave Webb's hint above. You can of course set the precision if you like ("%.3e") and perhaps override writelines if needed.</p>
<pre><code>import os
import sys
class ExpFloatFileObject:
def write(self, s):
try:
s = "%e"%float(s)
except ValueError:
pass
sys.__stdout__.write(s)
def __getattr__(self, name):
return getattr(sys.__stdout__, name)
sys.stdout = ExpFloatFileObject()
</code></pre>
<p>and usage:</p>
<pre><code>>>> 14000
1.400000e+04
>>> "text"
'text'
</code></pre>
| 1 | 2009-07-27T09:45:13Z | [
"python",
"ipython"
] |
In Python, how to tell if being called by exception handling code? | 1,187,102 | <p>I would like to write a function in Python (2.6) that can determine if it is being called from exception handling code somewhere up the stack.</p>
<p>This is for a specialized logging use. In python's <code>logging</code> module, the caller has to explicitly specify that exception information should be logged (either by calling <code>logger.exception()</code> or by using the <code>exc_info</code> keyword). I would like my logger to do this automatically, based on whether it is being called from within exception handling code.</p>
<p>I thought that checking sys.exc_info() might be the answer, but it also returns exception information from an already-handled exception. (From the <a href="http://docs.python.org/library/sys.html" rel="nofollow">docs</a>: "This function returns a tuple of three values that give information about the exception that is currently being handled... If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, 'handling an exception' is defined as 'executing or <b><i>having executed</i></b> an except clause.'")</p>
<p>Also, since I want this to be transparent to the caller, I do not want to have to use <code>exc_clear()</code> or anything else in the <code>except</code> clause.</p>
<p>What's the right way to do this?</p>
| 2 | 2009-07-27T08:40:55Z | 1,187,130 | <p>If you clear the exception using <code>sys.exc_clear</code> in your exception handlers, then <code>sys.exc_info</code> should work for you. For example: If you run the following script:</p>
<pre><code>import sys
try:
1 / 0
except:
print sys.exc_info()
sys.exc_clear()
print sys.exc_info()
</code></pre>
<p>You should see this output:</p>
<pre>
(, ZeroDivisionError('integer division or modulo by zero',), )
(None, None, None)
</pre>
<p><strong>Update:</strong> I don't believe there is a simple ("transparent") way of answering the question "Is an exception handler running?" without going to some trouble, and in my opinion it's not worth taking the trouble just for logging. It is of course easy to answer the question "Has an exception been raised (in this thread)?", even on a per-stack-frame basis (see the documentation for frame objects). </p>
| 2 | 2009-07-27T08:48:21Z | [
"python",
"exception"
] |
In Python, how to tell if being called by exception handling code? | 1,187,102 | <p>I would like to write a function in Python (2.6) that can determine if it is being called from exception handling code somewhere up the stack.</p>
<p>This is for a specialized logging use. In python's <code>logging</code> module, the caller has to explicitly specify that exception information should be logged (either by calling <code>logger.exception()</code> or by using the <code>exc_info</code> keyword). I would like my logger to do this automatically, based on whether it is being called from within exception handling code.</p>
<p>I thought that checking sys.exc_info() might be the answer, but it also returns exception information from an already-handled exception. (From the <a href="http://docs.python.org/library/sys.html" rel="nofollow">docs</a>: "This function returns a tuple of three values that give information about the exception that is currently being handled... If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, 'handling an exception' is defined as 'executing or <b><i>having executed</i></b> an except clause.'")</p>
<p>Also, since I want this to be transparent to the caller, I do not want to have to use <code>exc_clear()</code> or anything else in the <code>except</code> clause.</p>
<p>What's the right way to do this?</p>
| 2 | 2009-07-27T08:40:55Z | 1,187,484 | <p>Like everything in Python, an exception is an object. Therefore, you could keep a (weak!) reference to the last exception handled and then use <code>sys.exc_info()</code>.
Note: in case of multithreading code, you may have issues with this approach. And there could be other corner cases as well.</p>
<p>However, <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">explicit is better than implicit</a>; are you <em>really</em> sure that handling exception logging in the same way as normal one is a good feature to add to your system?<br />
In my humble opinion, not.</p>
| 0 | 2009-07-27T10:29:42Z | [
"python",
"exception"
] |
How to install a module as an egg under IronPython? | 1,187,110 | <p>Maybe, it is a stupid question but I can't use python eggs with IronPython.</p>
<p>I would like to test with IronPython 2.0.2 one module that I've developped. This modules is pure python. It works ok with python 2.6 and is installed as a python egg thanks to setuptools.</p>
<p>I thought that the process for installing my module under IronPython was very similar but unfortunately it doesn't work.</p>
<p>I can't install setuptools-0.6c9 with IronPython (Crash of IronPython). I've tried to copy manually my egg under IronPython site-packages and it doesn't work either.</p>
<p>I've also tried to include the python 2.6 site-package in the IronPython path but it can't load my module.</p>
<p>I've made some tests with other modules and it seems that IronPython can not load eggs. Did I miss something?</p>
| 2 | 2009-07-27T08:43:54Z | 1,187,165 | <p>AFAIK it's still not possible - it's work in progress. See <a href="http://ironpython-urls.blogspot.com/2009/01/jeff-hardy-django-zlib-and-easyinstall.html" rel="nofollow">this post</a>, for example. IronPython's main strength is in integration with the .NET ecosystem - it's not a drop-in replacement for CPython. See <a href="http://www.johndcook.com/blog/2009/02/26/ironpython-is-a-one-way-gate/" rel="nofollow">this post</a> for some other limitations of IronPython.</p>
| 1 | 2009-07-27T08:56:12Z | [
"python",
"ironpython",
"egg"
] |
How to check if some process is running in task manager with python | 1,187,264 | <p>I have one function in python which should start running when some process (eg. proc.exe) showed up in tasks manager.<br>
How can I monitor processes running in tasks manager with python?</p>
| 4 | 2009-07-27T09:26:20Z | 1,187,338 | <p>here is something, I've adapted from <a href="http://www.microsoft.com/technet/scriptcenter/scripts/python/pyindex.mspx?mfr=true">microsoft</a></p>
<pre>
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Process")
for objItem in colItems:
print "Name: ", objItem.Name
print "File location: ", objItem.ExecutablePath
</pre>
<p>There is <a href="http://www.microsoft.com/technet/scriptcenter/scripts/python/pyindex.mspx?mfr=true">here</a> a lot of nice examples for python and windows</p>
<p>Update: objItem.ExecutablePath gives the file location of the exe</p>
| 10 | 2009-07-27T09:54:04Z | [
"python",
"process"
] |
How to check if some process is running in task manager with python | 1,187,264 | <p>I have one function in python which should start running when some process (eg. proc.exe) showed up in tasks manager.<br>
How can I monitor processes running in tasks manager with python?</p>
| 4 | 2009-07-27T09:26:20Z | 7,180,235 | <p>Try the WMI module:
<a href="http://timgolden.me.uk/python/wmi/cookbook.html" rel="nofollow">http://timgolden.me.uk/python/wmi/cookbook.html</a></p>
| 0 | 2011-08-24T18:13:32Z | [
"python",
"process"
] |
How to resize svg image file using librsvg Python binding | 1,187,358 | <p>When rasterizing svg file, I would like to be able to set width and height for the resulting png file. With the following code, only the canvas is set to the desired width and height, the actual image content with the original svg file dimension is rendered in the top left corner on the (500, 600) canvas.</p>
<pre><code>import cairo
import rsvg
WIDTH, HEIGHT = 500, 600
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context(surface)
svg = rsvg.Handle(file="test.svg")
svg.render_cairo(ctx)
surface.write_to_png("test.png")
</code></pre>
<p>What should I do to make the image content same size with cairo canvas? I tried</p>
<pre><code>svg.set_property('width', 500)
svg.set_property('height', 500)
</code></pre>
<p>but got</p>
<pre><code>TypeError: property 'width' is not writable
</code></pre>
<p>Also documents for librsvg python binding seem to be extremely rare, only some random code snippets on cairo site.</p>
| 3 | 2009-07-27T10:00:20Z | 1,187,406 | <p>There is a <a href="http://library.gnome.org/devel/rsvg/stable/rsvg-Core-API.html#rsvg-handle-set-size-callback" rel="nofollow">resize function</a> in librsvg, but it is deprecated.</p>
<p>Set up a <a href="http://cairographics.org/manual/cairo-Transformations.html#cairo-scale" rel="nofollow">scale matrix</a> in Cairo to change the size of your drawing:</p>
<ul>
<li>setup a scale transformation matrix on your cairo context</li>
<li>draw your SVG with the .render_cairo() method</li>
<li>write your surface to PNG</li>
</ul>
| 6 | 2009-07-27T10:12:28Z | [
"python",
"cairo",
"librsvg"
] |
How to resize svg image file using librsvg Python binding | 1,187,358 | <p>When rasterizing svg file, I would like to be able to set width and height for the resulting png file. With the following code, only the canvas is set to the desired width and height, the actual image content with the original svg file dimension is rendered in the top left corner on the (500, 600) canvas.</p>
<pre><code>import cairo
import rsvg
WIDTH, HEIGHT = 500, 600
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context(surface)
svg = rsvg.Handle(file="test.svg")
svg.render_cairo(ctx)
surface.write_to_png("test.png")
</code></pre>
<p>What should I do to make the image content same size with cairo canvas? I tried</p>
<pre><code>svg.set_property('width', 500)
svg.set_property('height', 500)
</code></pre>
<p>but got</p>
<pre><code>TypeError: property 'width' is not writable
</code></pre>
<p>Also documents for librsvg python binding seem to be extremely rare, only some random code snippets on cairo site.</p>
| 3 | 2009-07-27T10:00:20Z | 26,133,667 | <p>This is the code that works for me.
It implements the answer by Luper above:</p>
<pre><code>import rsvg
import cairo
# Load the svg data
svg_xml = open('topthree.svg', 'r')
svg = rsvg.Handle()
svg.write(svg_xml.read())
svg.close()
# Prepare the Cairo context
img = cairo.ImageSurface(cairo.FORMAT_ARGB32,
WIDTH,
HEIGHT)
ctx = cairo.Context(img)
# Scale whatever is written into this context
# in this case 2x both x and y directions
ctx.scale(2, 2)
svg.render_cairo(ctx)
# Write out into a PNG file
png_io = StringIO.StringIO()
img.write_to_png(png_io)
with open('sample.png', 'wb') as fout:
fout.write(png_io.getvalue())
</code></pre>
| 2 | 2014-10-01T03:30:09Z | [
"python",
"cairo",
"librsvg"
] |
How to make the program run again after unexpected exit in Python? | 1,187,653 | <p>I'm writing an IRC bot in Python, due to the alpha nature of it, it will likely get unexpected errors and exit.</p>
<p>What's the techniques that I can use to make the program run again?</p>
| 1 | 2009-07-27T11:29:23Z | 1,187,671 | <p>The easiest way is to catch errors, and close the old and open a new instance of the program when you do catch em.</p>
<p>Note that it will not always work (in cases it stops working without throwing an error).</p>
| 0 | 2009-07-27T11:34:22Z | [
"python",
"irc"
] |
How to make the program run again after unexpected exit in Python? | 1,187,653 | <p>I'm writing an IRC bot in Python, due to the alpha nature of it, it will likely get unexpected errors and exit.</p>
<p>What's the techniques that I can use to make the program run again?</p>
| 1 | 2009-07-27T11:29:23Z | 1,187,733 | <p>You can create wrapper using subprocess(<a href="http://docs.python.org/library/subprocess.html" rel="nofollow">http://docs.python.org/library/subprocess.html</a>) which will spawn your application as a child process and track it's execution.</p>
| 1 | 2009-07-27T11:49:31Z | [
"python",
"irc"
] |
How to make the program run again after unexpected exit in Python? | 1,187,653 | <p>I'm writing an IRC bot in Python, due to the alpha nature of it, it will likely get unexpected errors and exit.</p>
<p>What's the techniques that I can use to make the program run again?</p>
| 1 | 2009-07-27T11:29:23Z | 1,187,787 | <p>You can use <code>sys.exit()</code> to tell that the program exited abnormally (generally, 1 is returned in case of error).</p>
<p>Your Python script could look something like this:</p>
<pre><code>import sys
def main():
# ...
if __name__ == '__main__':
try:
main()
except Exception as e:
print >> sys.stderr, e
sys.exit(1)
else:
sys.exit()
</code></pre>
<p>You could call again <code>main()</code> in case of error, but the program might not be in a state where it can work correctly again.
It may be safer to launch the program in a new process instead.</p>
<p>So you could write a script which invokes the Python script, gets its return value when it finishes, and relaunches it if the return value is different from 0 (which is what <code>sys.exit()</code> uses as return value by default).
This may look something like this:</p>
<pre><code>import subprocess
command = 'thescript'
args = ['arg1', 'arg2']
while True:
ret_code = subprocess.call([command] + args)
if ret_code == 0:
break
</code></pre>
| 5 | 2009-07-27T11:59:31Z | [
"python",
"irc"
] |
To set up environmental variables for a Python web application | 1,187,716 | <p>I need to set up the following env variables such that I can a database program which use PostgreSQL</p>
<pre><code>export PGDATA="/home/masi/postgres/var"
export PGPORT="12428"
</code></pre>
<p>I know that the problem may be solved by adding the files to .zshrc.
However, I am not sure whether it is the right way to go.</p>
<p><strong>How can you add env variables?</strong></p>
| 1 | 2009-07-27T11:46:30Z | 1,188,055 | <p>Put this somewhere in the main page of your app :</p>
<pre><code>import os
os.environ["PGDATA"] = "/home/masi/postgres/var"
os.environ["PGPORT"] = 12428
</code></pre>
<p>however, isn't there a better way to set that in the framework you use?</p>
| 2 | 2009-07-27T13:02:29Z | [
"python",
"postgresql"
] |
To set up environmental variables for a Python web application | 1,187,716 | <p>I need to set up the following env variables such that I can a database program which use PostgreSQL</p>
<pre><code>export PGDATA="/home/masi/postgres/var"
export PGPORT="12428"
</code></pre>
<p>I know that the problem may be solved by adding the files to .zshrc.
However, I am not sure whether it is the right way to go.</p>
<p><strong>How can you add env variables?</strong></p>
| 1 | 2009-07-27T11:46:30Z | 1,192,987 | <p>You only need to set the PGDATA variable in the script that starts the <em>server</em>. The client only cares about the port.</p>
<p>You do have to set the port value if you must run it on a non-standard port. I assume you have a good reason to not just run it on the default port? If you do run it on the default port (5432), it will just work without any parameters for it at all.</p>
<p>If you are running it on a different port, you should make two changes:</p>
<ul>
<li>In postgresql.conf, set the port= value to the new port you want, and restart the database server.</li>
<li>In your settings.py in django, set the DATABASE_PORT value to the new port you want.</li>
</ul>
<p>You should definitely not need to use environment variables for simple configuration options like these - avoiding them will make your life easier.</p>
| 3 | 2009-07-28T09:32:30Z | [
"python",
"postgresql"
] |
Empty XML element handling in Python | 1,187,718 | <p>I'm puzzled by minidom parser handling of empty element, as shown in following code section.</p>
<pre><code>import xml.dom.minidom
doc = xml.dom.minidom.parseString('<value></value>')
print doc.firstChild.nodeValue.__repr__()
# Out: None
print doc.firstChild.toxml()
# Out: <value/>
doc = xml.dom.minidom.Document()
v = doc.appendChild(doc.createElement('value'))
v.appendChild(doc.createTextNode(''))
print v.firstChild.nodeValue.__repr__()
# Out: ''
print doc.firstChild.toxml()
# Out: <value></value>
</code></pre>
<p>How can I get consistent behavior? I'd like to receive <em>empty string</em> as value of <em>empty element</em> (which <em>IS</em> what I put in XML structure in the first place).</p>
| 2 | 2009-07-27T11:46:32Z | 1,188,437 | <pre><code>value = thing.firstChild.nodeValue or ''
</code></pre>
| 1 | 2009-07-27T14:21:13Z | [
"python",
"xml",
"string"
] |
Empty XML element handling in Python | 1,187,718 | <p>I'm puzzled by minidom parser handling of empty element, as shown in following code section.</p>
<pre><code>import xml.dom.minidom
doc = xml.dom.minidom.parseString('<value></value>')
print doc.firstChild.nodeValue.__repr__()
# Out: None
print doc.firstChild.toxml()
# Out: <value/>
doc = xml.dom.minidom.Document()
v = doc.appendChild(doc.createElement('value'))
v.appendChild(doc.createTextNode(''))
print v.firstChild.nodeValue.__repr__()
# Out: ''
print doc.firstChild.toxml()
# Out: <value></value>
</code></pre>
<p>How can I get consistent behavior? I'd like to receive <em>empty string</em> as value of <em>empty element</em> (which <em>IS</em> what I put in XML structure in the first place).</p>
| 2 | 2009-07-27T11:46:32Z | 1,188,448 | <p>Xml spec does not distinguish these two cases.</p>
| 1 | 2009-07-27T14:22:57Z | [
"python",
"xml",
"string"
] |
Empty XML element handling in Python | 1,187,718 | <p>I'm puzzled by minidom parser handling of empty element, as shown in following code section.</p>
<pre><code>import xml.dom.minidom
doc = xml.dom.minidom.parseString('<value></value>')
print doc.firstChild.nodeValue.__repr__()
# Out: None
print doc.firstChild.toxml()
# Out: <value/>
doc = xml.dom.minidom.Document()
v = doc.appendChild(doc.createElement('value'))
v.appendChild(doc.createTextNode(''))
print v.firstChild.nodeValue.__repr__()
# Out: ''
print doc.firstChild.toxml()
# Out: <value></value>
</code></pre>
<p>How can I get consistent behavior? I'd like to receive <em>empty string</em> as value of <em>empty element</em> (which <em>IS</em> what I put in XML structure in the first place).</p>
| 2 | 2009-07-27T11:46:32Z | 1,190,379 | <p>Cracking open xml.dom.minidom and searching for "/>", we find this:</p>
<pre><code># Method of the Element(Node) class.
def writexml(self, writer, indent="", addindent="", newl=""):
# [snip]
if self.childNodes:
writer.write(">%s"%(newl))
for node in self.childNodes:
node.writexml(writer,indent+addindent,addindent,newl)
writer.write("%s</%s>%s" % (indent,self.tagName,newl))
else:
writer.write("/>%s"%(newl))
</code></pre>
<p>We can deduce from this that the short-end-tag form only occurs when childNodes is an empty list. Indeed, this seems to be true:</p>
<pre><code>>>> doc = Document()
>>> v = doc.appendChild(doc.createElement('v'))
>>> v.toxml()
'<v/>'
>>> v.childNodes
[]
>>> v.appendChild(doc.createTextNode(''))
<DOM Text node "''">
>>> v.childNodes
[<DOM Text node "''">]
>>> v.toxml()
'<v></v>'
</code></pre>
<p>As pointed out by Lloyd, the XML spec makes no distinction between the two. If your code <em>does</em> make the distinction, that means you need to rethink how you want to serialize your data. </p>
<p>xml.dom.minidom simply displays something differently because it's easier to code. You can, however, get consistent output. Simply inherit the <code>Element</code> class and override the <code>toxml</code> method such that it will print out the short-end-tag form when there are no child nodes with non-empty text content. Then monkeypatch the module to use your new Element class.</p>
| 3 | 2009-07-27T20:17:32Z | [
"python",
"xml",
"string"
] |
How to exit from Python without traceback? | 1,187,970 | <p>I would like to know how to I exit from Python without having an traceback dump on the output. </p>
<p>I still want want to be able to return an error code but I do not want to display the traceback log.</p>
<p>I want to be able to exit using <code>exit(number)</code> without trace but in case of an Exception (not an exit) I want the trace.</p>
| 156 | 2009-07-27T12:44:15Z | 1,187,975 | <pre><code>import sys
sys.exit(1)
</code></pre>
| 30 | 2009-07-27T12:45:38Z | [
"python",
"exit",
"traceback"
] |
How to exit from Python without traceback? | 1,187,970 | <p>I would like to know how to I exit from Python without having an traceback dump on the output. </p>
<p>I still want want to be able to return an error code but I do not want to display the traceback log.</p>
<p>I want to be able to exit using <code>exit(number)</code> without trace but in case of an Exception (not an exit) I want the trace.</p>
| 156 | 2009-07-27T12:44:15Z | 1,187,976 | <p>something like <code>import sys; sys.exit(0)</code> ?</p>
| 6 | 2009-07-27T12:45:44Z | [
"python",
"exit",
"traceback"
] |
How to exit from Python without traceback? | 1,187,970 | <p>I would like to know how to I exit from Python without having an traceback dump on the output. </p>
<p>I still want want to be able to return an error code but I do not want to display the traceback log.</p>
<p>I want to be able to exit using <code>exit(number)</code> without trace but in case of an Exception (not an exit) I want the trace.</p>
| 156 | 2009-07-27T12:44:15Z | 1,188,086 | <p>You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).</p>
<p>Try something like this in your <code>main</code> routine:</p>
<pre><code>import sys, traceback
def main():
try:
do main program stuff here
....
except KeyboardInterrupt:
print "Shutdown requested...exiting"
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(0)
if __name__ == "__main__":
main()
</code></pre>
| 182 | 2009-07-27T13:10:40Z | [
"python",
"exit",
"traceback"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.