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
Python Eval: What's wrong with this code?
1,456,760
<p>I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code:</p> <pre><code>import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sys.argv[1]) result = 0 for line in handle : eval('result += 1 if ' + pred + ' else 0') print result </code></pre> <p>When I run it using <code>python count.py myFile.txt "int(line) == 0"</code>, I get the following error:</p> <pre><code> File "c:/pycode/count.py", line 10, in &lt;module&gt; eval('toAdd = 1 if ' + pred + ' else 0') File "&lt;string&gt;", line 1 toAdd = 1 if int(line) == 0 else 0 </code></pre> <p>This looks like perfectly valid Python code to me (though I've never used Python's eval before, so I don't know what its quirks, if any, are). Please tell me how I can fix this to make it work.</p>
2
2009-09-21T20:47:37Z
1,456,817
<p>try:</p> <pre><code>for line in handle: result += 1 if eval(pred) else 0 </code></pre>
5
2009-09-21T20:57:49Z
[ "python", "eval", "syntax-error" ]
Python Eval: What's wrong with this code?
1,456,760
<p>I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code:</p> <pre><code>import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sys.argv[1]) result = 0 for line in handle : eval('result += 1 if ' + pred + ' else 0') print result </code></pre> <p>When I run it using <code>python count.py myFile.txt "int(line) == 0"</code>, I get the following error:</p> <pre><code> File "c:/pycode/count.py", line 10, in &lt;module&gt; eval('toAdd = 1 if ' + pred + ' else 0') File "&lt;string&gt;", line 1 toAdd = 1 if int(line) == 0 else 0 </code></pre> <p>This looks like perfectly valid Python code to me (though I've never used Python's eval before, so I don't know what its quirks, if any, are). Please tell me how I can fix this to make it work.</p>
2
2009-09-21T20:47:37Z
1,456,827
<p>Really, you are looking for the compile function:</p> <pre><code>&gt;&gt; a = compile("toAdd = 1 if int('0') == 0 else 0", 'tmp2.py', 'exec') &gt;&gt;&gt; eval(a) &gt;&gt;&gt; toAdd 1 </code></pre> <p>eval is intended only for expressions... compile while compile sequence of statements into a codeblock that can then be eval'ed.</p>
0
2009-09-21T20:59:33Z
[ "python", "eval", "syntax-error" ]
Python Eval: What's wrong with this code?
1,456,760
<p>I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code:</p> <pre><code>import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sys.argv[1]) result = 0 for line in handle : eval('result += 1 if ' + pred + ' else 0') print result </code></pre> <p>When I run it using <code>python count.py myFile.txt "int(line) == 0"</code>, I get the following error:</p> <pre><code> File "c:/pycode/count.py", line 10, in &lt;module&gt; eval('toAdd = 1 if ' + pred + ' else 0') File "&lt;string&gt;", line 1 toAdd = 1 if int(line) == 0 else 0 </code></pre> <p>This looks like perfectly valid Python code to me (though I've never used Python's eval before, so I don't know what its quirks, if any, are). Please tell me how I can fix this to make it work.</p>
2
2009-09-21T20:47:37Z
1,456,860
<pre><code>#!/usr/bin/env python import fileinput, sys pred = eval('lambda line: ' + sys.argv[1]) print sum(1 for line in fileinput.input(sys.argv[2:]) if pred(line)) </code></pre> <p>Usage: <code>pywc.py predicate [FILE]...</code><br /> Print number of lines that satisfy <code>predicate</code> for given <code>FILE</code>(s).<br /> With no <code>FILE</code>, or when FILE is -, read standard input.</p>
3
2009-09-21T21:06:57Z
[ "python", "eval", "syntax-error" ]
Can Python encode a string to match ASP.NET membership provider's EncodePassword
1,456,770
<p>I'm working on a Python script to create hashed strings from an existing system similar to that of ASP.NET's MembershipProvider. Using Python, is there a way to take a hexadecimal string and convert it back to a binary and then do a base64 encoding, somehow treating the original string as Unicode. Let's try some code. I'm looking to re-encode a hashed password so that the hashes would be equal in Python and ASP.NET/C#:</p> <pre><code>import base64 import sha import binascii def EncodePassword(password): # strings are currently stored as hex hex_hashed_password = sha.sha(password).hexdigest() # attempt to convert hex to base64 bin_hashed_password = binascii.unhexlify(hex_hashed_password) return base64.standard_b64encode(bin_hashed_password) print EncodePassword("password") # W6ph5Mm5Pz8GgiULbPgzG37mj9g= </code></pre> <p>The ASP.NET MembershipProvider users this method to encode:</p> <pre><code>static string EncodePassword(string pass) { byte[] bytes = Encoding.Unicode.GetBytes(pass); //bytes = Encoding.ASCII.GetBytes(pass); byte[] inArray = null; HashAlgorithm algorithm = HashAlgorithm.Create("SHA1"); inArray = algorithm.ComputeHash(bytes); return Convert.ToBase64String(inArray); } string s = EncodePassword("password"); // 6Pl/upEE0epQR5SObftn+s2fW3M= </code></pre> <p>That doesn't match. But, when I run it with the password encoded with ASCII encoding, it matches, so the Unicode part of the .NET method is what's the difference.</p> <blockquote> <p>W6ph5Mm5Pz8GgiULbPgzG37mj9g=</p> </blockquote> <p>Is there a way in the python script to get an output to match the default .NET version?</p>
1
2009-09-21T20:49:41Z
1,457,539
<p>This is the trick:</p> <blockquote> <p>Encoding.Unicode</p> </blockquote> <p>“Unicode” encoding is confusing Microsoft-speak for UTF-16LE (specifically, without any BOM). Encode the string to that before hashing and you get the right answer:</p> <pre><code>&gt;&gt;&gt; import hashlib &gt;&gt;&gt; p= u'password' &gt;&gt;&gt; hashlib.sha1(p.encode('utf-16le')).digest().encode('base64') '6Pl/upEE0epQR5SObftn+s2fW3M=\n' </code></pre>
4
2009-09-22T00:14:44Z
[ "c#", ".net", "asp.net", "python", "unicode" ]
Implementation of set reconciliation algorithm
1,457,045
<p>I'm looking for implementations of set reconciliation algorithm. The problem is following: there are two sets with elements identified by some relatively compact value (e.g. UUID or MD5/SHA1/whatever hash) sitting on different machines. These sets differ in relatively few elements and I want to synchronize these sets while transferring minimal amount of data. Most of googling leads <a href="http://ipsit.bu.edu/programs/reconcile/">here</a>. This is GPL'd implementation of what seems to be the state-of-art approach to the task. The problem is that I can't use GPL'd code in my app. Most likely I'll have to reimplement it myself using something like nzmath, but maybe there are other implementations (preferably Python or C/C++), or maybe there are other nicer algorithms?</p>
6
2009-09-21T21:43:11Z
1,459,497
<p>Not being able to use GPL is often a matter of abstraction; that is if it is the license you have problems with. So if you create a small GPL application (released under GPL) you can call this from your non-GPL application. Why re-invent the wheel?</p> <p>Especially if you can use a python script which already exists: why not leverage it? Of course things are different if you can not expose the element reconsolidation algorithms.</p>
1
2009-09-22T11:28:12Z
[ "python", "c", "algorithm", "synchronization", "set" ]
Implementation of set reconciliation algorithm
1,457,045
<p>I'm looking for implementations of set reconciliation algorithm. The problem is following: there are two sets with elements identified by some relatively compact value (e.g. UUID or MD5/SHA1/whatever hash) sitting on different machines. These sets differ in relatively few elements and I want to synchronize these sets while transferring minimal amount of data. Most of googling leads <a href="http://ipsit.bu.edu/programs/reconcile/">here</a>. This is GPL'd implementation of what seems to be the state-of-art approach to the task. The problem is that I can't use GPL'd code in my app. Most likely I'll have to reimplement it myself using something like nzmath, but maybe there are other implementations (preferably Python or C/C++), or maybe there are other nicer algorithms?</p>
6
2009-09-21T21:43:11Z
1,603,692
<p>This code is out of my head, and thus covered by whatever license applies for code samples in this site.</p> <pre><code># given two finite sequences of unique and hashable data, # return needed opcodes and data needed for reconciliation def set_reconcile(src_seq, dst_seq): "Return required operations to mutate src_seq into dst_seq" src_set= set(src_seq) # no-op if already of type set dst_set= set(dst_seq) # ditto for item in src_set - dst_set: yield 'delete', item for item in dst_set - src_set: yield 'create', item </code></pre> <p>Use as follows:</p> <pre><code>for opcode, datum in set_reconcile(machine1_stuff, machine2_stuff): if opcode == 'create': # act accordingly elif opcode == 'delete': # likewise else: raise RuntimeError, 'unexpected opcode' </code></pre>
1
2009-10-21T21:13:57Z
[ "python", "c", "algorithm", "synchronization", "set" ]
Implementation of set reconciliation algorithm
1,457,045
<p>I'm looking for implementations of set reconciliation algorithm. The problem is following: there are two sets with elements identified by some relatively compact value (e.g. UUID or MD5/SHA1/whatever hash) sitting on different machines. These sets differ in relatively few elements and I want to synchronize these sets while transferring minimal amount of data. Most of googling leads <a href="http://ipsit.bu.edu/programs/reconcile/">here</a>. This is GPL'd implementation of what seems to be the state-of-art approach to the task. The problem is that I can't use GPL'd code in my app. Most likely I'll have to reimplement it myself using something like nzmath, but maybe there are other implementations (preferably Python or C/C++), or maybe there are other nicer algorithms?</p>
6
2009-09-21T21:43:11Z
27,048,441
<p>The <a href="https://bitbucket.org/skskeyserver/sks-keyserver/wiki/Home" rel="nofollow">Synchronizing Keyserver</a> project implements efficient set reconciliation in OCaml.</p>
0
2014-11-20T20:01:34Z
[ "python", "c", "algorithm", "synchronization", "set" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need to do is rename the contents such that I eliminate the #outputs column so that the end result is:</p> <pre><code>gatename #outputs list_of_inputs_separated_by_spaces * gate_id nand 2 10 11 * G0 or 1 10 * G1 </code></pre> <p>I tried using the find and replace function of Eclipse (the find parameter was a regex statement that didn't work), but it ended up messing up the gatename. I am considering using a Python script and iterating over each line of the text file. what I need help with is determining what the appropriate regex statement is. </p>
0
2009-09-21T21:54:45Z
1,457,127
<p>Personally, if it is this structured of a document, don't bother with a regex.</p> <p>Just loop through the file, do a split on the " " character, then simply omit the second entry.</p>
1
2009-09-21T22:01:34Z
[ "python", "regex", "eclipse" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need to do is rename the contents such that I eliminate the #outputs column so that the end result is:</p> <pre><code>gatename #outputs list_of_inputs_separated_by_spaces * gate_id nand 2 10 11 * G0 or 1 10 * G1 </code></pre> <p>I tried using the find and replace function of Eclipse (the find parameter was a regex statement that didn't work), but it ended up messing up the gatename. I am considering using a Python script and iterating over each line of the text file. what I need help with is determining what the appropriate regex statement is. </p>
0
2009-09-21T21:54:45Z
1,457,137
<p>Something like...:</p> <pre><code>for theline in fileinput.input(inplace=1): print re.sub(r'(\w+\s*+)\d+\s+(.*)', r'\1\2', theline), </code></pre> <p>...should meet your needs.</p>
2
2009-09-21T22:04:05Z
[ "python", "regex", "eclipse" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need to do is rename the contents such that I eliminate the #outputs column so that the end result is:</p> <pre><code>gatename #outputs list_of_inputs_separated_by_spaces * gate_id nand 2 10 11 * G0 or 1 10 * G1 </code></pre> <p>I tried using the find and replace function of Eclipse (the find parameter was a regex statement that didn't work), but it ended up messing up the gatename. I am considering using a Python script and iterating over each line of the text file. what I need help with is determining what the appropriate regex statement is. </p>
0
2009-09-21T21:54:45Z
1,457,142
<p>I don't know what platform you're using Eclipse on, but if it's linux or you have cygwin, cut is very fast!</p> <pre><code>cut -d" " --complement -f2 $FILE </code></pre> <p>This will use space as the delimiter, and select the complement of the second field.</p> <p>If you really want to use a regular expression, you can do something like this:</p> <pre><code>sed -r 's/^ *([^ ]+) +[^ ]+ +(.+)/\1 \2/' $FILE </code></pre> <p>You could easily use the same expression in python or perl, of course, but Mitchel's right - splitting is easy. (Unless the text is extremely long, and it'll waste time unnecessarily splitting other fields).</p>
0
2009-09-21T22:04:46Z
[ "python", "regex", "eclipse" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need to do is rename the contents such that I eliminate the #outputs column so that the end result is:</p> <pre><code>gatename #outputs list_of_inputs_separated_by_spaces * gate_id nand 2 10 11 * G0 or 1 10 * G1 </code></pre> <p>I tried using the find and replace function of Eclipse (the find parameter was a regex statement that didn't work), but it ended up messing up the gatename. I am considering using a Python script and iterating over each line of the text file. what I need help with is determining what the appropriate regex statement is. </p>
0
2009-09-21T21:54:45Z
1,457,153
<p>This is basically what the <code>cut</code> utility is for:</p> <pre><code>cut -d " " -f 1,3- </code></pre> <p>(update: I forgot the <code>-f</code> option, sorry.)</p> <p>This takes a file, considers fields delimited by spaces, and outputs the first, third and following fields.</p> <p>(If you're on Windows, you should have these <a href="http://getgnuwin32.sourceforge.net/" rel="nofollow">unix-style utilities</a> anyway, they can be incredibly useful.)</p> <p>Using a regex, you could replace <code>(\w+) \d+ (.*)</code> with <code>$1 $2</code>. Something like:</p> <pre><code>sed -r -e "s/([^ ]+) [0-9]+ (.*)/\1 \2/" file </code></pre> <p>or</p> <pre><code>perl -p -e "s/(\w+) \d+ (.*)/\1 $2/" file </code></pre>
4
2009-09-21T22:07:09Z
[ "python", "regex", "eclipse" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need to do is rename the contents such that I eliminate the #outputs column so that the end result is:</p> <pre><code>gatename #outputs list_of_inputs_separated_by_spaces * gate_id nand 2 10 11 * G0 or 1 10 * G1 </code></pre> <p>I tried using the find and replace function of Eclipse (the find parameter was a regex statement that didn't work), but it ended up messing up the gatename. I am considering using a Python script and iterating over each line of the text file. what I need help with is determining what the appropriate regex statement is. </p>
0
2009-09-21T21:54:45Z
1,457,179
<p>You can indeed use Eclipse's find and replace feature, using the following:</p> <pre><code>Find: ^([a-z]+) \d Replace with: \1 </code></pre> <p>This is essentially matching the gatename at the beginning of each line (<code>^([a-z]+)</code>) followed by the output (<code> \d</code>), and replacing it with just the matched gatename (<code>\1</code>).</p>
1
2009-09-21T22:14:39Z
[ "python", "regex", "eclipse" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
1,457,852
<p>This behavior is almost certainly because your files are not named in accordance with nose's test matching behavior. From <a href="https://nose.readthedocs.org/en/latest/usage.html#extended-usage">the nose docs</a>:</p> <blockquote> <p>nose collects tests automatically from python source files, directories and packages found in its working directory (which defaults to the current working directory). <strong>Any python source file, directory or package that matches the testMatch regular expression (by default: (?:^|[b_.-])[Tt]est) will be collected as a test</strong> (or source for collection of tests).</p> </blockquote> <p>Emphasis was mine.</p> <p>Some example names that would match:</p> <ul> <li>TestFoo.py</li> <li>Foo-Test.py</li> <li>Foo_Test.py</li> <li>Foo.Test.py (note that this one will try to import Foo, and will raise an exception if it cannot)</li> </ul> <p>A name that <em>looks</em> like it would match, but actually does not:</p> <ul> <li>FooTest.py</li> </ul> <p>If you just rename your files you should be good to go.</p> <p><hr> <strong>Update</strong>: Have you read <a href="http://jgeewax.wordpress.com/2009/09/05/nose-gae-runtest-no-such-method-valueerror/">this blog post</a>? I wasn't able to tell from the details you've posted, but maybe your test directories are missing their <code>__init__.py</code> files?</p> <blockquote> <p>... make sure that your “tests” directories are actually modules (they have an empty <code>__init__.py</code> file).</p> </blockquote>
47
2009-09-22T02:24:24Z
[ "python", "nose", "nosetests" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
1,579,787
<p>The other thing which <em>always</em> gets me with <code>nose</code> is that it won't run tests in executable files. I'm not exactly sure why that would make a difference across Mac/Ubuntu, but it's worth a shot.</p> <p>Make sure that the scripts didn't somehow get <code>chmod +x</code>'d on the Mac… And if they did, fix them with <code>chmod -x $(find tests/ -name '*.py')</code>.</p>
70
2009-10-16T18:57:16Z
[ "python", "nose", "nosetests" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
5,644,762
<p>I can confirm that as @david-wolever said, they <strong>cannot</strong> be executable on Ubuntu. Run</p> <pre><code>nosetests -vv --collect-only </code></pre> <p>to see full details on which files were examined.</p>
14
2011-04-13T05:22:34Z
[ "python", "nose", "nosetests" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
7,410,349
<p>I had the same problem. My tests ran just fine in Windows, but not in Ubuntu.</p> <p>In Ubuntu, if you run:</p> <pre><code>nosetests -vv --collect-only </code></pre> <p>You'll probably see that it's skipping your test file because it's an executable: _Tools/LintControlFiles/test_HgLint.py <strong>is executable; skipped</strong></p> <p>In order to get nose to consider executables, run it like this:</p> <pre><code>nosetests --exe </code></pre>
25
2011-09-14T01:34:38Z
[ "python", "nose", "nosetests" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
18,860,584
<p>Some what related, if you're running tests off of a directory i.e </p> <pre><code>nosetests ... tests/ </code></pre> <p>where tests is the name of the folder with my tests, and have separate python test functions in one of the .py modules... Your functions have to start with 'test' for nosetests to recognize that as a test you want to run. </p> <p>for example:</p> <pre><code> def test_something(): ... </code></pre> <p>nosetests will run this function when executed in this directory while</p> <pre><code> def somethin_to_test(): ... </code></pre> <p>would not.</p>
3
2013-09-17T21:55:35Z
[ "python", "nose", "nosetests" ]
How do I find the name of the file that is the importer, within the imported file?
1,457,308
<p>How do I find the name of the file that is the "importer", within the imported file?</p> <p>If <code>a.py</code> and <code>b.py</code> both import <code>c.py</code>, is there anyway that c.py can know the name of the file importing it?</p>
2
2009-09-21T22:56:31Z
1,457,354
<p>In the top-level of c.py (i.e. outside of any function or class), you should be able to get the information you need by running</p> <pre><code>import traceback </code></pre> <p>and then examining the result of traceback.extract_stack(). At the time that top-level code is run, the importer of the module (and its importer, etc. recursively) are all on the callstack.</p>
1
2009-09-21T23:11:20Z
[ "python", "import" ]
How do I find the name of the file that is the importer, within the imported file?
1,457,308
<p>How do I find the name of the file that is the "importer", within the imported file?</p> <p>If <code>a.py</code> and <code>b.py</code> both import <code>c.py</code>, is there anyway that c.py can know the name of the file importing it?</p>
2
2009-09-21T22:56:31Z
1,457,358
<p>It can be done by <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspecting</a> the stack:</p> <pre><code>#inside c.py: import inspect FRAME_FILENAME = 1 print "Imported from: ", inspect.getouterframes(inspect.currentframe())[-1][FRAME_FILENAME] #or: print "Imported from: ", inspect.stack()[-1][FRAME_FILENAME] </code></pre> <p>But inspecting the stack can be buggy. Why do you need to know where a file is being imported from? Why not have the file that does the importing (<code>a.py</code> and <code>b.py</code>) pass in a name into <code>c.py</code>? (assuming you have control of <code>a.py</code> and <code>b.py</code>)</p>
1
2009-09-21T23:13:54Z
[ "python", "import" ]
How do I find the name of the file that is the importer, within the imported file?
1,457,308
<p>How do I find the name of the file that is the "importer", within the imported file?</p> <p>If <code>a.py</code> and <code>b.py</code> both import <code>c.py</code>, is there anyway that c.py can know the name of the file importing it?</p>
2
2009-09-21T22:56:31Z
1,457,700
<p>That's why you have parameters.</p> <p>It's not the job of <code>c.py</code> to determine who imported it.</p> <p>It's the job of <code>a.py</code> or <code>b.py</code> to pass the variable <code>__name__</code> to the functions or classes in <code>c.py</code>.</p>
2
2009-09-22T01:25:09Z
[ "python", "import" ]
How do I find the name of the file that is the importer, within the imported file?
1,457,308
<p>How do I find the name of the file that is the "importer", within the imported file?</p> <p>If <code>a.py</code> and <code>b.py</code> both import <code>c.py</code>, is there anyway that c.py can know the name of the file importing it?</p>
2
2009-09-21T22:56:31Z
1,457,942
<p>Use</p> <p>sys.path[0]</p> <p>returns the path of the script that launched the python interpreter. If you can this script directly, it will return the path of the script. If the script however, was imported from another script, it will return the path of that script.</p> <p>See <a href="http://arcoleo.org/dsawiki/Wiki.jsp?page=Python%20Path%20Issues" rel="nofollow" title="Python Path Issues">Python Path Issues</a></p>
1
2009-09-22T03:11:06Z
[ "python", "import" ]
TurtleGraphics Python: Bouncing turtle off the walls?
1,457,332
<p>So, I am trying to make a realistic bouncing function, where the turtle hits a wall and bounces off at the corresponding angle. My code looks like this:</p> <pre><code>def bounce(num_steps, step_size, initial_heading): turtle.reset() top = turtle.window_height()/2 bottom = -top right = turtle.window_width()/2 left = -right turtle.left(initial_heading) for step in range(num_steps): turtle.forward(step_size) x, y = turtle.position() if left &lt;= x &lt;= right and bottom &lt;= y &lt;= top: pass else: turtle.left(180-2 * (turtle.heading())) </code></pre> <p>So, this works for the side walls, but I don't get how to make it bounce correctly off the top/bottom. Any suggestions?</p>
1
2009-09-21T23:04:29Z
1,457,659
<p>Try something like this:</p> <pre><code>if not (left &lt;= x &lt;= right): turtle.left(180 - 2 * turtle.heading()) elif not (bottom &lt;= y &lt;= top): turtle.left(-2 * turtle.heading()) else: pass </code></pre> <p>My python syntax is a little rusty, sorry :P. But the math is a little different for a horizontal vs. a vertical flip.</p> <p><strong>EDIT</strong>:</p> <p>I suspect that what is happening is your turtle is getting into a situation where it is pointing upwards and stuck above the top wall. That would lead it to just flip indefinitely. You could try adding the following conditions:</p> <pre><code>if (x &lt;= left and 90 &lt;= turtle.heading() &lt;= 270) or (right &lt;= x and not 90 &lt;= turtle.heading() &lt;= 270): turtle.left(180 - 2 * turtle.heading()) elif (y &lt;= bottom and turtle.heading() &gt;= 180) or (top &lt;= y and turtle.heading &lt;= 180): turtle.left(-2 * turtle.heading()) else: pass </code></pre> <p>If that works, there is probably a bug elsewhere in your code. Edge handling is tricky to get right. I assume that turtle.heading() will always return something between 0 and 360 - if not then it will be even more tricky to get right.</p>
1
2009-09-22T01:02:33Z
[ "python", "turtle-graphics" ]
TurtleGraphics Python: Bouncing turtle off the walls?
1,457,332
<p>So, I am trying to make a realistic bouncing function, where the turtle hits a wall and bounces off at the corresponding angle. My code looks like this:</p> <pre><code>def bounce(num_steps, step_size, initial_heading): turtle.reset() top = turtle.window_height()/2 bottom = -top right = turtle.window_width()/2 left = -right turtle.left(initial_heading) for step in range(num_steps): turtle.forward(step_size) x, y = turtle.position() if left &lt;= x &lt;= right and bottom &lt;= y &lt;= top: pass else: turtle.left(180-2 * (turtle.heading())) </code></pre> <p>So, this works for the side walls, but I don't get how to make it bounce correctly off the top/bottom. Any suggestions?</p>
1
2009-09-21T23:04:29Z
1,458,020
<p>Gday,</p> <p>Your problem seems to be that you are using the same trigonometry to calculate the right and left walls, as you are the top and bottom. A piece of paper and a pencil should suffice to calculate the required deflections. </p> <pre><code>def inbounds(limit, value): 'returns boolean answer to question "is turtle position within my axis limits"' return -limit &lt; value * 2 &lt; limit def bounce(num_steps, step_size, initial_heading): '''given the number of steps, the size of the steps and an initial heading in degrees, plot the resultant course on a turtle window, taking into account elastic collisions with window borders. ''' turtle.reset() height = turtle.window_height() width = turtle.window_width() turtle.left(initial_heading) for step in xrange(num_steps): turtle.forward(step_size) x, y = turtle.position() if not inbounds(height, y): turtle.setheading(-turtle.heading()) if not inbounds(width, x): turtle.setheading(180 - turtle.heading()) </code></pre> <p>I've used the <code>setheading</code> function and a helper function (<code>inbounds</code>) to further declare the intent of the code here. Providing some kind of doc-string is also good practice in any code that you write (provided the message it states is accurate!!)</p> <p>Your mileage may vary on the use of <code>xrange</code>, Python 3.0+ renames it to simply <code>range</code>.</p>
0
2009-09-22T03:47:19Z
[ "python", "turtle-graphics" ]
python shell command - why won't it work?
1,457,757
<p>I wonder if anyone has any insights into this. I have a bash script that should put my ssh key onto a remote machine. Adopted from <a href="http://www.macosxhints.com/article.php?story=2007091814022049" rel="nofollow">here</a>, the script reads,</p> <pre><code>#!/usr/bin/sh REMOTEHOST=user@remote KEY="$HOME/.ssh/id_rsa.pub" KEYCODE=`cat $KEY` ssh -q $REMOTEHOST "mkdir ~/.ssh 2&gt;/dev/null; chmod 700 ~/.ssh; echo "$KEYCODE" &gt;&gt; ~/.ssh/authorized_keys; chmod 644 ~/.ssh/authorized_keys" </code></pre> <p>This works. The equivalent python script should be</p> <pre><code>#!/usr/bin/python import os os.system('ssh -q %(REMOTEHOST)s "mkdir ~/.ssh 2&gt;/dev/null; chmod 700 ~/.ssh; echo "%(KEYCODE)s" &gt;&gt; ~/.ssh/authorized_keys; chmod 644 ~/.ssh/authorized_keys"' % {'REMOTEHOST':'user@remote', 'KEYCODE':open(os.path.join(os.environ['HOME'], '.ssh/id_rsa.pub'),'r').read()}) </code></pre> <p>But in this case, I get that</p> <pre><code>sh: line 1: &gt;&gt; ~/.ssh/authorized_keys; chmod 644 ~/.ssh/authorized_keys: No such file or directory </code></pre> <p>What am I doing wrong? I tried escaping the inner-most quotes but same error message... Thank you in advance for your responses.</p>
1
2009-09-22T01:51:11Z
1,457,789
<p>You have a serious question -- in that <code>os.system</code> isn't behaving the way you expect it to -- but also, you should seriously rethink the approach as a whole.</p> <p>You're launching a Python interpreter -- but then, via <code>os.system</code>, telling that Python interpreter to launch a shell! <code>os.system</code> shouldn't be used at all in modern Python (<code>subprocess</code> is a complete replacement)... but using any Python call which starts a shell instance is exceptionally silly in this kind of use case.</p> <p>Now, in terms of the actual, immediate problem -- look at how your quotation marks are nesting. You'll see that the quote you're starting before <code>mkdir</code> is being closed in the <code>echo</code>, allowing your command to be split in a spot you don't intend.</p> <p>The following fixes this immediate issue, but is still awful and evil (starts a subshell unnecessarily, doesn't properly check output status, and should be converted to use <code>subprocess.Popen()</code>):</p> <pre><code>os.system('''ssh -q %(REMOTEHOST)s "mkdir ~/.ssh 2&gt;/dev/null; chmod 700 ~/.ssh; echo '%(KEYCODE)s' &gt;&gt; ~/.ssh/authorized_keys; chmod 644 ~/.ssh/authorized_keys"''' % { 'REMOTEHOST':'user@remote', 'KEYCODE':open(os.path.join(os.environ['HOME'], '.ssh/id_rsa.pub'),'r').read() }) </code></pre>
5
2009-09-22T01:59:17Z
[ "python", "shell" ]
Get every combination of strings
1,457,814
<p>I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings.</p> <p>In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem is that I can't get a good algorithm that would actually compute every possible option.</p> <p>If anyone could help, I'd appreciate it. I usually program in Python but really I just need help with the algorithm.</p>
3
2009-09-22T02:09:25Z
1,457,836
<p>Assuming you DO mean combinations (no repetitions, order does not matter):</p> <pre><code>import itertools S = [ 'a', 'ab', 'ba' ] for i in range(len(S)+1): for c in itertools.combinations(S, i): cc = ''.join(c) if len(cc) &lt;= 6: print c </code></pre> <p>emits all the possibilities:</p> <pre><code>() ('a',) ('ab',) ('ba',) ('a', 'ab') ('a', 'ba') ('ab', 'ba') ('a', 'ab', 'ba') </code></pre> <p>If you mean something different than "combinations", it's just an issue of using the right iterator or generator in the <code>for</code> (e.g., <code>itertools.permutations</code>, or something else of your own devising).</p> <p><strong>Edit</strong>: if for example you mean "repetitions and order ARE important",</p> <pre><code>def reps(seq, n): return itertools.product(*[seq]*n) for i in range(7): for c in reps(S, i): cc = ''.join(c) if len(cc) &lt;= 6: print c </code></pre> <p>will give you the required 85 lines of output.</p> <p><strong>Edit again</strong>: I had the wrong loop limit (and therefore wrong output length) -- tx to the commenter who pointed that out. Also, this approach can produce a string > 1 times, if the ''.join's of different tuples are considered equivalent; e.g., it produces ('a', 'ba') as distinct from ('ab', 'a') although their ''.join is the same (same "word" from different so-called "combinations", I guess -- terminology in use not being entirely clear).</p>
8
2009-09-22T02:17:59Z
[ "python", "string", "combinatorics" ]
Get every combination of strings
1,457,814
<p>I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings.</p> <p>In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem is that I can't get a good algorithm that would actually compute every possible option.</p> <p>If anyone could help, I'd appreciate it. I usually program in Python but really I just need help with the algorithm.</p>
3
2009-09-22T02:09:25Z
1,457,875
<p>You can iteratively generate all the strings made from one part, two parts, three parts and so on, until all the strings generated in a step are longer than six characters. Further steps would only generate even longer strings, so all possible short strings have already been generated. If you collect these short strings in each step you end up with a set of all possible generated short strings.</p> <p>In Python:</p> <pre><code>S = set(['a', 'ab', 'ba']) collect = set() step = set(['']) while step: step = set(a+b for a in step for b in S if len(a+b) &lt;= 6) collect |= step print sorted(collect) </code></pre>
6
2009-09-22T02:34:30Z
[ "python", "string", "combinatorics" ]
Get every combination of strings
1,457,814
<p>I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings.</p> <p>In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem is that I can't get a good algorithm that would actually compute every possible option.</p> <p>If anyone could help, I'd appreciate it. I usually program in Python but really I just need help with the algorithm.</p>
3
2009-09-22T02:09:25Z
1,457,927
<p>Doing it recursively is one way:</p> <pre><code>cache = {} def words_of_length(s, n=6): # memoise results if n in cache: return cache[n] # base cases if n &lt; 0: return [] if n == 0: return [""] # inductive case res = set() for x in s: res |= set( (x+y for y in words_of_length(s, n-len(x))) ) # sort and memoise result cache[n] = sorted(res) # sort results return cache[n] def words_no_longer_than(s, n=6): return sum( [words_of_length(s, i) for i in range(n+1)], [] ) </code></pre>
1
2009-09-22T03:03:02Z
[ "python", "string", "combinatorics" ]
Get every combination of strings
1,457,814
<p>I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings.</p> <p>In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem is that I can't get a good algorithm that would actually compute every possible option.</p> <p>If anyone could help, I'd appreciate it. I usually program in Python but really I just need help with the algorithm.</p>
3
2009-09-22T02:09:25Z
1,457,982
<pre><code>def combos(S,n): if (n &lt;= 0): return for s in S: if len(s) &lt;= n: yield s for t in combos(S,n-len(s)): yield s+t for x in combos(["a","ab","ba"],6): print x </code></pre> <p>Prints output:</p> <pre><code>a aa aaa aaaa aaaaa aaaaaa aaaaab aaaaba aaaab aaaaba aaaba aaabaa aaab aaaba aaabaa aaabab aaabba aaba aabaa aabaaa aabaab aababa aab aaba aabaa aabaaa aabaab aababa aabab aababa aabba aabbaa aba abaa abaaa abaaaa abaaab abaaba abaab abaaba ababa ababaa ab aba abaa abaaa abaaaa abaaab abaaba abaab abaaba ababa ababaa abab ababa ababaa ababab ababba abba abbaa abbaaa abbaab abbaba ba baa baaa baaaa baaaaa baaaab baaaba baaab baaaba baaba baabaa baab baaba baabaa baabab baabba baba babaa babaaa babaab bababa </code></pre>
3
2009-09-22T03:28:38Z
[ "python", "string", "combinatorics" ]
Python socket programming and ISO-OSI model
1,458,087
<p>I am sending packets from one pc to other. I am using python socket <code>socket.socket(socket.AF_INET, socket.SOCK_DGRAM )</code>. Do we need to take care of order in which packets are received ? In ISO-OSI model layers below transport layer handle all packets communication. Do all ISO-OSI layers present in the program ? Or some of them present in operating system ? On localhost I get all packets in order. Will it make any difference over internet ? </p>
1
2009-09-22T04:23:42Z
1,458,109
<p><code>SOCK_DGRAM</code> means you want to send packets by UDP -- no order guarantee, no guarantee of reception, no guarantee of lack of repetition. <code>SOCK_STREAM</code> would imply TCP -- no packet boundary guarantee, but (unless the connection's dropped;-) guarantee of order, reception, and no duplication. TCP/IP, <strong>the</strong> networking model that won the heart and soul of every live practitioned and made the Internet happen, is <strong>not</strong> compliant to ISO/OSI -- a standard designed at the drafting table and never really winning in the real world.</p> <p>The Internet as she lives and breathes is TCP/IP all the way. Don't rely on tests done on a low-latency local network as in ANY way representative of what will happen out there in the real world. Welcome to the real world, BTW, and, good luck (you'll need <em>some</em>!-).</p>
4
2009-09-22T04:31:25Z
[ "python", "sockets" ]
Python socket programming and ISO-OSI model
1,458,087
<p>I am sending packets from one pc to other. I am using python socket <code>socket.socket(socket.AF_INET, socket.SOCK_DGRAM )</code>. Do we need to take care of order in which packets are received ? In ISO-OSI model layers below transport layer handle all packets communication. Do all ISO-OSI layers present in the program ? Or some of them present in operating system ? On localhost I get all packets in order. Will it make any difference over internet ? </p>
1
2009-09-22T04:23:42Z
1,458,734
<p>To answer your immediate question, if you're using *SOCK_STREAM*, then you're actually using TCP, which is an implementation of the transport layer which <strong>does</strong> take care of packet ordering and integrity for you. So it sounds like that's what you want to use. *SOCK_DGRAM* is actually UDP, which doesn't take care of any integrity for you.</p> <blockquote> <p>Do we need to take care of order in which packets are received ? In ISO-OSI model layers below transport layer handle all packets communication. Do all ISO-OSI layers present in the program ?</p> </blockquote> <p>Just to clear this up, in the ISO-OSI model, all the layers below the transport layer handle sending of a <strong>single</strong> packet from one computer to the other, and don't "understand" the concept of packet ordering (it doesn't apply to them).</p> <p>In this model, there is another layer (the session layer, above the transport layer) which is responsible for defining the session behavior. It is this layer which decides whether to have things put in place to prevent reordering, to ensure integrity, and so on.</p> <p>In the modern world, the ISO-OSI model is more of an idealistic template, rather than an actual model. TCP/IP is the actual implementation which is used almost everywhere.</p> <p>In TCP/IP, the <strong>transport layer</strong> is the one that has the role of defining whether there is any session behavior or not.</p>
2
2009-09-22T08:13:11Z
[ "python", "sockets" ]
Reading a float from string
1,458,203
<p>I have a simple string that I want to read into a float without losing any <strong>visible</strong> information as illustrated below:</p> <pre><code>s = ' 1.0000\n' </code></pre> <p>When I do <code>f = float(s)</code>, I get <code>f=1.0</code></p> <p>How to trick this to get <code>f=1.0000</code> ?</p> <p>Thank you</p>
1
2009-09-22T05:13:00Z
1,458,217
<p><strong>Direct answer</strong>: You can't. Floats are imprecise, by design. While python's floats have more than enough precision to represent 1.0000, they will <em>never</em> represent a "1-point-zero-zero-zero-zero". Chances are, this is as good as you need. You can always use string formatting, if you need to display four decimal digits.</p> <pre><code>print '%.3f' % float(1.0000) </code></pre> <p><strong>Indirect answer</strong>: Use the <code>decimal</code> module.</p> <pre><code>from decimal import Decimal d = Decimal('1.0000') </code></pre> <p>The <code>decimal</code> package is designed to handle all these issues with arbitrary precision. A decimal "1.0000" is <em>exactly</em> 1.0000, no more, no less. Note, however, that complications with rounding means you can't convert from a <code>float</code> directly to a <code>Decimal</code>; you have to pass a string (or an integer) to the constructor. </p>
9
2009-09-22T05:17:00Z
[ "python", "string", "floating-point" ]
Reading a float from string
1,458,203
<p>I have a simple string that I want to read into a float without losing any <strong>visible</strong> information as illustrated below:</p> <pre><code>s = ' 1.0000\n' </code></pre> <p>When I do <code>f = float(s)</code>, I get <code>f=1.0</code></p> <p>How to trick this to get <code>f=1.0000</code> ?</p> <p>Thank you</p>
1
2009-09-22T05:13:00Z
1,458,226
<pre><code>&gt;&gt;&gt; 1.0 == 1.00 == 1.000 True </code></pre> <p>In other words, you're losing no info -- Python considers trailing zeros in floats' decimal parts to be irrelevant. If you need to keep track very specifically of "number of significant digits", that's also feasible, but you'll need to explain to us all exactly what you're trying to accomplish beyond Python's normal <code>float</code> (e.g., would <code>decimal</code> in the Python standard library have anything to do with it? etc, etc...).</p>
5
2009-09-22T05:18:46Z
[ "python", "string", "floating-point" ]
Reading a float from string
1,458,203
<p>I have a simple string that I want to read into a float without losing any <strong>visible</strong> information as illustrated below:</p> <pre><code>s = ' 1.0000\n' </code></pre> <p>When I do <code>f = float(s)</code>, I get <code>f=1.0</code></p> <p>How to trick this to get <code>f=1.0000</code> ?</p> <p>Thank you</p>
1
2009-09-22T05:13:00Z
1,458,306
<p>Indulge me while I reinvent the wheel a little bit! ;)</p> <p>Should you want the <code>repr</code>sentation of the object (the way it is displayed in the shell) to have the form 1.0000 then you may need to change the <code>__repr__</code> method of the float. If you would like the object to be printed to a file or screen you will need to change the <code>__str__</code> method. Here is a class that will do both.</p> <pre><code>class ExactFloat(float): def __repr__(self): return '%.4f' % self __str__ = __repr__ # usage of the shiny new class to follow.. &gt;&gt;&gt; f = ExactFloat(' 1.0000\n') &gt;&gt;&gt; f 1.0000 &gt;&gt;&gt; print f 1.0000 </code></pre> <p>Now there are also a myriad of other <code>better</code> ways to do this, but like I said, I love re-inventing wheels :)</p>
1
2009-09-22T05:46:58Z
[ "python", "string", "floating-point" ]
Reading a float from string
1,458,203
<p>I have a simple string that I want to read into a float without losing any <strong>visible</strong> information as illustrated below:</p> <pre><code>s = ' 1.0000\n' </code></pre> <p>When I do <code>f = float(s)</code>, I get <code>f=1.0</code></p> <p>How to trick this to get <code>f=1.0000</code> ?</p> <p>Thank you</p>
1
2009-09-22T05:13:00Z
1,459,292
<p>Here's an even shinier version of @Simon Edwards' <code>ExactFloat</code>, that counts the number of digits after the period and displays that number of digits when the number is converted to a string.</p> <pre><code>import re class ExactFloat(float): def __init__(self, str_value): float.__init__(self, str_value) mo = re.match("^\d+\.(\d+)", str_value) self.digits_after_period = len(mo.group(1)) def __repr__(self): return '%.*f' % (self.digits_after_period, self) def __str__(self): return self.__repr__() print ExactFloat("1.000") print ExactFloat("1.0") print ExactFloat("23.234500") </code></pre> <p>Example:</p> <pre><code>$ python exactfloat.py 1.000 1.0 23.234500 </code></pre>
1
2009-09-22T10:32:59Z
[ "python", "string", "floating-point" ]
With python.multiprocessing, how do I create a proxy in the current process to pass to other processes?
1,458,205
<p>I'm using the <code>multiprocessing</code> library in Python. I can see how to define that objects <em>returned</em> from functions should have proxies created, but I'd like to have objects in the current process turned into proxies so I can pass them as parameters.</p> <p>For example, running the following script:</p> <pre><code>from multiprocessing import current_process from multiprocessing.managers import BaseManager class ProxyTest(object): def call_a(self): print 'A called in %s' % current_process() def call_b(self, proxy_test): print 'B called in %s' % current_process() proxy_test.call_a() class MyManager(BaseManager): pass MyManager.register('proxy_test', ProxyTest) if __name__ == '__main__': manager = MyManager() manager.start() pt1 = ProxyTest() pt2 = manager.proxy_test() pt1.call_a() pt2.call_a() pt1.call_b(pt2) pt2.call_b(pt1) </code></pre> <p>... I get the following output ...</p> <pre><code>A called in &lt;_MainProcess(MainProcess, started)&gt; A called in &lt;Process(MyManager-1, started)&gt; B called in &lt;_MainProcess(MainProcess, started)&gt; A called in &lt;Process(MyManager-1, started)&gt; B called in &lt;Process(MyManager-1, started)&gt; A called in &lt;Process(MyManager-1, started)&gt; </code></pre> <p>... but I want that final line of output coming from <code>_MainProcess</code>. </p> <p>I could just create another Process and run it from there, but I'm trying to keep the amount of data that needs to be passed between processes to a minimum. The documentation for the <code>Manager</code> object mentioned a <code>serve_forever</code> method, but it doesn't seem to be supported. Any ideas? Does anyone know?</p>
2
2009-09-22T05:13:08Z
1,486,301
<p>Why do you say *serve_forever* is not supported?</p> <pre><code>manager = Mymanager() s = manager.get_server() s.serve_forever() </code></pre> <p>should work.</p> <p>See <strong>*<a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.managers.BaseManager.get%5Fserver" rel="nofollow">managers.BaseManager.get_server</a>*</strong> doc for official examples.</p>
1
2009-09-28T10:12:23Z
[ "python", "proxy", "multiprocessing", "manager" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = parent # This must be a gwebpage instance self.xpath = None # String self.visibleShingles = [] # list of tuples self.invisibleShingles = [] # list of tuples self.urls = [] # list of string class gwebpage: """ Holds all the datastructure after the results have been parsed holds: 1) lists of gpagelets 2) loc, string, location of the file that represents it """ def __init__(self, url): self.url = url # Str self.netloc = False # Str self.gpagelets = [] # gpagelets instance self.page_key = "" # str </code></pre> <p>Is there a way for me to make my class json serializable? The thing that I am worried is the recursive reference.</p>
22
2009-09-22T06:37:10Z
1,458,677
<p>Indirect answer: instead of using JSON, you could use <a href="http://pyyaml.org/wiki/PyYAMLDocumentation" rel="nofollow">YAML</a>, which has no problem doing what you want. (JSON is essentially a subset of YAML.)</p> <p>Example:</p> <pre><code>import yaml o1 = gwebpage("url") o2 = gpagelet(o1) o1.gpagelets = [o2] print yaml.dump(o1) </code></pre> <p>In fact, YAML nicely handles cyclic references for you.</p>
5
2009-09-22T07:48:29Z
[ "python", "json", "serializable" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = parent # This must be a gwebpage instance self.xpath = None # String self.visibleShingles = [] # list of tuples self.invisibleShingles = [] # list of tuples self.urls = [] # list of string class gwebpage: """ Holds all the datastructure after the results have been parsed holds: 1) lists of gpagelets 2) loc, string, location of the file that represents it """ def __init__(self, url): self.url = url # Str self.netloc = False # Str self.gpagelets = [] # gpagelets instance self.page_key = "" # str </code></pre> <p>Is there a way for me to make my class json serializable? The thing that I am worried is the recursive reference.</p>
22
2009-09-22T06:37:10Z
1,458,716
<p>Write your own encoder and decoder, which can be very simple like <code>return __dict__</code></p> <p>e.g. here is a encoder to dump totally recursive tree structure, you can enhance it or use as it is for your own purpose</p> <pre><code>import json class Tree(object): def __init__(self, name, childTrees=None): self.name = name if childTrees is None: childTrees = [] self.childTrees = childTrees class MyEncoder(json.JSONEncoder): def default(self, obj): if not isinstance(obj, Tree): return super(MyEncoder, self).default(obj) return obj.__dict__ c1 = Tree("c1") c2 = Tree("c2") t = Tree("t",[c1,c2]) print json.dumps(t, cls=MyEncoder) </code></pre> <p>it prints </p> <pre><code>{"childTrees": [{"childTrees": [], "name": "c1"}, {"childTrees": [], "name": "c2"}], "name": "t"} </code></pre> <p>you can similarly write a decoder but there you will somehow need to identify is it is your object or not, so may be you can put a type too if needed.</p>
42
2009-09-22T08:06:26Z
[ "python", "json", "serializable" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = parent # This must be a gwebpage instance self.xpath = None # String self.visibleShingles = [] # list of tuples self.invisibleShingles = [] # list of tuples self.urls = [] # list of string class gwebpage: """ Holds all the datastructure after the results have been parsed holds: 1) lists of gpagelets 2) loc, string, location of the file that represents it """ def __init__(self, url): self.url = url # Str self.netloc = False # Str self.gpagelets = [] # gpagelets instance self.page_key = "" # str </code></pre> <p>Is there a way for me to make my class json serializable? The thing that I am worried is the recursive reference.</p>
22
2009-09-22T06:37:10Z
11,023,172
<p><a href="http://jsonpickle.github.com/">jsonpickle</a> FOR THE WIN!</p> <p>(Just had this same question... json pickle handles recursive/nested object graphs as well as short circuits for cyclical object graphs).</p>
12
2012-06-13T20:57:33Z
[ "python", "json", "serializable" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = parent # This must be a gwebpage instance self.xpath = None # String self.visibleShingles = [] # list of tuples self.invisibleShingles = [] # list of tuples self.urls = [] # list of string class gwebpage: """ Holds all the datastructure after the results have been parsed holds: 1) lists of gpagelets 2) loc, string, location of the file that represents it """ def __init__(self, url): self.url = url # Str self.netloc = False # Str self.gpagelets = [] # gpagelets instance self.page_key = "" # str </code></pre> <p>Is there a way for me to make my class json serializable? The thing that I am worried is the recursive reference.</p>
22
2009-09-22T06:37:10Z
31,060,745
<p>My solution for this was to extend the 'dict' class and perform checks around required/allowed attributes by overriding init, update, and set class methods.</p> <pre><code>class StrictDict(dict): required=set() at_least_one_required=set() cannot_coexist=set() allowed=set() def __init__(self, iterable={}, **kwargs): super(StrictDict, self).__init__({}) keys = set(iterable.keys()).union(set(kwargs.keys())) if not keys.issuperset(self.required): msg = str(self.__class__.__name__) + " requires: " + str([str(key) for key in self.required]) raise AttributeError(msg) if len(list(self.at_least_one_required)) and len(list(keys.intersection(self.at_least_one_required))) &lt; 1: msg = str(self.__class__.__name__) + " requires at least one: " + str([str(key) for key in self.at_least_one_required]) raise AttributeError(msg) for key, val in iterable.iteritems(): self.__setitem__(key, val) for key, val in kwargs.iteritems(): self.__setitem__(key, val) def update(self, E=None, **F): for key, val in E.iteritems(): self.__setitem__(key, val) for key, val in F.iteritems(): self.__setitem__(key, val) super(StrictDict, self).update({}) def __setitem__(self, key, value): all_allowed = self.allowed.union(self.required).union(self.at_least_one_required).union(self.cannot_coexist) if key not in list(all_allowed): msg = str(self.__class__.__name__) + " does not allow member '" + key + "'" raise AttributeError(msg) if key in list(self.cannot_coexist): for item in list(self.cannot_coexist): if key != item and item in self.keys(): msg = str(self.__class__.__name__) + "does not allow members '" + key + "' and '" + item + "' to coexist'" raise AttributeError(msg) super(StrictDict, self).__setitem__(key, value) </code></pre> <p>Example usage:</p> <pre><code>class JSONDoc(StrictDict): """ Class corresponding to JSON API top-level document structure http://jsonapi.org/format/#document-top-level """ at_least_one_required={'data', 'errors', 'meta'} allowed={"jsonapi", "links", "included"} cannot_coexist={"data", "errors"} def __setitem__(self, key, value): if key == "included" and "data" not in self.keys(): msg = str(self.__class__.__name__) + " does not allow 'included' member if 'data' member is not present" raise AttributeError(msg) super(JSONDoc, self).__setitem__(key, value) json_doc = JSONDoc( data={ "id": 5, "type": "movies" }, links={ "self": "http://url.com" } ) </code></pre>
0
2015-06-25T21:03:08Z
[ "python", "json", "serializable" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = parent # This must be a gwebpage instance self.xpath = None # String self.visibleShingles = [] # list of tuples self.invisibleShingles = [] # list of tuples self.urls = [] # list of string class gwebpage: """ Holds all the datastructure after the results have been parsed holds: 1) lists of gpagelets 2) loc, string, location of the file that represents it """ def __init__(self, url): self.url = url # Str self.netloc = False # Str self.gpagelets = [] # gpagelets instance self.page_key = "" # str </code></pre> <p>Is there a way for me to make my class json serializable? The thing that I am worried is the recursive reference.</p>
22
2009-09-22T06:37:10Z
35,832,502
<p>I implemented a very simple <code>todict</code> method with the help of <a href="http://stackoverflow.com/a/11637457/1766716">http://stackoverflow.com/a/11637457/1766716</a></p> <ul> <li>Iterate over properties that is not starts with <code>__</code></li> <li>Eliminate methods</li> <li>Eliminate some properties manually which is not necessary (for my case, coming from sqlalcemy)</li> </ul> <p>And used <code>getattr</code> to build dictionary.</p> <pre><code>class User(Base): id = Column(Integer, primary_key=True) firstname = Column(String(50)) lastname = Column(String(50)) password = Column(String(20)) def props(self): return filter( lambda a: not a.startswith('__') and a not in ['_decl_class_registry', '_sa_instance_state', '_sa_class_manager', 'metadata'] and not callable(getattr(self, a)), dir(self)) def todict(self): return {k: self.__getattribute__(k) for k in self.props()} </code></pre>
0
2016-03-06T21:00:59Z
[ "python", "json", "serializable" ]
Find the file with a given SVN URL within a SVN working copy
1,458,457
<p>Given a starting point in a Subversion working copy (e.g. current working directory), and a target SVN URL, I'd like to find the file in the working copy that has that SVN URL.</p> <p>For example, given this current directory:</p> <pre><code>c:\Subversion\ProjectA\a\b\c\ </code></pre> <p>which has this SVN URL:</p> <pre><code>https://svnserver/svn/ProjectA/trunk/a/b/c/ </code></pre> <p>I'd like to locate the file on the hard drive with this target SVN URL:</p> <pre><code>https://svnserver/svn/ProjectA/trunk/a/x/y/test.txt </code></pre> <p>which in this example would be:</p> <pre><code>c:\Subversion\ProjectA\a\x\y\test.txt </code></pre> <p>Firstly, does the SVN API provide a function to do this? Secondly, if not, what is a good reliable (cross-platform) method to implement it?</p> <p>Python is my target language, and I'm using pySvn although the native Python SVN bindings could be an alternative.</p>
2
2009-09-22T06:39:39Z
1,458,688
<p>Subversion doesn't use this backward mapping from url to working copy location itself. The most stable way to check for the url use would be to perform a recursive 'svn info' call over the working copy.</p> <p>This gives you the url for all files and directories and you can do the matching yourself.</p> <p>You could optimize this a bit by trying to map the urls on local paths and only look at sensible locations, but you would miss other locations created by 'svn switch'.</p> <p>I don't know how 'svn info' is mapped in the python bindings, but there is most likely some info2() function on a client class you can use.</p>
4
2009-09-22T07:51:50Z
[ "python", "svn", "pysvn" ]
Need help installing MySQL for Python
1,458,500
<p>Trying to install <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">MySQL for Python</a>. Two problems:</p> <p>1) Instructions over the net says installation is <pre>python setup.py</pre> For me, it results with <pre>can't open file 'setup.py': [Errno 2] No such file or directory</pre></p> <p>2) README.txt says: <pre>The Z MySQL database adapter uses the MySQLdb package.<br/>This must be installed before you can use the Z MySQL DA. You can find this at: <a href="http://sourceforge.net/projects/mysql-python" rel="nofollow">http://sourceforge.net/projects/mysql-python</a></pre> Which simply leads to the package itself, not anything else.</p> <p>Thanks for your help.</p> <p>PS. I'm using a Mac + Leopard.</p>
0
2009-09-22T06:55:02Z
1,458,507
<p>If you're using a Debian based distro you can :</p> <p><code>apt-get install python-mysqldb</code> ( or aptitude if you prefer ).</p>
1
2009-09-22T06:57:24Z
[ "python", "mysql", "adapter", "zope" ]
Need help installing MySQL for Python
1,458,500
<p>Trying to install <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">MySQL for Python</a>. Two problems:</p> <p>1) Instructions over the net says installation is <pre>python setup.py</pre> For me, it results with <pre>can't open file 'setup.py': [Errno 2] No such file or directory</pre></p> <p>2) README.txt says: <pre>The Z MySQL database adapter uses the MySQLdb package.<br/>This must be installed before you can use the Z MySQL DA. You can find this at: <a href="http://sourceforge.net/projects/mysql-python" rel="nofollow">http://sourceforge.net/projects/mysql-python</a></pre> Which simply leads to the package itself, not anything else.</p> <p>Thanks for your help.</p> <p>PS. I'm using a Mac + Leopard.</p>
0
2009-09-22T06:55:02Z
1,458,554
<p>You are confusing A <a href="http://en.wikipedia.org/wiki/Zope" rel="nofollow"><code>Zope product</code></a> (<code>ZMySQLDA</code>) with the <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">python-mysqldb</a> package. Try one of the <a href="http://sourceforge.net/projects/mysql-python/files/" rel="nofollow">download files</a>, if it doesn't help, go for the <a href="http://mysql-python.svn.sourceforge.net/viewvc/mysql-python/trunk/" rel="nofollow">source</a>. Note that the source trunk is clearly divided into <code>ZMySQLDA/</code> and <code>MySQLdb/</code> .</p>
2
2009-09-22T07:13:06Z
[ "python", "mysql", "adapter", "zope" ]
Json encoder python recursive reference
1,458,671
<p>Hey everyone I don't know whether I am doing the right thing here, basically I want both of my class to be json-serializable.</p> <pre><code>import json class gpagelet(json.JSONEncoder): """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = parent # This must be a gwebpage instance self.xpath = None # This is just an id for the pagelet (not unique across page), historically called xpath self.visibleShingles = [] self.invisibleShingles = [] self.urls = [] def __str__(self): """String representation of this object""" ret = "" ret += "xpath: %s\n" % self.xpath def appendShingles(): ret += "shingles: \n" for each in self.shingles: ret += "%s\n" % str(each) ret += "urls:\n" for each in self.urls: ret += "%s\n" % str( each) return ret class gwebpage(json.JSONEncoder): """ Holds all the datastructure after the results have been parsed holds: 1) lists of gpagelets 2) loc, string, location of the file that represents it """ def __init__(self, url): self.url = url # This will be http:// self.netloc = False # This will be http:// too self.gpagelets = [] # Appended by functions self.page_key = "" def __str__(self): ret = "" ret += "url: %s\n" % self.url ret += "netloc: %s\n" % self.netloc ret += "page_key: %s\n" % self.page_key ret += "pagelets:\n" for each in self.gpagelets: ret += "%s\n" % each.__str__() return ret class GpageletEncoder( json.JSONEncoder): def default(self, gp): gwebpageEncoder = GwebpageEncoder() if not isinstance( gp, gpagelet): raise Exception( "Cannot use GpageletEncoder on a non gpagelet instance") u = { } u['parent'] = gwebpageEncoder.default( gp.parent) u['xpath'] = gp.xpath u['visibleShingles'] = gp.visibleShingles u['invisibleShingles'] = gp.invisibleShingles u['urls'] = gp.urls return u class GwebpageEncoder( json.JSONEncoder): def default(self, gw): gpageletEncoder = GpageletEncoder() if not isinstance( gw, gwebpage): raise Exception( "Cannot use gwebpageEncoder on a non gwebpage instance") u = { } u['url'] = gw.url u['netloc'] = gw.netloc u['gpagelets'] = [ gpageletEncoder.default( each) for each in gw.gpagelets ] u['page_key'] = gw.page_key return u if __name__ == "__main__": import simplejson mom = gwebpage('http://www.google.com') son = gpagelet( mom) mom.gpagelets.append( son) print simplejson.dumps( mom, cls=GwebpageEncoder) </code></pre> <p>One of the trouble is that 1) I don't know what default is suppose to do 2) I don't know whether GWebpage's default is suppose to return the default or encoded gwebpage</p> <p>Now I am getting infinite recursion.</p> <p>Can someone help?</p>
0
2009-09-22T07:46:24Z
1,464,208
<p>FYI I am seeing a lot of trouble with this: u['gpagelets'] = [ gpageletEncoder.default( each) for each in gw.gpagelets ]</p>
0
2009-09-23T06:09:42Z
[ "python", "json" ]
How to create a MAPI32.dll stub to be able to "send as attachment" from MS Word?
1,458,690
<p>Microsoft Word has "send as attachment" functionality which creates a new message in Outlook with the document attached. </p> <p>I would like to replace Outlook with a custom mail agent, but I do not know how to achieve this. Now my mail agent is simply a program that runs, and takes a file name as parameter. </p> <p>As far as I know, "send as attachment" is using some DLL/API called MAPI. I would need to change my app so that it does not simply accept file name arguments, but can receive MAPI(?) calls MS Word uses when "sending as attachment".</p> <p>Further, I need to change the default mail agent by creating my own MAPI32.dll stub which simply redirects to my app.</p> <p>I'd appreciate if anyone had more info on how this could be achieved!</p>
1
2009-09-22T07:53:03Z
1,483,115
<p>OK, to answer my own question. I need to build a DLL with "MAPISendDocuments" and/or "MAPISendMail" functions defined.</p> <p>This DLL can have any name, and is referenced in the registry at HKLM/Software/Clients/Mail/MyMailApp/DLLPath.</p> <p>Found examples using Delphi...</p>
0
2009-09-27T08:37:31Z
[ "c#", "python", "outlook", "ms-word", "mapi" ]
How to create a MAPI32.dll stub to be able to "send as attachment" from MS Word?
1,458,690
<p>Microsoft Word has "send as attachment" functionality which creates a new message in Outlook with the document attached. </p> <p>I would like to replace Outlook with a custom mail agent, but I do not know how to achieve this. Now my mail agent is simply a program that runs, and takes a file name as parameter. </p> <p>As far as I know, "send as attachment" is using some DLL/API called MAPI. I would need to change my app so that it does not simply accept file name arguments, but can receive MAPI(?) calls MS Word uses when "sending as attachment".</p> <p>Further, I need to change the default mail agent by creating my own MAPI32.dll stub which simply redirects to my app.</p> <p>I'd appreciate if anyone had more info on how this could be achieved!</p>
1
2009-09-22T07:53:03Z
2,674,286
<p>When writing your own mapi implementation it is critical to create a dll with both the proper exports and calling conventions in order for the system stub mapi dll (c:\windows\system32\mapi32.dll, should be the same as mapistub.dll) to pass calls through to your dll. MAPI functions are called with the __stdcall calling convention. Also critical is setting the right registry keys in order for you mapi dll to be chosen by the system stub, it looks like you've already found the right one in order to specify a particular mapi dll be used when your applicaion makes mapi calls.</p> <p>I did this exact thing just recently: wrote my own skeleton mapi dll, and had a lot of trouble getting the system stub to call my extended mapi functions. The key was that mapi32.dll calls GetProcAddress on the "foo@x" entry point, not the "foo" entrypoint in the mapi interface in order to test whether or not your dll is "compliant" with extended mapi (I think for simple mapi calls it does not use the "foo@x" but the plain "foo" entrypoint name). I also had to compile my skeleton library interface file in my project "As C" and not "As C++" in order to get all the symbol names right. </p> <p>For example, MAPIInitialize should be declared like this in your source code:</p> <pre><code>HRESULT __stdcall MAPIInitialize( LPVOID lpMapiInit ) ... </code></pre> <p>and you'll need to specify a .def file with entries like this:</p> <pre><code>EXPORTS MAPIInitialize@4=_MAPIInitialize@4 MAPIInitialize=_MAPIInitialize@4 </code></pre> <p>For simple mapi calls (as opposed to extended mapi calls), you may not need the "double export". In order to see what the exports look like for a working mapi implementation, you can do this (if you have outlook installed on your system):</p> <pre> c:\> dumpbin /exports c:\Program Files\Common Files\SYSTEM\MSMAPI\1033\msmapi32.dll </pre> <p>(or substitute the path you find in the registry in <code>HKLM\Software\Clients\Mail\Microsoft Outlook\DLLPathEx</code>)</p>
1
2010-04-20T10:32:07Z
[ "c#", "python", "outlook", "ms-word", "mapi" ]
Python ctypes and not enough arguments (4 bytes missing)
1,458,813
<p>The function i'm trying to call is:</p> <pre><code>void FormatError (HRESULT hrError,PCHAR pszText); </code></pre> <p>from a custom dll using windll.</p> <pre><code>c_p = c_char_p() windll.thedll.FormatError(errcode, c_p) </code></pre> <p>Results in:</p> <pre><code>ValueError: Procedure probably called with not enough arguments (4 bytes missing) </code></pre> <p>Using cdll instead increases the bytes missing counter to 12. errcode above is the errercode returned from another function out of the same dll. How do I get the call right?</p>
2
2009-09-22T08:37:38Z
1,459,197
<p>Have you tried to use the <a href="http://docs.python.org/library/ctypes.html#ctypes.HRESULT" rel="nofollow">ctypes.HRESULT</a>? </p>
0
2009-09-22T10:10:20Z
[ "python", "windows", "ctypes" ]
Python ctypes and not enough arguments (4 bytes missing)
1,458,813
<p>The function i'm trying to call is:</p> <pre><code>void FormatError (HRESULT hrError,PCHAR pszText); </code></pre> <p>from a custom dll using windll.</p> <pre><code>c_p = c_char_p() windll.thedll.FormatError(errcode, c_p) </code></pre> <p>Results in:</p> <pre><code>ValueError: Procedure probably called with not enough arguments (4 bytes missing) </code></pre> <p>Using cdll instead increases the bytes missing counter to 12. errcode above is the errercode returned from another function out of the same dll. How do I get the call right?</p>
2
2009-09-22T08:37:38Z
1,459,422
<p>At the very least, you'll get more descriptive errors if you properly set up the <a href="http://docs.python.org/library/ctypes.html#specifying-the-required-argument-types-function-prototypes" rel="nofollow"><code>argtypes</code></a> and the <a href="http://docs.python.org/library/ctypes.html#return-types" rel="nofollow"><code>restype</code></a>.</p> <p>Try doing it this way:</p> <pre><code>windll.thedll.FormatError.argtypes = [ctypes.HRESULT, ctypes.c_char_p] windll.thedll.FormatError.restype = None </code></pre> <p>There's also a very good chance you are using the wrong calling convention -- check out <a href="http://docs.python.org/library/ctypes.html#calling-functions" rel="nofollow">the Calling Functions section</a> and <a href="http://docs.python.org/library/ctypes.html#loading-shared-libraries" rel="nofollow">the Loading Libraries section</a> for details on how to use a different calling convention.</p>
2
2009-09-22T11:05:42Z
[ "python", "windows", "ctypes" ]
Python ctypes and not enough arguments (4 bytes missing)
1,458,813
<p>The function i'm trying to call is:</p> <pre><code>void FormatError (HRESULT hrError,PCHAR pszText); </code></pre> <p>from a custom dll using windll.</p> <pre><code>c_p = c_char_p() windll.thedll.FormatError(errcode, c_p) </code></pre> <p>Results in:</p> <pre><code>ValueError: Procedure probably called with not enough arguments (4 bytes missing) </code></pre> <p>Using cdll instead increases the bytes missing counter to 12. errcode above is the errercode returned from another function out of the same dll. How do I get the call right?</p>
2
2009-09-22T08:37:38Z
1,459,789
<p>Actually I think you want to use FormatError as provided by ctypes</p> <p><a href="http://docs.python.org/library/ctypes.html#ctypes.FormatError" rel="nofollow">http://docs.python.org/library/ctypes.html#ctypes.FormatError</a></p> <blockquote> <p>ctypes.FormatError([code])</p> <p>Windows only: Returns a textual description of the error code. If no error code is specified, the last error code is used by calling the Windows api function GetLastError.</p> </blockquote>
0
2009-09-22T12:24:52Z
[ "python", "windows", "ctypes" ]
Modify address in Django middleware
1,458,829
<p>I don't know if it's possible but I'd like to add few parameters at the end of the URL using middleware. Can it be done without redirect after modyfing requested URL?</p> <p>ie. user clicks: .../some_link and middleware rewrites it to: .../some_link?par1=1&amp;par2=2</p> <p>Other way is to modify reponse and replace every HTML link but it's not something I'd like to do.</p> <p>Thanks</p>
3
2009-09-22T08:41:05Z
1,458,940
<pre><code>class YourRedirectMiddleware: def process_request(self, request): redirect_url = request.path+'?par1=1&amp;par2=2' return HttpResponsePermanentRedirect(redirect_url) </code></pre> <p>what are you trying to accomplish and why this way?</p>
4
2009-09-22T09:03:49Z
[ "python", "django", "django-urls", "django-middleware" ]
Modify address in Django middleware
1,458,829
<p>I don't know if it's possible but I'd like to add few parameters at the end of the URL using middleware. Can it be done without redirect after modyfing requested URL?</p> <p>ie. user clicks: .../some_link and middleware rewrites it to: .../some_link?par1=1&amp;par2=2</p> <p>Other way is to modify reponse and replace every HTML link but it's not something I'd like to do.</p> <p>Thanks</p>
3
2009-09-22T08:41:05Z
1,458,950
<p>You can do whatever you like in the middleware. You have access to the request object, you can get the URL and redirect to a new one if you want.</p> <p>My question would be, why do you want to do this? If you need to keep information about the request, the proper place to do this is in the session.</p>
0
2009-09-22T09:06:21Z
[ "python", "django", "django-urls", "django-middleware" ]
Modify address in Django middleware
1,458,829
<p>I don't know if it's possible but I'd like to add few parameters at the end of the URL using middleware. Can it be done without redirect after modyfing requested URL?</p> <p>ie. user clicks: .../some_link and middleware rewrites it to: .../some_link?par1=1&amp;par2=2</p> <p>Other way is to modify reponse and replace every HTML link but it's not something I'd like to do.</p> <p>Thanks</p>
3
2009-09-22T08:41:05Z
1,460,317
<p>I think this really depends on your problem and what exactly you are trying to do.</p> <p>You cannot change the URL without redirecting the user, as you cannot modify the URL on a page without a reload. Basically a redirect is a response telling the user to move on, there is no way to actually change the URL. Note that even if you do it in something like JavaScript you basically do the same as a redirect, so it can't be done client or server side.</p> <p>I think it might help if you explain to us why you need to pass this information via the URL. Why not store data in the session?</p> <p>I guess you could add the data to the request object but that doesn't add it to the URL.</p>
1
2009-09-22T14:06:31Z
[ "python", "django", "django-urls", "django-middleware" ]
Python - Is there a way around 'os.listdir()' returning gibberish for bad folder name?
1,458,847
<p>I have a simple script written in Python:</p> <pre><code>import os def Path(SourcePath): for Folder in os.listdir(SourcePath): print "TESTING: %s" % Folder Path("\\\\192.168.0.36\\PDFs") </code></pre> <p>When i run this it recurses through a remote share on the LAN and just simply displays the names of the folders found. This share primarily contains folders.</p> <p>The problem is that if a folder name has a space at the end of it's name, the above script lists jibberish.</p> <p>For example, if i have the following folders in the above share:</p> <ol> <li>"6008386 HH - Walkers Crisps"</li> <li>"6008157 CPP - Santas Chocolate "</li> <li>"6007458 SCA - Morrisons Bananas"</li> </ol> <p>Notice that "6008157 CPP - Santas Chocolate " has a space at the end. This is the listing from the above script:</p> <ol> <li>"TESTING: 6008386 HH - Walkers Crisps"</li> <li>"TESTING: 6EBA72~1"</li> <li>"TESTING: 6007458 SCA - Morrisons Bananas"</li> </ol> <p>How can i avoid this while recursing the remote dir? I could fix the folder name if only it was returned properly by 'os.listdir()'.</p> <p>Any ideas on how to tackle this?</p>
3
2009-09-22T08:45:30Z
1,458,877
<p>That is not (<a href="http://en.wikipedia.org/wiki/Gibberish" rel="nofollow">g</a>|<a href="http://www.urbandictionary.com/define.php?term=jibberish" rel="nofollow">j</a>)ibberish, it's a <a href="http://en.wikipedia.org/wiki/8.3%5Ffilename" rel="nofollow">short (8.3) filename</a>. It's Windows-specific, but you might be able to use <code><a href="http://msdn.microsoft.com/en-us/library/aa364980%28VS.85%29.aspx" rel="nofollow">GetLongPathName()</a></code> to map it back to a long name.</p>
3
2009-09-22T08:51:08Z
[ "python" ]
Python - Is there a way around 'os.listdir()' returning gibberish for bad folder name?
1,458,847
<p>I have a simple script written in Python:</p> <pre><code>import os def Path(SourcePath): for Folder in os.listdir(SourcePath): print "TESTING: %s" % Folder Path("\\\\192.168.0.36\\PDFs") </code></pre> <p>When i run this it recurses through a remote share on the LAN and just simply displays the names of the folders found. This share primarily contains folders.</p> <p>The problem is that if a folder name has a space at the end of it's name, the above script lists jibberish.</p> <p>For example, if i have the following folders in the above share:</p> <ol> <li>"6008386 HH - Walkers Crisps"</li> <li>"6008157 CPP - Santas Chocolate "</li> <li>"6007458 SCA - Morrisons Bananas"</li> </ol> <p>Notice that "6008157 CPP - Santas Chocolate " has a space at the end. This is the listing from the above script:</p> <ol> <li>"TESTING: 6008386 HH - Walkers Crisps"</li> <li>"TESTING: 6EBA72~1"</li> <li>"TESTING: 6007458 SCA - Morrisons Bananas"</li> </ol> <p>How can i avoid this while recursing the remote dir? I could fix the folder name if only it was returned properly by 'os.listdir()'.</p> <p>Any ideas on how to tackle this?</p>
3
2009-09-22T08:45:30Z
1,459,011
<p>Windows uses generated 8.3 "placeholders" when a filename over CIFS contains characters which are illegal in a Windows filename.</p> <p>In this case, it's happening because your "Santas Chocolate " filename ends with a space. Windows filenames can't end with spaces, so it uses a placeholder to make the file accessible.</p> <p>I don't think you can use GetLongPathName for this--there's no long filename to map to, because that would, by definition, be an illegal filename. If you have filenames like this, I don't think there's any way to find out what it actually is on the server, and it would do you a limited amount of good, since you couldn't refer to it by that filename.</p>
4
2009-09-22T09:19:42Z
[ "python" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?</p> <p><strong>UPDATE</strong> Can you tell me how is this done in Python or Java?</p>
39
2009-09-22T09:36:21Z
1,459,090
<p>If the ZIP decompressor you use can provide the data on original and compressed size you can use that data. Otherwise start unzipping and monitor the output size - if it grows too much cut it loose.</p>
4
2009-09-22T09:38:53Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?</p> <p><strong>UPDATE</strong> Can you tell me how is this done in Python or Java?</p>
39
2009-09-22T09:36:21Z
1,459,095
<p>Check a zip header first :)</p>
5
2009-09-22T09:40:43Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?</p> <p><strong>UPDATE</strong> Can you tell me how is this done in Python or Java?</p>
39
2009-09-22T09:36:21Z
1,459,096
<p>Make sure you are not using your system drive for temp storage. I am not sure if a virusscanner will check it if it encounters it. </p> <p>Also you can look at the information inside the zip file and retrieve a list of the content. How to do this depends on the utility used to extract the file, so you need to provide more information here</p>
1
2009-09-22T09:40:43Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?</p> <p><strong>UPDATE</strong> Can you tell me how is this done in Python or Java?</p>
39
2009-09-22T09:36:21Z
1,459,154
<p>Try this in Python:</p> <pre><code>import zipfile z = zipfile.ZipFile('c:/a_zip_file') print 'total files size=', sum(e.file_size for e in z.infolist()) z.close() </code></pre>
19
2009-09-22T09:57:29Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?</p> <p><strong>UPDATE</strong> Can you tell me how is this done in Python or Java?</p>
39
2009-09-22T09:36:21Z
1,459,157
<p>Reading over the description on Wikipedia - </p> <p>Deny any compressed files that contain compressed files.<br> &nbsp;&nbsp;&nbsp;&nbsp; Use <a href="http://java.sun.com/javase/6/docs/api/java/util/zip/ZipFile.html#entries%28%29">ZipFile.entries()</a> to retrieve a list of files, then <a href="http://java.sun.com/javase/6/docs/api/java/util/zip/ZipEntry.html#getName%28%29">ZipEntry.getName()</a> to find the file extension.<br/> Deny any compressed files that contain files over a set size, or the size can not be determined at startup.<br> &nbsp;&nbsp;&nbsp;&nbsp; While iterating over the files use <a href="http://java.sun.com/javase/6/docs/api/java/util/zip/ZipEntry.html#getSize%28%29">ZipEntry.getSize()</a> to retrieve the file size.</p>
6
2009-09-22T09:58:04Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?</p> <p><strong>UPDATE</strong> Can you tell me how is this done in Python or Java?</p>
39
2009-09-22T09:36:21Z
1,459,186
<p>Don't allow the upload process to write enough data to fill up the disk, ie solve the problem, not just one possible cause of the problem.</p>
4
2009-09-22T10:07:22Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?</p> <p><strong>UPDATE</strong> Can you tell me how is this done in Python or Java?</p>
39
2009-09-22T09:36:21Z
1,459,369
<p>Zip is, erm, an "interesting" format. A robust solution is to stream the data out, and stop when you have had enough. In Java, use <code>ZipInputStream</code> rather than <code>ZipFile</code>. The latter also requires you to store the data in a temporary file, which is also not the greatest of ideas.</p>
17
2009-09-22T10:50:22Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?</p> <p><strong>UPDATE</strong> Can you tell me how is this done in Python or Java?</p>
39
2009-09-22T09:36:21Z
17,905,491
<p>Why would you want to? The moment you zip the first layer and find so many multiple files with weird numbering, you'd automatically know. There is no autoextracting sfx archive zip bomb that I know of.</p>
-1
2013-07-28T06:06:05Z
[ "java", "python", "security", "compression", "zip" ]
module reimported if imported from different path
1,459,236
<p>In a big application I am working, several people import same modules differently e.g. import x or from y import x the side effects of that is x is imported twice and may introduce very subtle bugs, if someone is relying on global attributes</p> <p>e.g. suppose I have a package mypakcage with three file mymodule.py, main.py and <strong>init</strong>.py</p> <p>mymodule.py contents</p> <pre><code>l = [] class A(object): pass </code></pre> <p><strong>main.py contents</strong></p> <pre><code>def add(x): from mypackage import mymodule mymodule.l.append(x) print "updated list",mymodule.l def get(): import mymodule return mymodule.l add(1) print "lets check",get() add(1) print "lets check again",get() </code></pre> <p>it prints</p> <pre><code>updated list [1] lets check [] updated list [1, 1] lets check again [] </code></pre> <p>because now there are two lists in two different modules, similarly class A is different To me it looks serious enough because classes itself will be treated differently e.g. below code prints False</p> <pre><code>def create(): from mypackage import mymodule return mymodule.A() def check(a): import mymodule return isinstance(a, mymodule.A) print check(create()) </code></pre> <p><strong>Question:</strong></p> <p>Is there any way to avoid this? except enforcing that module should be imported one way onyl. Can't this be handled by python import mechanism, I have seen several bugs related to this in django code and elsewhere too.</p>
7
2009-09-22T10:17:31Z
1,459,587
<p>I can only replicate this if main.py is the file you are actually running. In that case you will get the current directory of main.py on the sys path. But you apparently also have a system path set so that mypackage can be imported.</p> <p>Python will in that situation not realize that mymodule and mypackage.mymodule is the same module, and you get this effect. This change illustrates this:</p> <pre><code>def add(x): from mypackage import mymodule print "mypackage.mymodule path", mymodule mymodule.l.append(x) print "updated list",mymodule.l def get(): import mymodule print "mymodule path", mymodule return mymodule.l add(1) print "lets check",get() add(1) print "lets check again",get() $ export PYTHONPATH=. $ python mypackage/main.py mypackage.mymodule path &lt;module 'mypackage.mymodule' from '/tmp/mypackage/mymodule.pyc'&gt; mymodule path &lt;module 'mymodule' from '/tmp/mypackage/mymodule.pyc'&gt; </code></pre> <p>But add another mainfile, in the currect directory:</p> <pre><code>realmain.py: from mypackage import main </code></pre> <p>and the result is different:</p> <pre><code>mypackage.mymodule path &lt;module 'mypackage.mymodule' from '/tmp/mypackage/mymodule.pyc'&gt; mymodule path &lt;module 'mypackage.mymodule' from '/tmp/mypackage/mymodule.pyc'&gt; </code></pre> <p>So I suspect that you have your main python file within the package. And in that case the solution is to not do that. :-)</p>
3
2009-09-22T11:46:25Z
[ "python", "python-import" ]
module reimported if imported from different path
1,459,236
<p>In a big application I am working, several people import same modules differently e.g. import x or from y import x the side effects of that is x is imported twice and may introduce very subtle bugs, if someone is relying on global attributes</p> <p>e.g. suppose I have a package mypakcage with three file mymodule.py, main.py and <strong>init</strong>.py</p> <p>mymodule.py contents</p> <pre><code>l = [] class A(object): pass </code></pre> <p><strong>main.py contents</strong></p> <pre><code>def add(x): from mypackage import mymodule mymodule.l.append(x) print "updated list",mymodule.l def get(): import mymodule return mymodule.l add(1) print "lets check",get() add(1) print "lets check again",get() </code></pre> <p>it prints</p> <pre><code>updated list [1] lets check [] updated list [1, 1] lets check again [] </code></pre> <p>because now there are two lists in two different modules, similarly class A is different To me it looks serious enough because classes itself will be treated differently e.g. below code prints False</p> <pre><code>def create(): from mypackage import mymodule return mymodule.A() def check(a): import mymodule return isinstance(a, mymodule.A) print check(create()) </code></pre> <p><strong>Question:</strong></p> <p>Is there any way to avoid this? except enforcing that module should be imported one way onyl. Can't this be handled by python import mechanism, I have seen several bugs related to this in django code and elsewhere too.</p>
7
2009-09-22T10:17:31Z
1,459,594
<p>Each module namespace is imported only once. Issue is, you're importing them differently. On the first you're importing from the global package, and on the second you're doing a local, non-packaged <code>import</code>. Python sees modules as different. The first import is internally cached as <code>mypackage.mymodule</code> and the second one as <code>mymodule</code> only.</p> <p>A way to solve this is to <strong>always use absolute imports</strong>. That is, always give your module absolute import paths from the top-level package onwards:</p> <pre><code>def add(x): from mypackage import mymodule mymodule.l.append(x) print "updated list",mymodule.l def get(): from mypackage import mymodule return mymodule.l </code></pre> <p>Remember that your entry point (the file you run, <code>main.py</code>) also should be <strong>outside</strong> the package. When you want the entry point code to be inside the package, usually you use a run a small script instead. Example:</p> <p><code>runme.py</code>, outside the package:</p> <pre><code>from mypackage.main import main main() </code></pre> <p>And in <code>main.py</code> you add:</p> <pre><code>def main(): # your code </code></pre> <p>I find <a href="http://jcalderone.livejournal.com/39794.html" rel="nofollow">this document</a> by Jp Calderone to be a great tip on how to (not) structure your python project. Following it you won't have issues. Pay attention to the <code>bin</code> folder - it is outside the package. I'll reproduce the entire text here:</p> <blockquote> <h1>Filesystem structure of a Python project</h1> <p><strong>Do</strong>:</p> <ul> <li>name the directory something related to your project. For example, if your project is named "<em>Twisted</em>", name the top-level directory for its source files <code>Twisted</code>. When you do releases, you should include a version number suffix: <code>Twisted-2.5</code>. </li> <li>create a directory <code>Twisted/bin</code> and put your executables there, if you have any. Don't give them a <code>.py</code> extension, even if they are Python source files. Don't put any code in them except an import of and call to a main function defined somewhere else in your projects. </li> <li>If your project is expressable as a single Python source file, then put it into the directory and name it something related to your project. For example, <code>Twisted/twisted.py</code>. If you need multiple source files, create a package instead (<code>Twisted/twisted/</code>, with an empty <code>Twisted/twisted/__init__.py</code>) and place your source files in it. For example, <code>Twisted/twisted/internet.py</code>. </li> <li>put your unit tests in a sub-package of your package (note - this means that the single Python source file option above was a trick - you always need at least one other file for your unit tests). For example, <code>Twisted/twisted/test/</code>. Of course, make it a package with <code>Twisted/twisted/test/__init__.py</code>. Place tests in files like <code>Twisted/twisted/test/test_internet.py</code>.</li> <li>add <code>Twisted/README</code> and T<code>wisted/setup.py</code> to explain and install your software, respectively, if you're feeling nice.</li> </ul> <p><strong>Don't</strong>:</p> <ul> <li>put your source in a directory called <code>src</code> or <code>lib</code>. This makes it hard to run without installing. </li> <li>put your tests outside of your Python package. This makes it hard to run the tests against an installed version. </li> <li>create a package that only has a <code>__init__.py</code> and then put all your code into <code>__init__.py</code>. Just make a module instead of a package, it's simpler. </li> <li>try to come up with magical hacks to make Python able to import your module or package without having the user add the directory containing it to their import path (either via <code>PYTHONPATH</code> or some other mechanism). You will not correctly handle all cases and users will get angry at you when your software doesn't work in their environment.</li> </ul> </blockquote>
2
2009-09-22T11:47:06Z
[ "python", "python-import" ]
pyparsing - load ABNF?
1,459,371
<p>can pyparsing read ABNF from a file instead of having to define it in terms of python objects? </p> <p>If not, is there something which can do similar (load an ABNF file into a parser object)</p>
9
2009-09-22T10:50:31Z
1,459,433
<p>There are lots of Python parsing packages: <a href="http://nedbatchelder.com/text/python-parsers.html" rel="nofollow">Python Parsing Tools</a>. <a href="http://antlr.org" rel="nofollow">ANTLR</a> in particular is very well-respected, and reads a grammar from a dedicated file. </p>
2
2009-09-22T11:08:24Z
[ "python", "parsing", "pyparsing" ]
pyparsing - load ABNF?
1,459,371
<p>can pyparsing read ABNF from a file instead of having to define it in terms of python objects? </p> <p>If not, is there something which can do similar (load an ABNF file into a parser object)</p>
9
2009-09-22T10:50:31Z
1,459,981
<p>See <a href="http://pyparsing.wikispaces.com/file/view/ebnf.py" rel="nofollow" title="EBNF parser">this example</a> submitted by Seo Sanghyeon, which reads EBNF and parses it (using pyparsing) to create a pyparsing parser.</p>
9
2009-09-22T13:04:07Z
[ "python", "parsing", "pyparsing" ]
listing network shares with python
1,459,590
<p>if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:</p> <pre><code>os.listdir("\\\\remotehost\\share") </code></pre> <p>However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:</p> <pre><code>os.listdir("\\\\remotehost") </code></pre> <p>Is anyone aware of why this doesn't work?, any help/workaround is appreciated.</p>
2
2009-09-22T11:46:33Z
1,459,658
<p>May be <a href="http://miketeo.net/wp/index.php/projects/pysmb">pysmb</a> can help</p>
5
2009-09-22T12:01:27Z
[ "python", "networking", "drive" ]
listing network shares with python
1,459,590
<p>if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:</p> <pre><code>os.listdir("\\\\remotehost\\share") </code></pre> <p>However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:</p> <pre><code>os.listdir("\\\\remotehost") </code></pre> <p>Is anyone aware of why this doesn't work?, any help/workaround is appreciated.</p>
2
2009-09-22T11:46:33Z
1,459,771
<p>Sorry. I'm not able to try this as I'm not in a PC. Have you tried:</p> <pre><code>os.listdir("\\\\remotehost\\") </code></pre>
0
2009-09-22T12:21:12Z
[ "python", "networking", "drive" ]
listing network shares with python
1,459,590
<p>if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:</p> <pre><code>os.listdir("\\\\remotehost\\share") </code></pre> <p>However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:</p> <pre><code>os.listdir("\\\\remotehost") </code></pre> <p>Is anyone aware of why this doesn't work?, any help/workaround is appreciated.</p>
2
2009-09-22T11:46:33Z
1,459,813
<p>Maybe the following script will help you. See <a href="http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b" rel="nofollow">http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b</a></p>
1
2009-09-22T12:28:57Z
[ "python", "networking", "drive" ]
listing network shares with python
1,459,590
<p>if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:</p> <pre><code>os.listdir("\\\\remotehost\\share") </code></pre> <p>However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:</p> <pre><code>os.listdir("\\\\remotehost") </code></pre> <p>Is anyone aware of why this doesn't work?, any help/workaround is appreciated.</p>
2
2009-09-22T11:46:33Z
2,715,897
<p>I'm sure the OP has forgotten about this question by now, but here's (maybe) an explanation:</p> <p><a href="http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories" rel="nofollow">http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories</a></p> <p>In case anybody else happens along this problem, like I did.</p>
1
2010-04-26T18:31:18Z
[ "python", "networking", "drive" ]
Non-Blocking method for parsing (streaming) XML in python
1,459,648
<p>I have an XML document coming in over a socket that I need to parse and react to on the fly (ie parsing a partial tree). What I'd like is a non blocking method of doing so, so that I can do other things while waiting for more data to come in (without threading).</p> <p>Something like iterparse would be ideal if it finished iterating when the read buffer was empty, eg:</p> <pre><code>context = iterparse(imaginary_socket_file_wrapper) while 1: for event, elem in context: process_elem(elem) # iteration of context finishes when socket has no more data do_other_stuff() time.sleep(0.1) </code></pre> <p>I guess SAX would also be an option, but iterparse just seems simpler for my needs. Any ideas?</p> <p><strong>Update:</strong></p> <p>Using threads is fine, but introduces a level of complexity that I was hoping to sidestep. I thought that non-blocking calls would be a good way to do so, but I'm finding that it increases the complexity of parsing the XML.</p>
7
2009-09-22T11:59:05Z
1,467,966
<p>If you won't use threads, you can use an event loop and poll non-blocking sockets.</p> <p><a href="http://docs.python.org/library/asyncore.html" rel="nofollow"><code>asyncore</code></a> is the standard library module for such stuff. <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> is <strong>the</strong> async library for Python, but complex and probably a bit heavyweight for your needs.</p> <p>Alternatively, <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow"><code>multiprocessing</code></a> is the non-thread thread alternative, but I assume you aren't running 2.6.</p> <p>One way or the other, I think you're going to have to use threads, extra processes or weave some equally complex async magic.</p>
1
2009-09-23T18:58:00Z
[ "python", "xml", "parsing", "nonblocking" ]
Non-Blocking method for parsing (streaming) XML in python
1,459,648
<p>I have an XML document coming in over a socket that I need to parse and react to on the fly (ie parsing a partial tree). What I'd like is a non blocking method of doing so, so that I can do other things while waiting for more data to come in (without threading).</p> <p>Something like iterparse would be ideal if it finished iterating when the read buffer was empty, eg:</p> <pre><code>context = iterparse(imaginary_socket_file_wrapper) while 1: for event, elem in context: process_elem(elem) # iteration of context finishes when socket has no more data do_other_stuff() time.sleep(0.1) </code></pre> <p>I guess SAX would also be an option, but iterparse just seems simpler for my needs. Any ideas?</p> <p><strong>Update:</strong></p> <p>Using threads is fine, but introduces a level of complexity that I was hoping to sidestep. I thought that non-blocking calls would be a good way to do so, but I'm finding that it increases the complexity of parsing the XML.</p>
7
2009-09-22T11:59:05Z
1,468,092
<p>I think there are two components to this, the non-blocking network I/O, and a stream-oriented XML parser.</p> <p>For the former, you'd have to pick a non-blocking network framework, or roll your own solution for this. Twisted certainly would work, but I personally find inversion of control frameworks difficult to wrap my brain around. You would likely have to keep track of a lot of state in your callbacks to feed the parser. For this reason I tend to find <a href="http://eventlet.net/" rel="nofollow">Eventlet</a> a bit easier to program to, and I think it would fit well in this situation.</p> <p>Essentially it allows you to write your code <em>as if</em> you were using a blocking socket call (using an ordinary loop or a generator or whatever you like), except that you can spawn it into a separate coroutine (a "greenlet") that will automatically perform a cooperative yield when I/O operations would block, thus allowing other coroutines to run.</p> <p>This makes using any stream-oriented parser trivial again, because the code is structured like an ordinary blocking call. It also means that many libraries that don't directly deal with sockets or other I/O (like the parser for instance) don't have to be specially modified to be non-blocking: if they block, Eventlet yields the coroutine.</p> <p>Admittedly Eventlet is <em>slightly</em> magic, but I find it has a much easier learning curve than Twisted, and results in more straightforward code because you don't have to turn your logic "inside out" to fit the framework.</p>
4
2009-09-23T19:24:28Z
[ "python", "xml", "parsing", "nonblocking" ]
Non-Blocking method for parsing (streaming) XML in python
1,459,648
<p>I have an XML document coming in over a socket that I need to parse and react to on the fly (ie parsing a partial tree). What I'd like is a non blocking method of doing so, so that I can do other things while waiting for more data to come in (without threading).</p> <p>Something like iterparse would be ideal if it finished iterating when the read buffer was empty, eg:</p> <pre><code>context = iterparse(imaginary_socket_file_wrapper) while 1: for event, elem in context: process_elem(elem) # iteration of context finishes when socket has no more data do_other_stuff() time.sleep(0.1) </code></pre> <p>I guess SAX would also be an option, but iterparse just seems simpler for my needs. Any ideas?</p> <p><strong>Update:</strong></p> <p>Using threads is fine, but introduces a level of complexity that I was hoping to sidestep. I thought that non-blocking calls would be a good way to do so, but I'm finding that it increases the complexity of parsing the XML.</p>
7
2009-09-22T11:59:05Z
2,270,249
<p>Diving into the iterparse source provided the solution for me. Here's a simple example of building an XML tree on the fly and processing elements after their close tags:</p> <pre><code>import xml.etree.ElementTree as etree parser = etree.XMLTreeBuilder() def end_tag_event(tag): node = self.parser._end(tag) print node parser._parser.EndElementHandler = end_tag_event def data_received(data): parser.feed(data) </code></pre> <p>In my case I ended up feeding it data from twisted, but it should work with a non-blocking socket also.</p>
6
2010-02-16T02:18:32Z
[ "python", "xml", "parsing", "nonblocking" ]
Get the inputs from Excel and use those inputs in python script
1,459,788
<p>How to get the inputs from excel and use those inputs in python.</p>
1
2009-09-22T12:24:40Z
1,459,792
<p>Take a look at <a href="http://pypi.python.org/pypi/xlrd" rel="nofollow">xlrd</a></p> <p>This is the best reference I found for learning how to use it: <a href="http://www.dev-explorer.com/articles/excel-spreadsheets-and-python" rel="nofollow">http://www.dev-explorer.com/articles/excel-spreadsheets-and-python</a></p>
6
2009-09-22T12:25:42Z
[ "python" ]
Get the inputs from Excel and use those inputs in python script
1,459,788
<p>How to get the inputs from excel and use those inputs in python.</p>
1
2009-09-22T12:24:40Z
1,459,837
<p>Not sure if this is exactly what you're talking about, but:</p> <p>If you have a very simple excel file (i.e. basically just one table filled with string-values, nothing fancy), and all you want to do is basic processing, then I'd suggest just converting it to a <a href="http://en.wikipedia.org/wiki/Comma%5Fseparated%5Fvalues" rel="nofollow">csv</a> (comma-seperated value file). This can be done by "saving as..." in excel and selecting csv.</p> <p>This is just a file with the same data as the excel, except represented by lines seperated with commas: cell A:1, cell A:2, cell A:3 cell B:1, cell B:2, cell b:3</p> <p>This is then very easy to parse using standard python functions (i.e., readlines to get each line of the file, then it's just a list that you can split on ",").</p> <p>This if of course only helpful in some situations, like when you get a log from a program and want to quickly run a python script which handles it.</p> <p><strong>Note</strong>: As was pointed out in the comments, splitting the string on "," is actually not very good, since you run into all sorts of problems. Better to use the csv module (which another answer here teaches how to use).</p>
2
2009-09-22T12:34:41Z
[ "python" ]
Get the inputs from Excel and use those inputs in python script
1,459,788
<p>How to get the inputs from excel and use those inputs in python.</p>
1
2009-09-22T12:24:40Z
1,459,904
<p>If you can save as a csv file with headers: </p> <pre><code>Attrib1, Attrib2, Attrib3 value1.1, value1.2, value1.3 value2,1,... </code></pre> <p>Then I would highly recommend looking at built-in the <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv module</a> </p> <p>With that you can do things like:</p> <pre><code>csvFile = csv.DictReader(open("csvFile.csv", "r")) for row in csvFile: print row['Attrib1'], row['Attrib2'] </code></pre>
0
2009-09-22T12:52:12Z
[ "python" ]
Get the inputs from Excel and use those inputs in python script
1,459,788
<p>How to get the inputs from excel and use those inputs in python.</p>
1
2009-09-22T12:24:40Z
2,978,744
<pre><code>import win32com Excel=win32com.client.Dispatch("Excel.Application") Excel.Workbooks.Open(file path) Cells=Excel.ActiveWorkBook.ActiveSheet.Cells Cells(row,column).Value=Input Output=Cells(row,column).Value </code></pre>
1
2010-06-05T01:25:18Z
[ "python" ]
Do not require non-NULL field (allow empty strings) in FormAlchemy
1,459,919
<p>I'm fairly novice to FormAlchemy and it seems that I don't get something. I have a SQLAlchemy model defined like this:</p> <pre><code>... class Device(meta.Base): __tablename__ = 'devices' id = sa.Column('id_device', sa.types.Integer, primary_key=True) serial_number = sa.Column('sn', sa.types.Unicode(length=20), nullable=False) mac = sa.Column('mac', sa.types.Unicode(length=12), nullable=False) ipv4 = sa.Column('ip', sa.types.Unicode(length=15), nullable=False) type_id = sa.Column('type_id', sa.types.Integer, sa.schema.ForeignKey('device_types.id')) type = orm.relation(DeviceType, primaryjoin=type_id == DeviceType.id) ... </code></pre> <p>Then in my (Pylons) controller I create a FormAlchemy form like this:</p> <pre><code>c.device = model.meta.Session.query(model.Device).get(device_id) fs = FieldSet(c.device, data=request.POST or None) fs.configure(options=[fs.ipv4.label(u'IP').readonly(), fs.type.label(u'Type').with_null_as((u'—', '')), fs.serial_number.label(u'S/N'), fs.mac.label(u'MAC')]) </code></pre> <p>The documentation says that "By default, NOT NULL columns are required. You can only add required-ness, not remove it.", but I want to allow non-NULL empty strings, which <code>validators.required</code> disallows. Is there something like <code>blank=True, null=False</code> in Django?</p> <p>To be more precise, I want a custom validator like one below, to either allow empty strings with <code>type=None</code> or all values to be set non-NULL and non-empty:</p> <pre><code># For use on fs.mac and fs.serial_number. # I haven't tested this code yet. def required_when_type_is_set(value, field): type_is_set = field.parent.type.value is not None: if value is None or (type_is_set and value.strip() = ''): raise validators.ValidationError(u'Please enter a value') </code></pre> <p>If possible, I'd like to refrain from monkey-patching <code>formalchemy.validators.required</code> or other kludges. I don't want to set <code>nullable=True</code> on model fields, because it doesn't seems to be proper solution too.</p> <p>What's the correct way to validate form in such case? Thanks for any suggestions in advance.</p>
3
2009-09-22T12:54:56Z
1,462,689
<p>Can you explain why <code>nullable=True</code> would not be the solution?</p> <p>To me it seems useless to store empty strings in the database and I would not encourage it. If there is no data than choose the more efficient type for the database.</p> <p>Personally I think the Django solution in case of strings is wrong since it does not really support NULL in CharFields. If you want to store NULL in a CharField you will have to do it manually in the code.</p>
3
2009-09-22T21:22:02Z
[ "python", "sqlalchemy", "validation", "pylons", "formalchemy" ]
Do not require non-NULL field (allow empty strings) in FormAlchemy
1,459,919
<p>I'm fairly novice to FormAlchemy and it seems that I don't get something. I have a SQLAlchemy model defined like this:</p> <pre><code>... class Device(meta.Base): __tablename__ = 'devices' id = sa.Column('id_device', sa.types.Integer, primary_key=True) serial_number = sa.Column('sn', sa.types.Unicode(length=20), nullable=False) mac = sa.Column('mac', sa.types.Unicode(length=12), nullable=False) ipv4 = sa.Column('ip', sa.types.Unicode(length=15), nullable=False) type_id = sa.Column('type_id', sa.types.Integer, sa.schema.ForeignKey('device_types.id')) type = orm.relation(DeviceType, primaryjoin=type_id == DeviceType.id) ... </code></pre> <p>Then in my (Pylons) controller I create a FormAlchemy form like this:</p> <pre><code>c.device = model.meta.Session.query(model.Device).get(device_id) fs = FieldSet(c.device, data=request.POST or None) fs.configure(options=[fs.ipv4.label(u'IP').readonly(), fs.type.label(u'Type').with_null_as((u'—', '')), fs.serial_number.label(u'S/N'), fs.mac.label(u'MAC')]) </code></pre> <p>The documentation says that "By default, NOT NULL columns are required. You can only add required-ness, not remove it.", but I want to allow non-NULL empty strings, which <code>validators.required</code> disallows. Is there something like <code>blank=True, null=False</code> in Django?</p> <p>To be more precise, I want a custom validator like one below, to either allow empty strings with <code>type=None</code> or all values to be set non-NULL and non-empty:</p> <pre><code># For use on fs.mac and fs.serial_number. # I haven't tested this code yet. def required_when_type_is_set(value, field): type_is_set = field.parent.type.value is not None: if value is None or (type_is_set and value.strip() = ''): raise validators.ValidationError(u'Please enter a value') </code></pre> <p>If possible, I'd like to refrain from monkey-patching <code>formalchemy.validators.required</code> or other kludges. I don't want to set <code>nullable=True</code> on model fields, because it doesn't seems to be proper solution too.</p> <p>What's the correct way to validate form in such case? Thanks for any suggestions in advance.</p>
3
2009-09-22T12:54:56Z
1,464,363
<p>Finally found a (klugde, but seems this is the only sane choice) way to do this.</p> <pre><code> fs.serial_number.validators.remove(formalchemy.validators.required) fs.mac.validators.remove(formalchemy.validators.required) </code></pre> <p>(Regarding my validator) Note, that FA will <em>completely</em> skip all validation when the value is <code>None</code>, because, by convention, it won't pass <code>None</code> to validators (except for <code>validators.required</code>, which is hard-coded). I've filed an enhancement request ticket trying to solve this: <a href="http://code.google.com/p/formalchemy/issues/detail?id=117" rel="nofollow">http://code.google.com/p/formalchemy/issues/detail?id=117</a></p>
4
2009-09-23T07:02:08Z
[ "python", "sqlalchemy", "validation", "pylons", "formalchemy" ]
Do not require non-NULL field (allow empty strings) in FormAlchemy
1,459,919
<p>I'm fairly novice to FormAlchemy and it seems that I don't get something. I have a SQLAlchemy model defined like this:</p> <pre><code>... class Device(meta.Base): __tablename__ = 'devices' id = sa.Column('id_device', sa.types.Integer, primary_key=True) serial_number = sa.Column('sn', sa.types.Unicode(length=20), nullable=False) mac = sa.Column('mac', sa.types.Unicode(length=12), nullable=False) ipv4 = sa.Column('ip', sa.types.Unicode(length=15), nullable=False) type_id = sa.Column('type_id', sa.types.Integer, sa.schema.ForeignKey('device_types.id')) type = orm.relation(DeviceType, primaryjoin=type_id == DeviceType.id) ... </code></pre> <p>Then in my (Pylons) controller I create a FormAlchemy form like this:</p> <pre><code>c.device = model.meta.Session.query(model.Device).get(device_id) fs = FieldSet(c.device, data=request.POST or None) fs.configure(options=[fs.ipv4.label(u'IP').readonly(), fs.type.label(u'Type').with_null_as((u'—', '')), fs.serial_number.label(u'S/N'), fs.mac.label(u'MAC')]) </code></pre> <p>The documentation says that "By default, NOT NULL columns are required. You can only add required-ness, not remove it.", but I want to allow non-NULL empty strings, which <code>validators.required</code> disallows. Is there something like <code>blank=True, null=False</code> in Django?</p> <p>To be more precise, I want a custom validator like one below, to either allow empty strings with <code>type=None</code> or all values to be set non-NULL and non-empty:</p> <pre><code># For use on fs.mac and fs.serial_number. # I haven't tested this code yet. def required_when_type_is_set(value, field): type_is_set = field.parent.type.value is not None: if value is None or (type_is_set and value.strip() = ''): raise validators.ValidationError(u'Please enter a value') </code></pre> <p>If possible, I'd like to refrain from monkey-patching <code>formalchemy.validators.required</code> or other kludges. I don't want to set <code>nullable=True</code> on model fields, because it doesn't seems to be proper solution too.</p> <p>What's the correct way to validate form in such case? Thanks for any suggestions in advance.</p>
3
2009-09-22T12:54:56Z
4,484,806
<p>This is exactly the same issue i'm having, where I often write interfaces for existing databases and want to use formalchemy but end up having to manually remove 'requiredness' as I am not able to change the database. </p>
0
2010-12-19T19:58:20Z
[ "python", "sqlalchemy", "validation", "pylons", "formalchemy" ]
Do not require non-NULL field (allow empty strings) in FormAlchemy
1,459,919
<p>I'm fairly novice to FormAlchemy and it seems that I don't get something. I have a SQLAlchemy model defined like this:</p> <pre><code>... class Device(meta.Base): __tablename__ = 'devices' id = sa.Column('id_device', sa.types.Integer, primary_key=True) serial_number = sa.Column('sn', sa.types.Unicode(length=20), nullable=False) mac = sa.Column('mac', sa.types.Unicode(length=12), nullable=False) ipv4 = sa.Column('ip', sa.types.Unicode(length=15), nullable=False) type_id = sa.Column('type_id', sa.types.Integer, sa.schema.ForeignKey('device_types.id')) type = orm.relation(DeviceType, primaryjoin=type_id == DeviceType.id) ... </code></pre> <p>Then in my (Pylons) controller I create a FormAlchemy form like this:</p> <pre><code>c.device = model.meta.Session.query(model.Device).get(device_id) fs = FieldSet(c.device, data=request.POST or None) fs.configure(options=[fs.ipv4.label(u'IP').readonly(), fs.type.label(u'Type').with_null_as((u'—', '')), fs.serial_number.label(u'S/N'), fs.mac.label(u'MAC')]) </code></pre> <p>The documentation says that "By default, NOT NULL columns are required. You can only add required-ness, not remove it.", but I want to allow non-NULL empty strings, which <code>validators.required</code> disallows. Is there something like <code>blank=True, null=False</code> in Django?</p> <p>To be more precise, I want a custom validator like one below, to either allow empty strings with <code>type=None</code> or all values to be set non-NULL and non-empty:</p> <pre><code># For use on fs.mac and fs.serial_number. # I haven't tested this code yet. def required_when_type_is_set(value, field): type_is_set = field.parent.type.value is not None: if value is None or (type_is_set and value.strip() = ''): raise validators.ValidationError(u'Please enter a value') </code></pre> <p>If possible, I'd like to refrain from monkey-patching <code>formalchemy.validators.required</code> or other kludges. I don't want to set <code>nullable=True</code> on model fields, because it doesn't seems to be proper solution too.</p> <p>What's the correct way to validate form in such case? Thanks for any suggestions in advance.</p>
3
2009-09-22T12:54:56Z
23,969,483
<p>You can teach FormAlchemy to not replace an empty input with None by changing the <code>null_as</code> column attribute.</p> <pre><code> whatever = Column(Unicode(999), required=False, null_as=("","\0"), nullable=False, default="", doc="Whatever for ever") </code></pre> <p>Formalchemy will replace input that's equal to the second member of the <code>null_as</code> tuple with <code>None</code>. (The first is the display text for SELECTs and similar fields.)</p> <p>If you set that to a string the user cannot input, this will never happen.</p>
0
2014-05-31T11:25:01Z
[ "python", "sqlalchemy", "validation", "pylons", "formalchemy" ]
KindError on setting a ReferenceProperty value
1,460,105
<p>This seemingly perfect Google App Engine code fails with a KindError.</p> <pre><code># in a django project 'stars' from google.appengine.ext import db class User(db.Model): pass class Picture(db.Model): user = db.ReferenceProperty(User) user = User() user.put() picture = Picture() picture.user = user # ===&gt; KindError: Property user must be an instance of stars_user </code></pre> <p>The exception is raised in google.appengine.ext.db.ReferenceProperty.validate:</p> <pre><code>def validate(self, value): ... if value is not None and not isinstance(value, self.reference_class): raise KindError('Property %s must be an instance of %s' % (self.name, self.reference_class.kind())) ... </code></pre>
1
2009-09-22T13:26:51Z
1,460,108
<p>Turns out that I was importing the model in admin.py as</p> <pre><code>from frontend.stars.models import Star </code></pre> <p>This line had contaminated the module namespace of <code>Star</code> and the <code>isinstance</code> query was failing.</p> <pre><code>&gt;&gt;&gt; user.__class__ &lt;class 'frontend.stars.models.User'&gt; &gt;&gt;&gt; Picture.user.reference_class &lt;class 'stars.models.User'&gt; </code></pre>
1
2009-09-22T13:27:12Z
[ "python", "google-app-engine" ]
Why pysqlite does not work properly?
1,460,136
<p>I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed:</p> <pre><code>python setup.py build </code></pre> <p>I got the following message in the end:</p> <pre><code>src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function) src/module.c:287: error: ‘SQLITE_READ’ undeclared here (not in a function) src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function) src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function) src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function) src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function) src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function) src/module.c: In function ‘init_sqlite’: src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’ src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast error: command 'gcc' failed with exit status 1 </code></pre> <p>I just ignored the last line and decided to continue. So, I typed:</p> <pre><code>python setup.py install </code></pre> <p>And than, again, I got similar error message:</p> <pre><code>src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function) src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function) src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function) src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function) src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function) src/module.c: In function ‘init_sqlite’: src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’ src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast error: command 'gcc' failed with exit status 1 </code></pre> <p>After that I wanted to try if pysqlite works. If in the python-command-line mode I type</p> <pre><code>from pysqlite2 import * </code></pre> <p>Python does not complain. However, if I try to follow an exmaple in my book:</p> <pre><code>from pysqlite2 import dbapi2 as sqlite </code></pre> <p>I get a error message:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "pysqlite2/dbapi2.py", line 27, in &lt;module&gt; from pysqlite2._sqlite import * ImportError: No module named _sqlite </code></pre> <p>Does anybody have any ideas why it happens and how this problem can be solved. By the way, I have installed a new version of Python. "python -V" gives me "Python 2.6.2". Thank you in advance for any help.</p>
1
2009-09-22T13:34:17Z
1,460,176
<blockquote> <p>I just ignored the last line and decided to continue.</p> </blockquote> <p>You can't just ignore the last line. It was telling you there was an error, so it couldn't compile. The next thing you ran told you it couldn't install because it couldn't compile. Then, your python told you it couldn't run the code because it wasn't installed. You need to get the compile step working before you move on to installing it.</p>
3
2009-09-22T13:41:09Z
[ "python", "sqlite", "installation", "pysqlite" ]
Why pysqlite does not work properly?
1,460,136
<p>I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed:</p> <pre><code>python setup.py build </code></pre> <p>I got the following message in the end:</p> <pre><code>src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function) src/module.c:287: error: ‘SQLITE_READ’ undeclared here (not in a function) src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function) src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function) src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function) src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function) src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function) src/module.c: In function ‘init_sqlite’: src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’ src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast error: command 'gcc' failed with exit status 1 </code></pre> <p>I just ignored the last line and decided to continue. So, I typed:</p> <pre><code>python setup.py install </code></pre> <p>And than, again, I got similar error message:</p> <pre><code>src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function) src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function) src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function) src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function) src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function) src/module.c: In function ‘init_sqlite’: src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’ src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast error: command 'gcc' failed with exit status 1 </code></pre> <p>After that I wanted to try if pysqlite works. If in the python-command-line mode I type</p> <pre><code>from pysqlite2 import * </code></pre> <p>Python does not complain. However, if I try to follow an exmaple in my book:</p> <pre><code>from pysqlite2 import dbapi2 as sqlite </code></pre> <p>I get a error message:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "pysqlite2/dbapi2.py", line 27, in &lt;module&gt; from pysqlite2._sqlite import * ImportError: No module named _sqlite </code></pre> <p>Does anybody have any ideas why it happens and how this problem can be solved. By the way, I have installed a new version of Python. "python -V" gives me "Python 2.6.2". Thank you in advance for any help.</p>
1
2009-09-22T13:34:17Z
1,460,311
<p>A lesson in compiling python extensions is needed, which distribution are you using ? You seem to be missing the sqlite headers with the given macro definitions. When the python setup runs it compiles bindings to the sqlite native binary and copies a few .py files to the library. The _sqlite is typically a .pyd file (equivalent to a dll) which has calls to the sqlite library, in your case that did not get built.</p> <p>Check the presence of the sqlite headers etc.</p>
2
2009-09-22T14:04:18Z
[ "python", "sqlite", "installation", "pysqlite" ]
Why pysqlite does not work properly?
1,460,136
<p>I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed:</p> <pre><code>python setup.py build </code></pre> <p>I got the following message in the end:</p> <pre><code>src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function) src/module.c:287: error: ‘SQLITE_READ’ undeclared here (not in a function) src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function) src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function) src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function) src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function) src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function) src/module.c: In function ‘init_sqlite’: src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’ src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast error: command 'gcc' failed with exit status 1 </code></pre> <p>I just ignored the last line and decided to continue. So, I typed:</p> <pre><code>python setup.py install </code></pre> <p>And than, again, I got similar error message:</p> <pre><code>src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function) src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function) src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function) src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function) src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function) src/module.c: In function ‘init_sqlite’: src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’ src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast error: command 'gcc' failed with exit status 1 </code></pre> <p>After that I wanted to try if pysqlite works. If in the python-command-line mode I type</p> <pre><code>from pysqlite2 import * </code></pre> <p>Python does not complain. However, if I try to follow an exmaple in my book:</p> <pre><code>from pysqlite2 import dbapi2 as sqlite </code></pre> <p>I get a error message:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "pysqlite2/dbapi2.py", line 27, in &lt;module&gt; from pysqlite2._sqlite import * ImportError: No module named _sqlite </code></pre> <p>Does anybody have any ideas why it happens and how this problem can be solved. By the way, I have installed a new version of Python. "python -V" gives me "Python 2.6.2". Thank you in advance for any help.</p>
1
2009-09-22T13:34:17Z
4,222,096
<p>The correct way to build pysqlite is now on the website.</p> <pre><code>$ tar xvfz &lt;version&gt;.tar.gz $ cd &lt;version&gt; $ python setup.py build_static install </code></pre> <p>The build_static will download the latest sqlite code and statically compile against it. For a note I just did this on a 1and1 shared host.</p> <p><a href="http://trac.edgewall.org/wiki/PySqlite#Buildingpysqlite" rel="nofollow">http://trac.edgewall.org/wiki/PySqlite#Buildingpysqlite</a></p>
2
2010-11-19T04:30:21Z
[ "python", "sqlite", "installation", "pysqlite" ]
epylint script is not working on Windows
1,460,275
<p>I have installed <a href="http://ftp.logilab.org/pub/pylint/pylint-0.18.1.tar.gz" rel="nofollow">http://ftp.logilab.org/pub/pylint/pylint-0.18.1.tar.gz</a> on Windows and now I am trying to configure my Emacs's flymake mode using epylint script. But it is not working. Here is the output of I got when I tried epylint on windows command prompt.</p> <pre><code>C:\&gt;epylint test.py 'test.py':1: [F] No module named 'test.py' </code></pre> <p>Did anyone tried this? Any suggestion on how to fix the problem.</p> <p>Thanks.</p>
0
2009-09-22T13:58:53Z
1,461,686
<p>Reading the documentation of the <code>epylint.lint</code> function:</p> <blockquote> <p>When run from emacs we will be in the directory of a file, and passed its filename. If this file is part of a package and is trying to import other modules from within its own package or another package rooted in a directory below it, pylint will classify it as a failed import.</p> <p>To get around this, we traverse down the directory tree to find the root of the package this module is in. We then invoke pylint from this directory.</p> <p>Finally, we must correct the filenames in the output generated by pylint so Emacs doesn't become confused (it will expect just the original filename, while pylint may extend it with extra directories if we've traversed down the tree)</p> </blockquote> <p>It sounds like it has to do some extra magic to work within Emacs. It doesn't look like you can run it the same way from the command line.</p> <p>Is it not working for you from within Emacs? It might be a bug in pylint then. Does pylint have a mailing list you can report issues to?</p>
0
2009-09-22T18:09:28Z
[ "python", "windows", "emacs", "pylint" ]
Why does Python keep a reference count on False and True?
1,460,454
<p>I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest:</p> <pre><code>Py_INCREF(Py_False); return Py_False; ... Py_INCREF(Py_True); return Py_True; </code></pre> <p>Aren't <code>Py_False</code> and <code>Py_True</code> global values? Just out of sheer curiosity, why is Python keeping a reference count for these variables?</p>
20
2009-09-22T14:33:04Z
1,460,492
<p>It's to make all object handling uniform. If I'm writing C code that handles a return value from a function, I have to increment and decrement the reference count on that object. If the function returns me True, I don't want to have to check to see if it's one of those special objects to know whether to manipulate its reference count. I can treat all objects identically.</p> <p>By treating True and False (and None, btw) the same as all other objects, the C code is much simpler throughout.</p>
20
2009-09-22T14:39:43Z
[ "python", "reference-counting", "python-c-api" ]
Verbose list comprehension in Python
1,460,484
<p>I have a list of integers and I want to create a new list with all elements smaller than a given limit.</p> <pre><code>a=range(15) #example list limit=9 #example limit </code></pre> <p>My approach to solve this problem was</p> <pre><code>[i for i in a if i &lt; limit] </code></pre> <p>To me the beginning 'i for i in' looks pretty verbose. Is there a <i>better</i> implementation in Python?</p>
0
2009-09-22T14:37:55Z
1,460,496
<p>You can use filter() (at least in the Python 2.x series... I think it might have been removed in 3.0)</p> <pre><code>newlist = filter(lambda item: item &lt; limit, oldlist) </code></pre> <p>The first argument can be any callable (its result will be coerced to boolean, so it's best to use a callable that returns boolean anyway), and the second argument can be any sequence.</p>
1
2009-09-22T14:40:15Z
[ "python", "list-comprehension" ]
Verbose list comprehension in Python
1,460,484
<p>I have a list of integers and I want to create a new list with all elements smaller than a given limit.</p> <pre><code>a=range(15) #example list limit=9 #example limit </code></pre> <p>My approach to solve this problem was</p> <pre><code>[i for i in a if i &lt; limit] </code></pre> <p>To me the beginning 'i for i in' looks pretty verbose. Is there a <i>better</i> implementation in Python?</p>
0
2009-09-22T14:37:55Z
1,460,497
<p>You could use <a href="http://docs.python.org/library/functions.html#filter" rel="nofollow">filter</a></p> <pre><code>&gt;&gt;&gt; filter(lambda i: i &lt; limit, a) [0, 1, 2, 3, 4, 5, 6, 7, 8] </code></pre> <p>But list comprehensions are the preferred way to do it</p> <p>Here is what <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">python docs</a> has to say about this:</p> <blockquote> <p>List comprehensions provide a concise way to create lists without resorting to use of map(), filter() and/or lambda. The resulting list definition tends often to be clearer than lists built using those constructs.</p> </blockquote>
4
2009-09-22T14:40:16Z
[ "python", "list-comprehension" ]
Verbose list comprehension in Python
1,460,484
<p>I have a list of integers and I want to create a new list with all elements smaller than a given limit.</p> <pre><code>a=range(15) #example list limit=9 #example limit </code></pre> <p>My approach to solve this problem was</p> <pre><code>[i for i in a if i &lt; limit] </code></pre> <p>To me the beginning 'i for i in' looks pretty verbose. Is there a <i>better</i> implementation in Python?</p>
0
2009-09-22T14:37:55Z
1,460,514
<p>This is about the best you can do. You may be able to do better with filter, but I wouldn't recommend it. Bear in mind that the list comprehension reads almost like english: "i for i in a if i &lt; limit". This makes it much easier to read and understand, if a little on the verbose side.</p>
2
2009-09-22T14:43:39Z
[ "python", "list-comprehension" ]
Verbose list comprehension in Python
1,460,484
<p>I have a list of integers and I want to create a new list with all elements smaller than a given limit.</p> <pre><code>a=range(15) #example list limit=9 #example limit </code></pre> <p>My approach to solve this problem was</p> <pre><code>[i for i in a if i &lt; limit] </code></pre> <p>To me the beginning 'i for i in' looks pretty verbose. Is there a <i>better</i> implementation in Python?</p>
0
2009-09-22T14:37:55Z
1,460,582
<p>The nicer versions require boilerplate code, so the list comprehension is as nice as you can get.</p> <p>This would be one different way to do it:</p> <pre><code>from operator import ge from functools import partial filter(partial(ge, limit), a) </code></pre> <p>(But if you were to use <code>filter</code>, <a href="http://stackoverflow.com/questions/1460484/verbose-list-comprehension-in-python/1460497#1460497">Nadia's way</a> would be the obvious way to do it)</p>
0
2009-09-22T14:54:43Z
[ "python", "list-comprehension" ]
How can I get the element of a list that has a minimum/maximum property in Python?
1,460,512
<p>I have the following array in Python:</p> <pre><code>points_list = [point0, point1, point2] </code></pre> <p>where each of <code>points_list</code> is of the type:</p> <pre><code>class point: __init__(self, coord, value): self.coord = numpy.array(coord) self.value = value # etc... </code></pre> <p>And a function:</p> <pre><code>def distance(x,y): return numpy.linalg.norm(x.coord - y.coord) </code></pre> <p>And I have a point <code>point_a</code> defined elsewhere. Now I want to find the point in <code>points_list</code> that's closest to <code>point_a</code>.</p> <p>Other than a loop, what's the best way to do this in Python?</p>
2
2009-09-22T14:43:06Z
1,460,531
<p>Have you tried this?</p> <pre><code>min(points_list, key=lambda x: distance(x, point_a)) </code></pre> <p><strong>To answer a question in comment</strong>: <code>lambda</code> is indeed necessary here since <a href="http://docs.python.org/3.1/library/functions.html#min" rel="nofollow">function specified as a <code>key</code> argument needs to accept only a single argument</a>.</p> <p><em>However</em>, since your <code>point_a</code> is essentially global you could "hard-code" it into the <code>distance</code> function:</p> <pre><code>&gt;&gt;&gt; point_a = point([1, 2, 3], 5) &gt;&gt;&gt; def distance(x): return numpy.linalg.norm(x.coord - point_a.coord) </code></pre> <p>This way you could pass <code>distance</code> as a key argument skipping <code>lambda</code> altogether.</p> <pre><code>&gt;&gt;&gt; min(points_list, key=distance) </code></pre>
13
2009-09-22T14:46:56Z
[ "python", "list" ]
Charts with proper unicode support
1,460,587
<p>I want to create simple charts like pies and bars in python.</p> <p>I tried out <code>CairoPlot</code> and <code>pycha</code>. Both look amazing, but they seem not to be able to handle unicode characters properly.</p> <pre><code>CairoPlot.pie_plot(name='test.png', width=800, height=600, data={'eins':100, 'zwei':48, 'drei':90, 'vier':98,u'fünf':187}) </code></pre> <p>result in <code>fünf</code> instead of <code>fünf</code>.</p> <p>Is there an easy to use module with proven support for unicode? or did you make <code>CairoPlot</code> or <code>pycha</code> display the unicodes correctly? </p> <p>I prefer in-house solution, so google chart is not what I want.</p> <p><strong>edit</strong></p> <p>ironfroggy's answer made me try this</p> <pre><code>CairoPlot.pie_plot(name='test.png', width=800, height=600, data={'eins':100, 'zwei':48, 'drei':90, 'vier':98,'f\xc3\xbcnf':187}) </code></pre> <p>this works.</p> <p>What is a safe way to convert unicode-strings to ascii-strings with escaped non-ascii characters?</p> <p><strong>edit 2</strong></p> <pre><code>u'fünf'.encode('latin-1') </code></pre> <p>does the trick. Thanks!</p> <p><strong>edit 3</strong></p> <p>for pycha it worked in the same way</p> <pre><code>dataSet = ( ('dataSet 1', ((0, 1), (1, 3), (2, 2.5))), ('dataSet 2', ((0, 2), (1, 4), (2, 3))), (u'dataSet Ü'.encode('latin-1'), ((0, 5), (1, 1), (2, 0.5))), ) chart = pycha.bar.VerticalBarChart(surface) chart.addDataset(dataSet) chart.render() surface.write_to_png('output.png') </code></pre>
1
2009-09-22T14:55:21Z
1,460,633
<p>Be careful including non-ASCII directly in your source. Are you including an encoding hint in your source?</p> <pre><code>#!/usr/bin/env python # -*- encoding: utf-8 -*- </code></pre> <p>And, of course, are you sure your editor is properly saving the file in the encoding you think it is? The safest bet is still to keep source in ASCII and to do unicode string literals with escaped non-ASCII characters (like \UXXXX where XXXX is your codepoint).</p>
1
2009-09-22T15:01:59Z
[ "python", "unicode", "encoding", "charts", "cairoplot" ]
Charts with proper unicode support
1,460,587
<p>I want to create simple charts like pies and bars in python.</p> <p>I tried out <code>CairoPlot</code> and <code>pycha</code>. Both look amazing, but they seem not to be able to handle unicode characters properly.</p> <pre><code>CairoPlot.pie_plot(name='test.png', width=800, height=600, data={'eins':100, 'zwei':48, 'drei':90, 'vier':98,u'fünf':187}) </code></pre> <p>result in <code>fünf</code> instead of <code>fünf</code>.</p> <p>Is there an easy to use module with proven support for unicode? or did you make <code>CairoPlot</code> or <code>pycha</code> display the unicodes correctly? </p> <p>I prefer in-house solution, so google chart is not what I want.</p> <p><strong>edit</strong></p> <p>ironfroggy's answer made me try this</p> <pre><code>CairoPlot.pie_plot(name='test.png', width=800, height=600, data={'eins':100, 'zwei':48, 'drei':90, 'vier':98,'f\xc3\xbcnf':187}) </code></pre> <p>this works.</p> <p>What is a safe way to convert unicode-strings to ascii-strings with escaped non-ascii characters?</p> <p><strong>edit 2</strong></p> <pre><code>u'fünf'.encode('latin-1') </code></pre> <p>does the trick. Thanks!</p> <p><strong>edit 3</strong></p> <p>for pycha it worked in the same way</p> <pre><code>dataSet = ( ('dataSet 1', ((0, 1), (1, 3), (2, 2.5))), ('dataSet 2', ((0, 2), (1, 4), (2, 3))), (u'dataSet Ü'.encode('latin-1'), ((0, 5), (1, 1), (2, 0.5))), ) chart = pycha.bar.VerticalBarChart(surface) chart.addDataset(dataSet) chart.render() surface.write_to_png('output.png') </code></pre>
1
2009-09-22T14:55:21Z
29,546,019
<p>Try to use a third party library to replace the garbage unicode , i will be happy to provide you with a one upon professional consulation</p>
1
2015-04-09T18:18:05Z
[ "python", "unicode", "encoding", "charts", "cairoplot" ]
Related to executing Java programs through Python
1,460,590
<p>I am using os.system to execute a java program through a python script. I need to pass a file name to the java program as an argument. I am not able to figure out how to pass the relative file location. What should be my reference for determining the relative location. I tried to use the location of the python script as the reference but doesn't work.</p>
1
2009-09-22T14:55:50Z
1,460,615
<p>See the subprocess module for all your external process invoking needs.</p> <pre><code>p = subprocess.Popen(['myjavaapp', 'afilename.txt']) </code></pre> <p>If you need to get the relative location and you aren't sure how the other command is going to take it, make it absolute.</p> <pre><code>p = subprocess.Popen(['myjavaapp', os.path.abspath('afilename.txt')]) </code></pre>
2
2009-09-22T14:59:20Z
[ "java", "python" ]
How to decompile a regex?
1,460,686
<p>Is there any way to decompile a regular expression once compiled?</p>
14
2009-09-22T15:09:24Z
1,460,695
<pre><code>r = re.compile('some[pattern]'); print r.pattern </code></pre>
8
2009-09-22T15:11:01Z
[ "python", "regex" ]
How to decompile a regex?
1,460,686
<p>Is there any way to decompile a regular expression once compiled?</p>
14
2009-09-22T15:09:24Z
1,460,699
<p>Compiled regular expression objects have a "pattern" attribute which gives the original text pattern.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; regex = re.compile('foo (?:bar)*') &gt;&gt;&gt; regex.pattern 'foo (?:bar)*' </code></pre>
32
2009-09-22T15:11:31Z
[ "python", "regex" ]
wxpython drag&drop focus problem
1,460,722
<p>I'd like to implement drag&amp;drop in wxPython that works in similar way that in WordPad/Eclipse etc. I mean the following:</p> <p>when something is being dropped to WordPad, WordPad window is on top with focus and text is added. In Eclipse editor text is pasted, Eclipse window gains focus and is on top.</p> <p>When I implement drag&amp;drop using wxPython target window is not brought to front. I implemented drag&amp;drop in similar way to (drag):</p> <pre><code>import wx class DragFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.tree = wx.TreeCtrl(self, wx.ID_ANY) root = self.tree.AddRoot("root item") self.tree.AppendItem(root, "child 1") self.tree.Bind(wx.EVT_TREE_BEGIN_DRAG, self.__onBeginDrag) def __onBeginDrag(self, event): tdo = wx.PyTextDataObject(self.tree.GetItemText(event.GetItem())) dropSource = wx.DropSource(self.tree) dropSource.SetData(tdo) dropSource.DoDragDrop(True) app = wx.PySimpleApp() frame = DragFrame() app.SetTopWindow(frame) frame.Show() app.MainLoop() </code></pre> <p><hr /></p> <p>Second program (drop):</p> <pre><code>import wx class TextDropTarget(wx.TextDropTarget): def __init__(self, obj): wx.TextDropTarget.__init__(self) self.obj = obj def OnDropText(self, x, y, data): self.obj.WriteText(data + '\n\n') wx.MessageBox("Error", "Error", style = wx.ICON_ERROR) class DropFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) text = wx.TextCtrl(self, wx.ID_ANY) text.SetDropTarget(TextDropTarget(text)) app = wx.PySimpleApp() frame = DropFrame() app.SetTopWindow(frame) frame.Show() app.MainLoop() </code></pre> <p>When you run both programs, place windows in the centre of the screen (part of drop window is visible), then drag a node from drag window to drop window - target window displays message box which isn't visible, target window is hidden behind source window. </p> <p>How to implement drag&amp;drop that will focus on the second (target) window? I've tried adding window.Show(), window.SetFocus(), even using some functions of WinAPI (through win32gui). I think there should be some standard way of doing this. What am I missing?</p>
2
2009-09-22T15:16:49Z
1,461,564
<p>Wouldn't this work?</p> <pre><code>class DropFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) text = wx.TextCtrl(self, wx.ID_ANY) self.SetFocus() # Set's the focus to this window, allowing it to receive keyboard input. text.SetDropTarget(TextDropTarget(text)) </code></pre> <p><a href="http://www.wxpython.org/docs/api/wx.Frame-class.html" rel="nofollow"><code>wx.Frame</code></a> inherits from <a href="http://www.wxpython.org/docs/api/wx.Window-class.html" rel="nofollow"><code>wx.Window</code></a>, that has <a href="http://www.wxpython.org/docs/api/wx.Window-class.html#SetFocus" rel="nofollow"><code>SetFocus(self)</code></a>.</p> <p><hr /></p> <p>I have just tested it and it works. Just moved <code>SetFocus</code> before <code>SetDropTarget</code>, as its a cleaner behavior.</p>
0
2009-09-22T17:52:20Z
[ "python", "drag-and-drop", "wxpython", "focus" ]
wxpython drag&drop focus problem
1,460,722
<p>I'd like to implement drag&amp;drop in wxPython that works in similar way that in WordPad/Eclipse etc. I mean the following:</p> <p>when something is being dropped to WordPad, WordPad window is on top with focus and text is added. In Eclipse editor text is pasted, Eclipse window gains focus and is on top.</p> <p>When I implement drag&amp;drop using wxPython target window is not brought to front. I implemented drag&amp;drop in similar way to (drag):</p> <pre><code>import wx class DragFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.tree = wx.TreeCtrl(self, wx.ID_ANY) root = self.tree.AddRoot("root item") self.tree.AppendItem(root, "child 1") self.tree.Bind(wx.EVT_TREE_BEGIN_DRAG, self.__onBeginDrag) def __onBeginDrag(self, event): tdo = wx.PyTextDataObject(self.tree.GetItemText(event.GetItem())) dropSource = wx.DropSource(self.tree) dropSource.SetData(tdo) dropSource.DoDragDrop(True) app = wx.PySimpleApp() frame = DragFrame() app.SetTopWindow(frame) frame.Show() app.MainLoop() </code></pre> <p><hr /></p> <p>Second program (drop):</p> <pre><code>import wx class TextDropTarget(wx.TextDropTarget): def __init__(self, obj): wx.TextDropTarget.__init__(self) self.obj = obj def OnDropText(self, x, y, data): self.obj.WriteText(data + '\n\n') wx.MessageBox("Error", "Error", style = wx.ICON_ERROR) class DropFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) text = wx.TextCtrl(self, wx.ID_ANY) text.SetDropTarget(TextDropTarget(text)) app = wx.PySimpleApp() frame = DropFrame() app.SetTopWindow(frame) frame.Show() app.MainLoop() </code></pre> <p>When you run both programs, place windows in the centre of the screen (part of drop window is visible), then drag a node from drag window to drop window - target window displays message box which isn't visible, target window is hidden behind source window. </p> <p>How to implement drag&amp;drop that will focus on the second (target) window? I've tried adding window.Show(), window.SetFocus(), even using some functions of WinAPI (through win32gui). I think there should be some standard way of doing this. What am I missing?</p>
2
2009-09-22T15:16:49Z
1,464,342
<p>You need to do anything you want int DragOver method of DropTarget e.g. there you can raise and set focus on your window</p> <p>sample working code for target</p> <pre><code>import wx class TextDropTarget(wx.TextDropTarget): def __init__(self, obj, callback): wx.TextDropTarget.__init__(self) self.obj = obj self._callback = callback def OnDropText(self, x, y, data): self.obj.WriteText(data + '\n\n') wx.MessageBox("Error", "Error", style = wx.ICON_ERROR) def OnDragOver(self, *args): wx.CallAfter(self._callback) return wx.TextDropTarget.OnDragOver(self, *args) class DropFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) text = wx.TextCtrl(self, wx.ID_ANY) text.SetDropTarget(TextDropTarget(text, self._callback)) def _callback(self): self.Raise() self.SetFocus() app = wx.PySimpleApp() frame = DropFrame() app.SetTopWindow(frame) frame.Show() app.MainLoop() </code></pre>
1
2009-09-23T06:56:19Z
[ "python", "drag-and-drop", "wxpython", "focus" ]
Installing Mercurial on Mac OS X 10.6 Snow Leopard
1,461,374
<h1>Installing Mercurial on Mac OS X 10.6 Snow Leopard</h1> <p>I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following:</p> <pre><code>cd ~/src curl -O http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install </code></pre> <p>This installs the site-packages files for Mercurial in <code>/usr/local/lib/python2.6/site-packages/</code>. I know that installing Mercurial from the Mac Disk Image will install the files into <code>/Library/Python/2.6/site-packages/</code>, which is the site-packages directory for the Mac OS X default Python install.</p> <p>I have Python 2.6.2+ installed as a Framework with its site-packages directory in:</p> <blockquote> <p>/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages</p> </blockquote> <p>With Mercurial installed this way, I have to issue:</p> <blockquote> <p>PYTHONPATH=/usr/local/lib/python2.6/site-packages:"${PYTHONPATH}"</p> </blockquote> <p>in order to get Mercurial to work.</p> <h3>Questions</h3> <ul> <li>How can I install Mercurial from source with the site-packages in a different directory?</li> <li>Is there an advantage or disadvantage to having the site-packages in the current location? Would it be better in one of the Python site-package directories that already exist?</li> <li>Do I need to be concerned about virtualenv working correctly since I have modified PYTHONPATH (or any other conflicts for that matter)?</li> </ul> <h3>Reasons for Installing from Source</h3> <p><a href="http://hivelogic.com/about" rel="nofollow">Dan Benjamin</a> of <a href="http://hivelogic.com/" rel="nofollow">Hivelogic</a> provides the benefits of and instructions for installing Mercurial from source in his article <a href="http://hivelogic.com/articles/compiling-mercurial-on-snow-leopard/" rel="nofollow">Installing Mercurial on Snow Leopard</a>.</p>
13
2009-09-22T17:13:09Z
1,462,607
<p>Especially since you have Python 2.6 available you can do something like <code>python setup.py install --user</code>, which will install Mercurial with ~/.local as prefix. You don't have to change the PYTHONPATH for this but only add ~/.local/bin to your PATH.</p> <p>Regarding advantages and disadvantages: That all depends on what your PYTHONPATH in general looks like since modifying it will naturally modify the load order of packages (which becomes relevant if you have one version of Mercurial installed with one prefix and another with a different prefix). In general, I try to put all custom packages into a certain site-packages folder (say /usr/local/lib/python2.6/site-packages). Again: If you are the only person who will use those libs, the --user flag provided by Python 2.6's distutils makes something like this pretty easy (with adding ~/.local to the default search path for modules).</p> <p>virtualenv should work just fine as long you your PYTHONPATH is used consistently.</p>
8
2009-09-22T21:08:11Z
[ "python", "osx", "mercurial", "osx-snow-leopard" ]