title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
How to debug Web2py applications? | 315,165 | <p>Is it possible?
By debug I mean setting breakpoints, inspect values and advance step by step.</p>
| 16 | 2008-11-24T19:27:05Z | 4,806,333 | <p>I'm debugging web2py applications with Eclipse and PyDev. Here is an article:
<a href="http://www.web2pyslices.com/main/slices/take_slice/2" rel="nofollow">http://www.web2pyslices.com/main/slices/take_slice/2</a></p>
| 1 | 2011-01-26T15:27:53Z | [
"python",
"debugging",
"web2py"
] |
How to debug Web2py applications? | 315,165 | <p>Is it possible?
By debug I mean setting breakpoints, inspect values and advance step by step.</p>
| 16 | 2008-11-24T19:27:05Z | 9,620,478 | <p>You can also use Visual Studio 2010. Here's how:</p>
<ul>
<li>Download and install <a href="http://pytools.codeplex.com/">Python Tools for Visual Studio</a>.</li>
<li>Create a new project from existing code (<em>File > New > Project From Existing Code...</em>)</li>
<li>Specify your web2py folder and use the defaults.</li>
<li>Right-click on web2py.py and choose <em>Set as Startup File</em>.</li>
<li>Set breakpoints and hit F5 (run) or right-click on web2py.py and choose <em>Start with Debugging</em>.</li>
</ul>
<p>This is a nice setup if you already use visual studio.</p>
| 6 | 2012-03-08T15:45:57Z | [
"python",
"debugging",
"web2py"
] |
Properly formatted example for Python iMAP email access? | 315,362 | <p>tldr: Can someone show me how to properly format this Python iMAP example so it works?</p>
<p>from
<a href="https://docs.python.org/2.4/lib/imap4-example.html" rel="nofollow">https://docs.python.org/2.4/lib/imap4-example.html</a></p>
<blockquote>
<pre><code>import getpass, imaplib
M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()
</code></pre>
</blockquote>
<p>Assuming my email is "[email protected]" and the password is "password," how should this look? I tried <code>M.login(getpass.getuser([email protected]), getpass.getpass(password))</code>
and it timed out. Complete newb here, so it's very likely I missed something obvious (like creating an iMAP object first? Not sure).</p>
| 9 | 2008-11-24T20:31:14Z | 315,387 | <p>Did you forget to specify the IMAP host and port? Use something to the effect of:</p>
<pre><code>M = imaplib.IMAP4_SSL( 'imap.gmail.com' )
</code></pre>
<p>or, </p>
<pre><code>M = imaplib.IMAP4_SSL()
M.open( 'imap.gmail.com' )
</code></pre>
| 2 | 2008-11-24T20:39:52Z | [
"python",
"email",
"imap"
] |
Properly formatted example for Python iMAP email access? | 315,362 | <p>tldr: Can someone show me how to properly format this Python iMAP example so it works?</p>
<p>from
<a href="https://docs.python.org/2.4/lib/imap4-example.html" rel="nofollow">https://docs.python.org/2.4/lib/imap4-example.html</a></p>
<blockquote>
<pre><code>import getpass, imaplib
M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()
</code></pre>
</blockquote>
<p>Assuming my email is "[email protected]" and the password is "password," how should this look? I tried <code>M.login(getpass.getuser([email protected]), getpass.getpass(password))</code>
and it timed out. Complete newb here, so it's very likely I missed something obvious (like creating an iMAP object first? Not sure).</p>
| 9 | 2008-11-24T20:31:14Z | 315,710 | <pre><code>import imaplib
# you want to connect to a server; specify which server
server= imaplib.IMAP4_SSL('imap.googlemail.com')
# after connecting, tell the server who you are
server.login('[email protected]', 'password')
# this will show you a list of available folders
# possibly your Inbox is called INBOX, but check the list of mailboxes
code, mailboxen= server.list()
print mailboxen
# if it's called INBOX, thenâ¦
server.select("INBOX")
</code></pre>
<p>The rest of your code seems correct.</p>
| 10 | 2008-11-24T22:18:52Z | [
"python",
"email",
"imap"
] |
Properly formatted example for Python iMAP email access? | 315,362 | <p>tldr: Can someone show me how to properly format this Python iMAP example so it works?</p>
<p>from
<a href="https://docs.python.org/2.4/lib/imap4-example.html" rel="nofollow">https://docs.python.org/2.4/lib/imap4-example.html</a></p>
<blockquote>
<pre><code>import getpass, imaplib
M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()
</code></pre>
</blockquote>
<p>Assuming my email is "[email protected]" and the password is "password," how should this look? I tried <code>M.login(getpass.getuser([email protected]), getpass.getpass(password))</code>
and it timed out. Complete newb here, so it's very likely I missed something obvious (like creating an iMAP object first? Not sure).</p>
| 9 | 2008-11-24T20:31:14Z | 316,457 | <p>Here is a script I used to use to grab logwatch info from my mailbox. <a href="http://brianlane.com/articles/lfnw2008/">Presented at LFNW 2008</a> - </p>
<pre><code>#!/usr/bin/env python
''' Utility to scan my mailbox for new mesages from Logwatch on systems and then
grab useful info from the message and output a summary page.
by Brian C. Lane <[email protected]>
'''
import os, sys, imaplib, rfc822, re, StringIO
server ='mail.brianlane.com'
username='yourusername'
password='yourpassword'
M = imaplib.IMAP4_SSL(server)
M.login(username, password)
M.select()
typ, data = M.search(None, '(UNSEEN SUBJECT "Logwatch")')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
# print 'Message %s\n%s\n' % (num, data[0][1])
match = re.search( "^(Users logging in.*?)^\w",
data[0][1],
re.MULTILINE|re.DOTALL )
if match:
file = StringIO.StringIO(data[0][1])
message = rfc822.Message(file)
print message['from']
print match.group(1).strip()
print '----'
M.close()
M.logout()
</code></pre>
| 10 | 2008-11-25T05:42:27Z | [
"python",
"email",
"imap"
] |
Properly formatted example for Python iMAP email access? | 315,362 | <p>tldr: Can someone show me how to properly format this Python iMAP example so it works?</p>
<p>from
<a href="https://docs.python.org/2.4/lib/imap4-example.html" rel="nofollow">https://docs.python.org/2.4/lib/imap4-example.html</a></p>
<blockquote>
<pre><code>import getpass, imaplib
M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()
</code></pre>
</blockquote>
<p>Assuming my email is "[email protected]" and the password is "password," how should this look? I tried <code>M.login(getpass.getuser([email protected]), getpass.getpass(password))</code>
and it timed out. Complete newb here, so it's very likely I missed something obvious (like creating an iMAP object first? Not sure).</p>
| 9 | 2008-11-24T20:31:14Z | 29,733,692 | <p>Instead of <code>M.login(getpass.getuser([email protected]), getpass.getpass(password))</code> you need to use <code>M.login('[email protected]', 'password')</code>, i.e. plain strings (or better, variables containing them). Your attempt actually shouldn't have worked at all, since <a href="https://docs.python.org/2/library/getpass.html" rel="nofollow"><code>getpass</code></a>'s <code>getuser</code> doesn't take arguments but merely returns the user login name. And <code>[email protected]</code> isn't even a valid variable name (you didn't put it into quotes)...</p>
| 0 | 2015-04-19T18:01:18Z | [
"python",
"email",
"imap"
] |
Spambots are cluttering my log file [Django] | 315,363 | <p>I have a nice and lovely Django site up and running, but have noticed that my <code>error.log</code> file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like <code>http://mysite.com/ie</code> or <code>http://mysite.com/~admin.php</code> etc. </p>
<p>Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a <code>TemplateDoesNotExist</code> exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.</p>
<p>Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?</p>
| 3 | 2008-11-24T20:31:20Z | 315,394 | <p>A programming solution would be to :</p>
<ul>
<li>open the log file</li>
<li>read the lines in a buffer</li>
<li>replace the lines that match the errors the bots caused</li>
<li>seek to the beginning of the file</li>
<li>write the new buffer</li>
<li>truncate the file to current pointer position</li>
<li>close</li>
</ul>
<p>Voila ! It's done !</p>
| 0 | 2008-11-24T20:41:43Z | [
"python",
"django",
"apache",
"spam-prevention"
] |
Spambots are cluttering my log file [Django] | 315,363 | <p>I have a nice and lovely Django site up and running, but have noticed that my <code>error.log</code> file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like <code>http://mysite.com/ie</code> or <code>http://mysite.com/~admin.php</code> etc. </p>
<p>Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a <code>TemplateDoesNotExist</code> exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.</p>
<p>Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?</p>
| 3 | 2008-11-24T20:31:20Z | 315,400 | <p>Um, perhaps, use <a href="http://linuxcommand.org/man_pages/logrotate8.html" rel="nofollow">logrotate</a> to rotate and compress the logs periodically, if it isn't being done already.</p>
| 6 | 2008-11-24T20:44:05Z | [
"python",
"django",
"apache",
"spam-prevention"
] |
Spambots are cluttering my log file [Django] | 315,363 | <p>I have a nice and lovely Django site up and running, but have noticed that my <code>error.log</code> file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like <code>http://mysite.com/ie</code> or <code>http://mysite.com/~admin.php</code> etc. </p>
<p>Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a <code>TemplateDoesNotExist</code> exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.</p>
<p>Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?</p>
| 3 | 2008-11-24T20:31:20Z | 315,467 | <p>"Is there a way to turn this behavior off?" - the 500 is absolutely mandatory. The log entry is also mandatory. </p>
<p>"Or perhaps just block the IP's doing this?" - don't we wish.</p>
<p>Everyone has this problem. Just about everyone uses Apache <a href="http://httpd.apache.org/docs/1.3/logs.html#rotation" rel="nofollow">log rotation</a>. Everyone else either uses an OS rotation or rolls their own.</p>
| 3 | 2008-11-24T21:06:03Z | [
"python",
"django",
"apache",
"spam-prevention"
] |
Spambots are cluttering my log file [Django] | 315,363 | <p>I have a nice and lovely Django site up and running, but have noticed that my <code>error.log</code> file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like <code>http://mysite.com/ie</code> or <code>http://mysite.com/~admin.php</code> etc. </p>
<p>Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a <code>TemplateDoesNotExist</code> exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.</p>
<p>Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?</p>
| 3 | 2008-11-24T20:31:20Z | 315,596 | <p>If you can find a pattern in UserAgent string, you may use <code>DISALLOWED_USER_AGENT</code> setting. Mine is:</p>
<pre><code>DISALLOWED_USER_AGENTS = (
re.compile(r'Java'),
re.compile(r'gigamega'),
re.compile(r'litefinder'),
)
</code></pre>
<p>See the description in <a href="http://docs.djangoproject.com/en/dev/ref/settings/#disallowed-user-agents" rel="nofollow">Django docs</a>.</p>
| 3 | 2008-11-24T21:39:47Z | [
"python",
"django",
"apache",
"spam-prevention"
] |
Spambots are cluttering my log file [Django] | 315,363 | <p>I have a nice and lovely Django site up and running, but have noticed that my <code>error.log</code> file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like <code>http://mysite.com/ie</code> or <code>http://mysite.com/~admin.php</code> etc. </p>
<p>Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a <code>TemplateDoesNotExist</code> exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.</p>
<p>Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?</p>
| 3 | 2008-11-24T20:31:20Z | 315,615 | <p>How about setting up a catch-all pattern as the last item in your urls file and directing it to a generic "no such page" or even your homepage? In other words, turn 500's into requests for your homepage.</p>
| 0 | 2008-11-24T21:46:38Z | [
"python",
"django",
"apache",
"spam-prevention"
] |
Spambots are cluttering my log file [Django] | 315,363 | <p>I have a nice and lovely Django site up and running, but have noticed that my <code>error.log</code> file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like <code>http://mysite.com/ie</code> or <code>http://mysite.com/~admin.php</code> etc. </p>
<p>Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a <code>TemplateDoesNotExist</code> exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.</p>
<p>Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?</p>
| 3 | 2008-11-24T20:31:20Z | 316,103 | <p>Why not fix those "bugs"? If a url pattern is not matched, then a proper error message should be shown. By adding those templates you will <a href="http://www.codinghorror.com/blog/archives/000819.html" rel="nofollow">help the user</a> and yourself :-)</p>
| 0 | 2008-11-25T01:26:56Z | [
"python",
"django",
"apache",
"spam-prevention"
] |
Spambots are cluttering my log file [Django] | 315,363 | <p>I have a nice and lovely Django site up and running, but have noticed that my <code>error.log</code> file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like <code>http://mysite.com/ie</code> or <code>http://mysite.com/~admin.php</code> etc. </p>
<p>Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a <code>TemplateDoesNotExist</code> exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.</p>
<p>Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?</p>
| 3 | 2008-11-24T20:31:20Z | 317,923 | <p>Django should be throwing a 404, not a 500, if the URL doesn't match any entries in your URLConf.</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#handler404" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/http/urls/#handler404</a></p>
<p>You need to provide a 404 template:</p>
<blockquote>
<p>If you don't define your own 404 view -- and simply use the default, which is recommended -- you still have one obligation: To create a 404.html template in the root of your template directory. The default 404 view will use that template for all 404 errors.</p>
</blockquote>
| 2 | 2008-11-25T16:17:47Z | [
"python",
"django",
"apache",
"spam-prevention"
] |
Spambots are cluttering my log file [Django] | 315,363 | <p>I have a nice and lovely Django site up and running, but have noticed that my <code>error.log</code> file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like <code>http://mysite.com/ie</code> or <code>http://mysite.com/~admin.php</code> etc. </p>
<p>Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a <code>TemplateDoesNotExist</code> exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.</p>
<p>Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?</p>
| 3 | 2008-11-24T20:31:20Z | 318,079 | <ol>
<li><p>Yes, it should be a 404, not a 500. 500 indicates something is trying to deal with the URL and is failing in the process. You need to find and fix that.</p></li>
<li><p>We have a similar problem. Since we are running Apache/mod_python, I chose to deal with it in .htaccess with mod_rewrite rules. I periodically look at the logs and add a few patterns to my "go to hell" list. These all rewrite to deliver a 1x1 pixel gif file. There is no tsunami of 404s to clutter up my log analysis and it puts minimal load on Django and Apache.</p></li>
</ol>
<p>You can't make these a**holes go away, so all you can do is minimize their impact on your system and get on with your life.</p>
| 0 | 2008-11-25T16:52:54Z | [
"python",
"django",
"apache",
"spam-prevention"
] |
How do I search through a folder for the filename that matches a regular expression using Python? | 315,381 | <p>I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An example would be very much appreciated. Thanks in advance. </p>
| 2 | 2008-11-24T20:38:45Z | 315,404 | <ol>
<li><p>Read about the <a href="http://www.python.org/doc/2.5.2/lib/module-re.html" rel="nofollow">RE</a> pattern's <code>match</code> method. </p></li>
<li><p>Read all answers to <a href="http://stackoverflow.com/questions/296173/how-do-i-copy-files-with-specific-file-extension-to-a-folder-in-my-python-versi">How do I copy files with specific file extension to a folder in my python (version 2.5) script</a>?</p></li>
<li><p>Pick one that uses <code>fnmatch</code>. Replace <code>fnmatch</code> with <code>re.match</code>. This requires careful thought. It's not a cut-and-paste.</p></li>
<li><p>Then, ask specific questions.</p></li>
</ol>
| 2 | 2008-11-24T20:44:50Z | [
"python",
"regex"
] |
How do I search through a folder for the filename that matches a regular expression using Python? | 315,381 | <p>I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An example would be very much appreciated. Thanks in advance. </p>
| 2 | 2008-11-24T20:38:45Z | 315,430 | <p>This will find all files starting with two digits and ending in gif, you can add the files into a global list, if you wish:</p>
<pre><code>import re
import os
r = re.compile(r'\d{2}.+gif$')
for root, dirs, files in os.walk('/home/vinko'):
l = [os.path.join(root,x) for x in files if r.match(x)]
if l: print l #Or append to a global list, whatever
</code></pre>
| 8 | 2008-11-24T20:51:04Z | [
"python",
"regex"
] |
How do I search through a folder for the filename that matches a regular expression using Python? | 315,381 | <p>I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An example would be very much appreciated. Thanks in advance. </p>
| 2 | 2008-11-24T20:38:45Z | 315,446 | <p>If the pattern you have to match is simple enough to grab with filesystem wildcards, I recommend you take a look at the glob module, which exists for this exact purpose.</p>
| 1 | 2008-11-24T20:59:28Z | [
"python",
"regex"
] |
How do I search through a folder for the filename that matches a regular expression using Python? | 315,381 | <p>I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An example would be very much appreciated. Thanks in advance. </p>
| 2 | 2008-11-24T20:38:45Z | 315,839 | <p>One of the Stackoverflow founders is a big fan of <a href="http://www.regexbuddy.com/" rel="nofollow">RegexBuddy</a> from JGSoft. I tried it on a whim when i was writing a simple file moving script at work, and it makes generating the best regex for a job quite easy in the language of your choice. If you're having trouble with developing the regex itself this is a nice tool to check your logic. I guess I'm a big fan now as well.</p>
| 1 | 2008-11-24T23:15:31Z | [
"python",
"regex"
] |
Need instructions for Reversi game | 315,435 | <p>I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?</p>
<p>I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid in some part that should be fairly simple. So.... </p>
| 3 | 2008-11-24T20:53:22Z | 315,454 | <p>Reversi is an elegantly simple game. I'm going to use a psuedo C#/Java langauge to explain some concepts, but you can transpose them to Python.</p>
<p>To break it down into its most simple compnents, you have two basic things:</p>
<p>A 2 dimensional array that represents the game board:</p>
<pre><code>gameBoard[10,10]
</code></pre>
<p>And some form of enumaration that stores the state of each tile in the gameboard:</p>
<pre><code>enum tile
{
none,
white,
black
}
</code></pre>
<p>To render the board, you loop through the gameBoard array, increasing by an offset of the piece size:</p>
<pre><code>for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
// The Piece to draw would be at gameBoard[i,j];
// Pixel locations are calculated by multiplying the array location by an offset.
DrawPiece(gameBoard[i,j],i * Width of Tile, j * width of tile);
}
}
</code></pre>
<p>Likewise, resolving a mouse click back to a location in the array would be similar, use the mouse location and offset to calculate the actual tile you are on.</p>
<p>Each time a tile is placed, you scan the entire array, and apply a simple rules based engine on what the new colors should be. (This is the real challenge, and I'll leave it up to you.)</p>
<p>The AI can take advantage of doing this array scan with hypothetical moves, have it scan 10 or so possible moves, then choose the one that produces the best outcome. Try to not make it to smart, as its easy to make an unbeatable AI when you let it play out the entire game in its head.</p>
<p>When there are no longer any free locations in the array, You end the game.</p>
| 4 | 2008-11-24T21:01:43Z | [
"python",
"reversi"
] |
Need instructions for Reversi game | 315,435 | <p>I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?</p>
<p>I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid in some part that should be fairly simple. So.... </p>
| 3 | 2008-11-24T20:53:22Z | 315,515 | <p>You'll need a 2D array. Beware of [[0] * 8] * 8, instead use [[0 for _ in [0] * 8] for _ in [0] * 8]</p>
<p>White should be 1 and black -1 (Or vice versa, of course). This way you can do flips with *=-1 and keep blank blank
Double four loops will be able to total scores and determine if the game is done pretty well. map(sum,map(sum,board)) will give you the net score</p>
<p>Don't forget to check and see if the player can even move at the beginning of a round</p>
| 0 | 2008-11-24T21:21:09Z | [
"python",
"reversi"
] |
Need instructions for Reversi game | 315,435 | <p>I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?</p>
<p>I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid in some part that should be fairly simple. So.... </p>
| 3 | 2008-11-24T20:53:22Z | 315,696 | <p>The <a href="http://en.wikipedia.org/wiki/Reversi" rel="nofollow">wikipedia page</a> has all of the rules and some decent strategy advice for reversi/othello. Basically, you need some sort of data structure to represent board state, that is to say the position of all the pieces on the board at any point in the game. As suggested by others, a 2d array is probably a decent choice, but it doesn't really matter so long as it is a representation that makes sense to you. Some of the hard stuff is figuring out which spaces are valid moves and then which pieces to flip over but, again, the wikipedia page has all of the details so it shouldn't be too hard to implement.</p>
<p>If you want to create an AI for your game, then I would suggest look at some sort of minimax type algorithm with Alpha-Beta pruning. There are a ton of resources on the web for these and an ai that uses minimax with a decent evaluation function will be able to beat most human players pretty easily, as it can look at least 8 or 9 moves ahead in very little time. There are some other fancier variants on minimax, like negamax or negascout that can do even better than basic minimax, but I'd start with the simpler ones. Wikipedia has pages on all of these algorithms and there is a ton of information on all of them as many AI courses use them for Othello or something similar. One page that is particularly useful is <a href="http://wolfey.110mb.com/GameVisual/launch.php?agent=2" rel="nofollow">this Java Applet</a>. It allows you to step through the steps of minimax and negamax on a sample state tree with and without alpha-beta pruning. </p>
<p>If none of this makes sense, let me know.</p>
| 1 | 2008-11-24T22:12:36Z | [
"python",
"reversi"
] |
Need instructions for Reversi game | 315,435 | <p>I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?</p>
<p>I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid in some part that should be fairly simple. So.... </p>
| 3 | 2008-11-24T20:53:22Z | 319,927 | <p>You may also wish to consider the application of a "fuzzy logic" loop to analyze positions. Reversi/Othello is notorious for forcing players to consider certain strategic gains against strategic losses for each move, as well as prioritizing one positive move over another.</p>
<p>A fuzzy system would give you greater control over testing move selection by setting various settings against each other, as well as giving you the ability to create multiple "personalities" to play against by shifting the various weights.</p>
| 0 | 2008-11-26T06:41:00Z | [
"python",
"reversi"
] |
Need instructions for Reversi game | 315,435 | <p>I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?</p>
<p>I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid in some part that should be fairly simple. So.... </p>
| 3 | 2008-11-24T20:53:22Z | 527,021 | <p>Don't get suckered into the multi-dim array solution. I've already written a tic-tac-toe with a multi-dim and it worked alright, but then when I started my own version of othello I did a linear integer array and its almost 2x faster.</p>
<p><a href="http://stackoverflow.com/questions/507295/alternative-faster-methods-of-converting-an-integer-to-a-cartesian-coordinate">http://stackoverflow.com/questions/507295/alternative-faster-methods-of-converting-an-integer-to-a-cartesian-coordinate</a></p>
<p>I've got everything mostly coded out in PHP but still researching Idea's for the AI as a brute force solution like in Tic-tac-toe isn't going to work.</p>
| 0 | 2009-02-09T02:53:14Z | [
"python",
"reversi"
] |
Need instructions for Reversi game | 315,435 | <p>I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?</p>
<p>I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid in some part that should be fairly simple. So.... </p>
| 3 | 2008-11-24T20:53:22Z | 527,064 | <p>You don't even need a linear array. Two 64-bit java long values suffice (one for the white pieces, one for the black. assert (white&black)==0 .</p>
<p>You can make play stronger by counting not pieces that are joined to a corner, but pieces that cannot be taken.</p>
| 0 | 2009-02-09T03:32:23Z | [
"python",
"reversi"
] |
Automagically expanding a Python list with formatted output | 315,672 | <p>Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.</p>
<p>For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "<code>IN</code>" clause.</p>
<pre><code>import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]
mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()
sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"
mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()
</code></pre>
<p>Any help would be appreciated!</p>
| 6 | 2008-11-24T22:02:29Z | 315,684 | <p>try:</p>
<pre><code>",".join( map(str, record_ids) )
</code></pre>
<p><code> ",".join( list_of_strings ) </code> joins a list of string by separating them with commas</p>
<p>if you have a list of numbers, <code>map( str, list )</code> will convert it to a list of strings</p>
| 16 | 2008-11-24T22:06:59Z | [
"python",
"list",
"mysql"
] |
Automagically expanding a Python list with formatted output | 315,672 | <p>Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.</p>
<p>For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "<code>IN</code>" clause.</p>
<pre><code>import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]
mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()
sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"
mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()
</code></pre>
<p>Any help would be appreciated!</p>
| 6 | 2008-11-24T22:02:29Z | 315,786 | <p>Further to the given answers, note that you may want to special case the empty list case as "<code>where rec_id in ()</code>" is not valid SQL, so you'll get an error.</p>
<p>Also be very careful of building SQL manually like this, rather than just using automatically escaped parameters. For a list of integers, it'll work, but if you're dealing with strings received from user input, you open up a huge SQL injection vulnerability by doing this.</p>
| 2 | 2008-11-24T22:53:27Z | [
"python",
"list",
"mysql"
] |
Automagically expanding a Python list with formatted output | 315,672 | <p>Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.</p>
<p>For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "<code>IN</code>" clause.</p>
<pre><code>import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]
mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()
sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"
mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()
</code></pre>
<p>Any help would be appreciated!</p>
| 6 | 2008-11-24T22:02:29Z | 315,822 | <p>I do stuff like this (to ensure I'm using bindings):</p>
<pre><code>sqlStmt=("UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in (%s)"
% ', '.join(['?' for n in record_ids]))
mysql_cursor.execute(sqlStmt, record_ids)
mysql.commit()
</code></pre>
<p>This works for all dynamic lists you want to bind without leaving you susceptible to SQL injection attacks.</p>
| 1 | 2008-11-24T23:09:46Z | [
"python",
"list",
"mysql"
] |
Automagically expanding a Python list with formatted output | 315,672 | <p>Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.</p>
<p>For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "<code>IN</code>" clause.</p>
<pre><code>import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]
mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()
sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"
mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()
</code></pre>
<p>Any help would be appreciated!</p>
| 6 | 2008-11-24T22:02:29Z | 318,342 | <p>Slightly different alternative to Dustin's answer:</p>
<pre><code>sqlStmt=("UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in (%s)"
% ', '.join(['?' * len(record_ids])))
</code></pre>
| 0 | 2008-11-25T18:11:38Z | [
"python",
"list",
"mysql"
] |
Automagically expanding a Python list with formatted output | 315,672 | <p>Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.</p>
<p>For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "<code>IN</code>" clause.</p>
<pre><code>import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]
mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()
sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"
mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()
</code></pre>
<p>Any help would be appreciated!</p>
| 6 | 2008-11-24T22:02:29Z | 3,146,633 | <p>Alternitavely, using <em>replace</em>:</p>
<pre><code>sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in " +
record_ids.__str__().replace('[','(').replace(']',')')
</code></pre>
| 0 | 2010-06-30T05:14:17Z | [
"python",
"list",
"mysql"
] |
Running a function periodically in twisted protocol | 315,716 | <p>I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reactor as needed. I don't know how to tie it from reactor to all protocol instances...</p>
| 23 | 2008-11-24T22:21:17Z | 315,855 | <p>I'd imagine the easiest way to do that is to manage a list of clients in the protocol with connectionMade and connectionLost in the client and then use a LoopingCall to ask each client to send data.</p>
<p>That feels a little invasive, but I don't think you'd want to do it without the protocol having some control over the transmission/reception. Of course, I'd have to see your code to really know how it'd fit in well. Got a github link? :)</p>
| 3 | 2008-11-24T23:19:48Z | [
"python",
"tcp",
"twisted",
"protocols"
] |
Running a function periodically in twisted protocol | 315,716 | <p>I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reactor as needed. I don't know how to tie it from reactor to all protocol instances...</p>
| 23 | 2008-11-24T22:21:17Z | 316,559 | <p>You would probably want to do this in the Factory for the connections. The Factory is not automatically notified of every time a connection is made and lost, so you can notify it from the Protocol.</p>
<p>Here is a complete example of how to use twisted.internet.task.LoopingCall in conjunction with a customised basic Factory and Protocol to announce that '10 seconds has passed' to every connection every 10 seconds.</p>
<pre><code>from twisted.internet import reactor, protocol, task
class MyProtocol(protocol.Protocol):
def connectionMade(self):
self.factory.clientConnectionMade(self)
def connectionLost(self, reason):
self.factory.clientConnectionLost(self)
class MyFactory(protocol.Factory):
protocol = MyProtocol
def __init__(self):
self.clients = []
self.lc = task.LoopingCall(self.announce)
self.lc.start(10)
def announce(self):
for client in self.clients:
client.transport.write("10 seconds has passed\n")
def clientConnectionMade(self, client):
self.clients.append(client)
def clientConnectionLost(self, client):
self.clients.remove(client)
myfactory = MyFactory()
reactor.listenTCP(9000, myfactory)
reactor.run()
</code></pre>
| 36 | 2008-11-25T07:12:05Z | [
"python",
"tcp",
"twisted",
"protocols"
] |
OpenCV's Python - OS X | 315,803 | <p>I get the following error while building OpenCV on OS X 10.5 (intel):</p>
<pre><code>ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture
ld: warning in .libs/_cv_la-error.o, file is not of required architecture
ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture
ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture
ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture
ld: warning in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libcxcore.dylib, file is not of required architecture
Undefined symbols for architecture i386:
"_fputs$UNIX2003", referenced from:
_PySwigObject_print in _cv_la-_cv.o
_PySwigPacked_print in _cv_la-_cv.o
_PySwigPacked_print in _cv_la-_cv.o
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status
lipo: can't open input file: /var/folders/Sr/Srq9N4R8Hr82xeFvW3o-uk+++TI/-Tmp-//cchT0WVX.out (No such file or directory)
make[4]: *** [_cv.la] Error 1
make[3]: *** [all-recursive] Error 1
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
</code></pre>
<p>While running ./configure --without-python everything is ok. Another strange thing is that when I used Python 2.4.5 or 2.5.1 everything has built ok, the problem occured after switching to Python Framework 2.5.2</p>
| 4 | 2008-11-24T23:01:50Z | 320,245 | <p>It seems a little weird that it is warning about different architectures when looking for /Developer/SDKs/MacOSX10.4u.sdk while linking - can you give us some more detail about your build environment (version of XCode, GCC, Python, $PATH etc)</p>
<p>Alternatively, won't any of the OpenCV binaries available work for you?</p>
| 1 | 2008-11-26T10:29:09Z | [
"python",
"osx",
"opencv"
] |
OpenCV's Python - OS X | 315,803 | <p>I get the following error while building OpenCV on OS X 10.5 (intel):</p>
<pre><code>ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture
ld: warning in .libs/_cv_la-error.o, file is not of required architecture
ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture
ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture
ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture
ld: warning in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libcxcore.dylib, file is not of required architecture
Undefined symbols for architecture i386:
"_fputs$UNIX2003", referenced from:
_PySwigObject_print in _cv_la-_cv.o
_PySwigPacked_print in _cv_la-_cv.o
_PySwigPacked_print in _cv_la-_cv.o
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status
lipo: can't open input file: /var/folders/Sr/Srq9N4R8Hr82xeFvW3o-uk+++TI/-Tmp-//cchT0WVX.out (No such file or directory)
make[4]: *** [_cv.la] Error 1
make[3]: *** [all-recursive] Error 1
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
</code></pre>
<p>While running ./configure --without-python everything is ok. Another strange thing is that when I used Python 2.4.5 or 2.5.1 everything has built ok, the problem occured after switching to Python Framework 2.5.2</p>
| 4 | 2008-11-24T23:01:50Z | 321,534 | <p>/Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib is just a link to /usr/local/lib
after deleting files that caused the warnings I'm getting :</p>
<pre><code>ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture
ld: warning in .libs/_cv_la-error.o, file is not of required architecture
ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture
ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture
ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture
ld: warning in /Users/Pietras/opencv/cxcore/src/.libs/libcxcore.dylib, file is not of required architecture
Undefined symbols for architecture i386: ... `
</code></pre>
<p>And these files are created by make.</p>
<p>gcc: i686-apple-darwin9-gcc-4.0.1</p>
<p>$PATH:</p>
<pre><code>/Library/Frameworks/Python.framework/Versions/Current/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/sw/bin:/sw/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/AVRMacPack/bin:/usr/X11R6/bin
</code></pre>
<p>XCode 3 (latest)</p>
<p>Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) - MacPython from python.org
(tried to downgrade and use it instead of 2.5.2, but that doesn't work anymore...)</p>
<pre><code>which python
/Library/Frameworks/Python.framework/Versions/Current/bin/python
</code></pre>
<p>I didn't find any Python OpenCV binaries for OS X.
I've tried to make it while setting python2.4 or 2.5 from macports as default and it compiles and installs, but when I try to import there is a bus error or Fatal Python error Interpreter not initialized (version mismatch?)
and it quits.</p>
| 0 | 2008-11-26T17:42:00Z | [
"python",
"osx",
"opencv"
] |
OpenCV's Python - OS X | 315,803 | <p>I get the following error while building OpenCV on OS X 10.5 (intel):</p>
<pre><code>ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture
ld: warning in .libs/_cv_la-error.o, file is not of required architecture
ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture
ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture
ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture
ld: warning in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libcxcore.dylib, file is not of required architecture
Undefined symbols for architecture i386:
"_fputs$UNIX2003", referenced from:
_PySwigObject_print in _cv_la-_cv.o
_PySwigPacked_print in _cv_la-_cv.o
_PySwigPacked_print in _cv_la-_cv.o
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status
lipo: can't open input file: /var/folders/Sr/Srq9N4R8Hr82xeFvW3o-uk+++TI/-Tmp-//cchT0WVX.out (No such file or directory)
make[4]: *** [_cv.la] Error 1
make[3]: *** [all-recursive] Error 1
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
</code></pre>
<p>While running ./configure --without-python everything is ok. Another strange thing is that when I used Python 2.4.5 or 2.5.1 everything has built ok, the problem occured after switching to Python Framework 2.5.2</p>
| 4 | 2008-11-24T23:01:50Z | 322,059 | <p>Ok, I kind of worked it out</p>
<p>It needs to be compiled with python from macports or whatever. Then I need to run <code>/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5</code> (this is my previous python version) and there OpenCV just works.</p>
| 0 | 2008-11-26T20:37:14Z | [
"python",
"osx",
"opencv"
] |
Python float to Decimal conversion | 316,238 | <p>Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. </p>
<p>This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as Decimal(""%.15f"% my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal.</p>
<p>Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?</p>
| 26 | 2008-11-25T02:53:44Z | 316,248 | <p>The "official" string representation of a float is given by the repr() built-in:</p>
<pre><code>>>> repr(1.5)
'1.5'
>>> repr(12345.678901234567890123456789)
'12345.678901234567'
</code></pre>
<p>You can use repr() instead of a formatted string, the result won't contain any unnecessary garbage.</p>
| 1 | 2008-11-25T03:00:30Z | [
"python",
"decimal"
] |
Python float to Decimal conversion | 316,238 | <p>Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. </p>
<p>This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as Decimal(""%.15f"% my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal.</p>
<p>Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?</p>
| 26 | 2008-11-25T02:53:44Z | 316,253 | <h3>Python <2.7</h3>
<pre><code>"%.15g" % f
</code></pre>
<p>Or in Python 3.0:</p>
<pre><code>format(f, ".15g")
</code></pre>
<h3>Python 2.7+, 3.2+</h3>
<p>Just pass the float to <code>Decimal</code> constructor directly.</p>
| 25 | 2008-11-25T03:07:03Z | [
"python",
"decimal"
] |
Python float to Decimal conversion | 316,238 | <p>Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. </p>
<p>This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as Decimal(""%.15f"% my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal.</p>
<p>Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?</p>
| 26 | 2008-11-25T02:53:44Z | 316,308 | <p>You said in your question: </p>
<blockquote>
<p>Can someone suggest a good way to
convert from float to Decimal
<strong>preserving value as the user has
entered</strong></p>
</blockquote>
<p>But every time the user enters a value, it is entered as a string, not as a float. You are converting it to a float somewhere. Convert it to a Decimal directly instead and no precision will be lost.</p>
| 21 | 2008-11-25T03:40:02Z | [
"python",
"decimal"
] |
Python float to Decimal conversion | 316,238 | <p>Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. </p>
<p>This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as Decimal(""%.15f"% my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal.</p>
<p>Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?</p>
| 26 | 2008-11-25T02:53:44Z | 316,309 | <p>The "right" way to do this was documented in 1990 by <a href="http://portal.acm.org/citation.cfm?id=93542&type=proceeding" rel="nofollow">Steele and White's and
Clinger's PLDI 1990</a> papers.</p>
<p>You might also look at <a href="http://stackoverflow.com/questions/286061/python-decimal-place-issues-with-floats">this</a> SO discussion about Python Decimal, including my suggestion to try using something like <a href="http://www.ics.uci.edu/~eppstein/numth/frap.c" rel="nofollow">frap</a> to rationalize a float.</p>
| 0 | 2008-11-25T03:41:27Z | [
"python",
"decimal"
] |
Python float to Decimal conversion | 316,238 | <p>Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. </p>
<p>This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as Decimal(""%.15f"% my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal.</p>
<p>Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?</p>
| 26 | 2008-11-25T02:53:44Z | 316,313 | <p>When you say "preserving value as the user has entered", why not just store the user-entered value as a string, and pass that to the Decimal constructor?</p>
| 2 | 2008-11-25T03:44:20Z | [
"python",
"decimal"
] |
Python float to Decimal conversion | 316,238 | <p>Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. </p>
<p>This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as Decimal(""%.15f"% my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal.</p>
<p>Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?</p>
| 26 | 2008-11-25T02:53:44Z | 342,356 | <p>Python does support Decimal creation from a float. You just cast it as a string first. But the precision loss doesn't occur with string conversion. The float you are converting doesn't have that kind of precision in the first place. (Otherwise you wouldn't need Decimal)</p>
<p>I think the confusion here is that <em>we can create float literals in decimal format</em>, but as soon as the interpreter consumes that literal the inner representation becomes a floating point number.</p>
| 4 | 2008-12-04T22:41:36Z | [
"python",
"decimal"
] |
Python float to Decimal conversion | 316,238 | <p>Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. </p>
<p>This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as Decimal(""%.15f"% my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal.</p>
<p>Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?</p>
| 26 | 2008-11-25T02:53:44Z | 8,413,753 | <p>I suggest this</p>
<pre><code>>>> a = 2.111111
>>> a
2.1111110000000002
>>> str(a)
'2.111111'
>>> decimal.Decimal(str(a))
Decimal('2.111111')
</code></pre>
| 3 | 2011-12-07T10:22:10Z | [
"python",
"decimal"
] |
"import wx" fails after installation of wxPython on Windows XP | 316,325 | <p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow">wxPython</a> for use with my Python 2.6 installation:</p>
<p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p>
<p>When I run Python and try to import wx, I get the following error:</p>
<pre><code>C:\Program Files\Console2>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in <module>
from wx._core import *
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>>>
</code></pre>
<p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
| 4 | 2008-11-25T03:54:51Z | 316,466 | <p>Try the ANSI version instead of the Unicode one. IIRC it needs to match the Python 2.6 install to work properly.</p>
| 1 | 2008-11-25T05:50:18Z | [
"python",
"windows",
"wxpython"
] |
"import wx" fails after installation of wxPython on Windows XP | 316,325 | <p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow">wxPython</a> for use with my Python 2.6 installation:</p>
<p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p>
<p>When I run Python and try to import wx, I get the following error:</p>
<pre><code>C:\Program Files\Console2>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in <module>
from wx._core import *
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>>>
</code></pre>
<p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
| 4 | 2008-11-25T03:54:51Z | 316,492 | <p>From looking for "application configuration is incorrect" in the <a href="http://trac.wxwidgets.org/" rel="nofollow">wxPython trac system</a>, the only reference that might make sense is a 64-bit vs 32-bit compatibility issue. </p>
<p>Otherwise, I'd say <a href="http://stackoverflow.com/questions/316325/import-wx-fails-after-installation-of-wxpython-on-windows-xp/316466#316466">Brian's answer</a> of trying ANSI is pretty good.</p>
<p>BTW, if you try uninstalling again, make go into the site-packages folder and make sure all the wx and wxPython stuff is deleted.</p>
| 1 | 2008-11-25T06:20:30Z | [
"python",
"windows",
"wxpython"
] |
"import wx" fails after installation of wxPython on Windows XP | 316,325 | <p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow">wxPython</a> for use with my Python 2.6 installation:</p>
<p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p>
<p>When I run Python and try to import wx, I get the following error:</p>
<pre><code>C:\Program Files\Console2>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in <module>
from wx._core import *
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>>>
</code></pre>
<p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
| 4 | 2008-11-25T03:54:51Z | 328,051 | <p>I was getting the same error. </p>
<p>After some googling found this link to <a href="http://www.microsoft.com/downloads/details.aspx?familyid=9B2DA534-3E03-4391-8A4D-074B9F2BC1BF&displaylang=en" rel="nofollow">MSVC++ 2008 Redestributable</a> and installed it. </p>
<p>That solved the problem.</p>
| 3 | 2008-11-29T21:46:17Z | [
"python",
"windows",
"wxpython"
] |
"import wx" fails after installation of wxPython on Windows XP | 316,325 | <p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow">wxPython</a> for use with my Python 2.6 installation:</p>
<p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p>
<p>When I run Python and try to import wx, I get the following error:</p>
<pre><code>C:\Program Files\Console2>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in <module>
from wx._core import *
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>>>
</code></pre>
<p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
| 4 | 2008-11-25T03:54:51Z | 853,581 | <p>Copy the Microsoft C runtime library v.9 files and manifest. That is, <code>msvcr90.dll</code> and <code>microsoft.vc90.crt.manifest</code> from folder <code>python</code> to the folder wx, tha is, folder which contains failed to start DLLs. </p>
<p>Or install the Visual C++ 2008 Redistributable Package.</p>
| 1 | 2009-05-12T16:07:24Z | [
"python",
"windows",
"wxpython"
] |
"import wx" fails after installation of wxPython on Windows XP | 316,325 | <p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow">wxPython</a> for use with my Python 2.6 installation:</p>
<p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p>
<p>When I run Python and try to import wx, I get the following error:</p>
<pre><code>C:\Program Files\Console2>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in <module>
from wx._core import *
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>>>
</code></pre>
<p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
| 4 | 2008-11-25T03:54:51Z | 4,852,316 | <p>I too have the same issue.Better install "Portable Python" IDE which comes with some nice modules including wxPython .You can start coding GUI immediately without the need to download a separate wxPython.The link ,
<a href="http://www.portablepython.com/" rel="nofollow">http://www.portablepython.com/</a></p>
| 1 | 2011-01-31T14:56:09Z | [
"python",
"windows",
"wxpython"
] |
"import wx" fails after installation of wxPython on Windows XP | 316,325 | <p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow">wxPython</a> for use with my Python 2.6 installation:</p>
<p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p>
<p>When I run Python and try to import wx, I get the following error:</p>
<pre><code>C:\Program Files\Console2>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in <module>
from wx._core import *
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>>>
</code></pre>
<p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
| 4 | 2008-11-25T03:54:51Z | 5,120,296 | <p>Hate to say this, but I had the same problem, and and import worked fine after a reboot.</p>
| 3 | 2011-02-25T17:09:02Z | [
"python",
"windows",
"wxpython"
] |
"import wx" fails after installation of wxPython on Windows XP | 316,325 | <p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow">wxPython</a> for use with my Python 2.6 installation:</p>
<p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p>
<p>When I run Python and try to import wx, I get the following error:</p>
<pre><code>C:\Program Files\Console2>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in <module>
from wx._core import *
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>>>
</code></pre>
<p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
| 4 | 2008-11-25T03:54:51Z | 20,026,326 | <p>Maybe too late, but I had the same problem and solved that by downloading that from their <a href="http://www.wxpython.org/download.php" rel="nofollow">own website</a> : wxPython2.8-win64-unicode-py27
In my case it initially wanted to setup in somewhere else than my python folder. So I changed it to be in ../python27/Lib/SitePackages/
Then it worked properly.</p>
<p>I hope it helps.</p>
| 0 | 2013-11-17T02:06:42Z | [
"python",
"windows",
"wxpython"
] |
"import wx" fails after installation of wxPython on Windows XP | 316,325 | <p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow">wxPython</a> for use with my Python 2.6 installation:</p>
<p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p>
<p>When I run Python and try to import wx, I get the following error:</p>
<pre><code>C:\Program Files\Console2>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in <module>
from wx._core import *
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>>>
</code></pre>
<p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
| 4 | 2008-11-25T03:54:51Z | 25,088,999 | <p>Another late answer, but I recently had issues (8/14) and my solution was to use the 32-bit instead of 64-bit wxPython version. </p>
| 0 | 2014-08-01T21:32:28Z | [
"python",
"windows",
"wxpython"
] |
"import wx" fails after installation of wxPython on Windows XP | 316,325 | <p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow">wxPython</a> for use with my Python 2.6 installation:</p>
<p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p>
<p>When I run Python and try to import wx, I get the following error:</p>
<pre><code>C:\Program Files\Console2>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in <module>
from wx._core import *
File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>>>
</code></pre>
<p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
| 4 | 2008-11-25T03:54:51Z | 25,703,964 | <p>you try to use the module wxpython 2.8.12.1 version, select the version of your python. you can download it here:</p>
<p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#wxpython" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#wxpython</a></p>
| 0 | 2014-09-06T19:27:57Z | [
"python",
"windows",
"wxpython"
] |
Problem compiling MySQLdb for Python 2.6 on Win32 | 316,484 | <p>I'm using Django and Python 2.6, and I want to grow my application using a MySQL backend. Problem is that there isn't a win32 package for MySQLdb on Python 2.6.</p>
<p>Now I'm no hacker, but I thought I might compile it myself using MSVC++9 Express. But I run into a problem that the compiler quickly can't find <code>config_win.h</code>, which I assume is a header file for MySQL so that the MySQLdb package can know what calls it can make into MySQL.</p>
<p>Am I right? And if so, where do I get the header files for MySQL?</p>
| 9 | 2008-11-25T06:14:20Z | 317,332 | <p>Have you considered using a pre-built stack with Python, MySQL, Apache, etc.?</p>
<p>For example: <a href="http://bitnami.org/stack/djangostack" rel="nofollow">http://bitnami.org/stack/djangostack</a></p>
| 1 | 2008-11-25T13:35:16Z | [
"python",
"mysql",
"winapi"
] |
Problem compiling MySQLdb for Python 2.6 on Win32 | 316,484 | <p>I'm using Django and Python 2.6, and I want to grow my application using a MySQL backend. Problem is that there isn't a win32 package for MySQLdb on Python 2.6.</p>
<p>Now I'm no hacker, but I thought I might compile it myself using MSVC++9 Express. But I run into a problem that the compiler quickly can't find <code>config_win.h</code>, which I assume is a header file for MySQL so that the MySQLdb package can know what calls it can make into MySQL.</p>
<p>Am I right? And if so, where do I get the header files for MySQL?</p>
| 9 | 2008-11-25T06:14:20Z | 317,716 | <p>I think that the header files are shipped with MySQL, just make sure you check the appropriate options when installing (I think that sources and headers are under "developer components" in the installation dialog).</p>
| 2 | 2008-11-25T15:29:51Z | [
"python",
"mysql",
"winapi"
] |
Problem compiling MySQLdb for Python 2.6 on Win32 | 316,484 | <p>I'm using Django and Python 2.6, and I want to grow my application using a MySQL backend. Problem is that there isn't a win32 package for MySQLdb on Python 2.6.</p>
<p>Now I'm no hacker, but I thought I might compile it myself using MSVC++9 Express. But I run into a problem that the compiler quickly can't find <code>config_win.h</code>, which I assume is a header file for MySQL so that the MySQLdb package can know what calls it can make into MySQL.</p>
<p>Am I right? And if so, where do I get the header files for MySQL?</p>
| 9 | 2008-11-25T06:14:20Z | 319,007 | <p>Thanks all! I found that I hadn't installed the developer components in MySQL. Once that was done the problem was solved and I easily compiled the MySQLdb for Python 2.6.</p>
<p>I've made the package available at <a href="http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe" rel="nofollow">my site</a>.</p>
| 9 | 2008-11-25T21:51:20Z | [
"python",
"mysql",
"winapi"
] |
Problem compiling MySQLdb for Python 2.6 on Win32 | 316,484 | <p>I'm using Django and Python 2.6, and I want to grow my application using a MySQL backend. Problem is that there isn't a win32 package for MySQLdb on Python 2.6.</p>
<p>Now I'm no hacker, but I thought I might compile it myself using MSVC++9 Express. But I run into a problem that the compiler quickly can't find <code>config_win.h</code>, which I assume is a header file for MySQL so that the MySQLdb package can know what calls it can make into MySQL.</p>
<p>Am I right? And if so, where do I get the header files for MySQL?</p>
| 9 | 2008-11-25T06:14:20Z | 1,137,151 | <p>Also see this post on the mysql-python blog: <a href="http://mysql-python.blogspot.com/2009/03/mysql-python-123-beta-2-released.html" rel="nofollow">MySQL-python-1.2.3 beta 2 released</a> - dated March 2009. MySQLdb for Python 2.6 is still a work in progress...</p>
| 1 | 2009-07-16T12:17:26Z | [
"python",
"mysql",
"winapi"
] |
Ghostscript PDF -> TIFF throws an untrappable exception, when consuming files with asian fonts | 316,518 | <p>Ghostscript curls up and dies, throwing an exception to stdout which I cannot catch and log. I am pretty sure it gets sick when I give it asian fonts. Has anybody backed into this problem and solved it?</p>
| 1 | 2008-11-25T06:41:16Z | 317,300 | <p>It may be that you need to read stderr from the child process.</p>
| 0 | 2008-11-25T13:21:28Z | [
"python",
"jython",
"tiff",
"ghostscript"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 316,974 | <p>Depending on what you want to achive, you are probably easiest calling the system ping command..</p>
<p>Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!</p>
<pre><code>import subprocess
host = "www.google.com"
ping = subprocess.Popen(
["ping", "-c", "4", host],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print out
</code></pre>
<p>You don't need to worry about shell-escape characters. For example..</p>
<pre><code>host = "google.com; `echo test`
</code></pre>
<p>..will <strong>not</strong> execute the echo command.</p>
<p>Now, to actually get the ping results, you could parse the <code>out</code> variable. Example output:</p>
<pre><code>round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms
</code></pre>
<p>Example regex:</p>
<pre><code>import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()
# ('248.139', '249.474', '250.530', '0.896')
</code></pre>
<p>Again, remember the output will vary depending on operating system (and even the version of <code>ping</code>). This isn't ideal, but it will work fine in many situations (where you know the machines the script will be running on)</p>
| 35 | 2008-11-25T10:49:58Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 317,021 | <p>It's hard to say what your question is, but there are some alternatives.</p>
<p>If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google "Python ICMP" to find things like this <a href="http://code.activestate.com/recipes/409689/">icmplib</a>. You might want to look at <a href="http://www.secdev.org/projects/scapy/">scapy</a>, also.</p>
<p>This will be much faster than using <code>os.system("ping " + ip )</code>. </p>
<p>If you mean to generically "ping" a box to see if it's up, you can use the echo protocol on port 7.</p>
<p>For echo, you use the <a href="http://www.python.org/doc/2.5.2/lib/module-socket.html">socket</a> library to open the IP address and port 7. You write something on that port, send a carriage return (<code>"\r\n"</code>) and then read the reply.</p>
<p>If you mean to "ping" a web site to see if the site is running, you have to use the http protocol on port 80.</p>
<p>For or properly checking a web server, you use <a href="http://www.python.org/doc/2.5.2/lib/module-urllib2.html">urllib2</a> to open a specific URL. (<code>/index.html</code> is always popular) and read the response. </p>
<p>There are still more potential meaning of "ping" including "traceroute" and "finger".</p>
| 9 | 2008-11-25T11:12:56Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 317,050 | <p>Take a look at <a href="http://www.python.org/~jeremy/python.html" rel="nofollow">Jeremy Hylton's code</a>, if you need to do a more complex, detailed implementation in Python rather than just calling <code>ping</code>.</p>
| 2 | 2008-11-25T11:22:14Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 317,172 | <p>You may find <a href="http://noahgift.com/">Noah Gift's</a> presentation <a href="http://www.slideshare.net/noahgift/pycon2008-cli-noahgift">Creating Agile Commandline Tools With Python</a>. In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below is a basic version before he adds command line parsing and some other features. The code to this version and others can be found <a href="http://code.noahgift.com/pycon2008/pycon2008_cli_noahgift.zip">here</a></p>
<pre><code>#!/usr/bin/env python2.5
from threading import Thread
import subprocess
from Queue import Queue
num_threads = 4
queue = Queue()
ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
#wraps system ping command
def pinger(i, q):
"""Pings subnet"""
while True:
ip = q.get()
print "Thread %s: Pinging %s" % (i, ip)
ret = subprocess.call("ping -c 1 %s" % ip,
shell=True,
stdout=open('/dev/null', 'w'),
stderr=subprocess.STDOUT)
if ret == 0:
print "%s: is alive" % ip
else:
print "%s: did not respond" % ip
q.task_done()
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=pinger, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Place work in queue
for ip in ips:
queue.put(ip)
#Wait until worker threads are done to exit
queue.join()
</code></pre>
<p>He is also author of: <a href="http://rads.stackoverflow.com/amzn/click/0596515820">Python for Unix and Linux System Administration</a></p>
<p><a href="http://rads.stackoverflow.com/amzn/click/0596515820"><img src="http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg" alt=""></a></p>
| 37 | 2008-11-25T12:28:42Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 317,206 | <p>See this <a href="https://pypi.python.org/pypi/python-ping/2011.10.17.376a019">pure Python ping</a> by <a href="http://www.mondoinfo.com/">Matthew Dixon Cowles</a> and <a href="http://www.jensdiemer.de/">Jens Diemer</a>. Also, remember that Python requires root to spawn ICMP (i.e. ping) sockets in linux.</p>
<pre><code>import ping, socket
try:
ping.verbose_ping('www.google.com', count=3)
delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
except socket.error, e:
print "Ping Error:", e
</code></pre>
<p>The source code itself is easy to read, see the implementations of <code>verbose_ping</code> and of <code>Ping.do</code> for inspiration.</p>
| 76 | 2008-11-25T12:39:12Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 317,214 | <p>I use the ping module by Lars Strand. Google for "Lars Strand python ping" and you will find a lot of references.</p>
| 0 | 2008-11-25T12:41:38Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 318,142 | <p>using system ping command to ping a list of hosts:</p>
<pre><code>import re
from subprocess import Popen, PIPE
from threading import Thread
class Pinger(object):
def __init__(self, hosts):
for host in hosts:
pa = PingAgent(host)
pa.start()
class PingAgent(Thread):
def __init__(self, host):
Thread.__init__(self)
self.host = host
def run(self):
p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
m = re.search('Average = (.*)ms', p.stdout.read())
if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
else: print 'Error: Invalid Response -', self.host
if __name__ == '__main__':
hosts = [
'www.pylot.org',
'www.goldb.org',
'www.google.com',
'www.yahoo.com',
'www.techcrunch.com',
'www.this_one_wont_work.com'
]
Pinger(hosts)
</code></pre>
| 0 | 2008-11-25T17:12:11Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 1,165,094 | <p>I did something similar this way, as an inspiration:</p>
<pre><code>import urllib
import threading
import time
def pinger_urllib(host):
"""
helper function timing the retrival of index.html
TODO: should there be a 1MB bogus file?
"""
t1 = time.time()
urllib.urlopen(host + '/index.html').read()
return (time.time() - t1) * 1000.0
def task(m):
"""
the actual task
"""
delay = float(pinger_urllib(m))
print '%-30s %5.0f [ms]' % (m, delay)
# parallelization
tasks = []
URLs = ['google.com', 'wikipedia.org']
for m in URLs:
t = threading.Thread(target=task, args=(m,))
t.start()
tasks.append(t)
# synchronization point
for t in tasks:
t.join()
</code></pre>
| 7 | 2009-07-22T12:59:52Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 1,741,799 | <p>You can find an updated version of the mentioned script that works on both Windows and Linux <a href="http://www.g-loaded.eu/2009/10/30/python-ping/" rel="nofollow">here</a></p>
| 2 | 2009-11-16T12:10:29Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 12,490,356 | <p>Here's a short snippet using <code>subprocess</code>. The <code>check_call</code> method either returns 0 for success, or raises an exception. This way, I don't have to parse the output of ping. I'm using <code>shlex</code> to split the command line arguments.</p>
<pre><code> import subprocess
import shlex
command_line = "ping -c 1 www.google.comsldjkflksj"
args = shlex.split(command_line)
try:
subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print "Website is there."
except subprocess.CalledProcessError:
print "Couldn't get a ping."
</code></pre>
| 6 | 2012-09-19T07:35:43Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 13,659,790 | <p>read a file name, the file contain the one url per line, like this:</p>
<pre><code>http://www.poolsaboveground.com/apache/hadoop/core/
http://mirrors.sonic.net/apache/hadoop/core/
</code></pre>
<p>use command:</p>
<pre><code>python url.py urls.txt
</code></pre>
<p>get the result:</p>
<pre><code>Round Trip Time: 253 ms - mirrors.sonic.net
Round Trip Time: 245 ms - www.globalish.com
Round Trip Time: 327 ms - www.poolsaboveground.com
</code></pre>
<p>source code(url.py):</p>
<pre><code>import re
import sys
import urlparse
from subprocess import Popen, PIPE
from threading import Thread
class Pinger(object):
def __init__(self, hosts):
for host in hosts:
hostname = urlparse.urlparse(host).hostname
if hostname:
pa = PingAgent(hostname)
pa.start()
else:
continue
class PingAgent(Thread):
def __init__(self, host):
Thread.__init__(self)
self.host = host
def run(self):
p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
m = re.search('Average = (.*)ms', p.stdout.read())
if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
else: print 'Error: Invalid Response -', self.host
if __name__ == '__main__':
with open(sys.argv[1]) as f:
content = f.readlines()
Pinger(content)
</code></pre>
| 3 | 2012-12-01T13:14:48Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 28,896,872 | <pre><code>import subprocess as s
ip=raw_input("Enter the IP/Domain name:")
if(s.call(["ping",ip])==0):
print "your IP is alive"
else:
print "Check ur IP"
</code></pre>
| 0 | 2015-03-06T10:29:11Z | [
"python",
"network-programming",
"ping"
] |
Ping a site in Python? | 316,866 | <p>The basic code is:</p>
<pre><code>from Tkinter import *
import os,sys
ana= Tk()
def ping1():
os.system('ping')
a=Button(pen)
ip=("192.168.0.1")
a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ???
a.pack()
ana.mainloop()
</code></pre>
<p>How could I ping a sites or address?</p>
| 64 | 2008-11-25T09:58:37Z | 29,580,669 | <p>Use this it's tested on python 2.7 and works fine it returns ping time in milliseconds if success and return False on fail.</p>
<pre><code>import platform,subproccess,re
def Ping(hostname,timeout):
if platform.system() == "Windows":
command="ping "+hostname+" -n 1 -w "+str(timeout*1000)
else:
command="ping -i "+str(timeout)+" -c 1 " + hostname
proccess = subprocess.Popen(command, stdout=subprocess.PIPE)
matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)
if matches:
return matches.group(1)
else:
return False
</code></pre>
| 0 | 2015-04-11T17:10:06Z | [
"python",
"network-programming",
"ping"
] |
Newbie Python question about strings with parameters: "%%s"? | 317,368 | <p>I'm trying to figure out what the following line does exactly - specifically the %%s part?</p>
<pre><code>cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))
</code></pre>
<p>Any good mini-tutorial about string formatting and inserting variables into strings with Python?</p>
| 5 | 2008-11-25T13:43:04Z | 317,372 | <p>%% turns into a single %</p>
| 1 | 2008-11-25T13:44:17Z | [
"python",
"string"
] |
Newbie Python question about strings with parameters: "%%s"? | 317,368 | <p>I'm trying to figure out what the following line does exactly - specifically the %%s part?</p>
<pre><code>cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))
</code></pre>
<p>Any good mini-tutorial about string formatting and inserting variables into strings with Python?</p>
| 5 | 2008-11-25T13:43:04Z | 317,385 | <p>The <code>%%</code> becomes a single <code>%</code>. This code is essentially doing two levels of string formatting. First the <code>%sourcedest</code> is executed to turn your code essentially into:</p>
<pre><code>cursor.execute('INSERT INTO mastertickets (BLAH, FOO) VALUES (%s, %s)', (self.tkt.id, n))
</code></pre>
<p>then the db layer applies the parameters to the slots that are left.</p>
<p>The double-% is needed to get the db's slots passed through the first string formatting operation safely.</p>
| 6 | 2008-11-25T13:48:23Z | [
"python",
"string"
] |
Newbie Python question about strings with parameters: "%%s"? | 317,368 | <p>I'm trying to figure out what the following line does exactly - specifically the %%s part?</p>
<pre><code>cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))
</code></pre>
<p>Any good mini-tutorial about string formatting and inserting variables into strings with Python?</p>
| 5 | 2008-11-25T13:43:04Z | 317,459 | <p>"but how should one do it instead?"</p>
<p>Tough call. The issue is that they are plugging in metadata (specifically column names) on the fly into a SQL statement. I'm not a big fan of this kind of thing. The <code>sourcedest</code> variable has two column names that are going to be updated. </p>
<p>Odds are good that there is only one (or a few few) pairs of column names that are actually used. My preference is to do this.</p>
<pre><code>if situation1:
stmt= "INSERT INTO mastertickets (this, that) VALUES (?, ?)"
elif situation2:
stmt= "INSERT INTO mastertickets (foo, bar) VALUES (?, ?)"
else:
raise Exception( "Bad configuration -- with some explanation" )
cursor.execute( stmt, (self.tkt.id, n) )
</code></pre>
<p>When there's more than one valid combination of columns for this kind of thing, it indicates that the data model has merged two entities into a single table, which is a common database design problem. Since you're working with a product and a plug-in, there's not much you can do about the data model issues.</p>
| 4 | 2008-11-25T14:11:35Z | [
"python",
"string"
] |
Newbie Python question about strings with parameters: "%%s"? | 317,368 | <p>I'm trying to figure out what the following line does exactly - specifically the %%s part?</p>
<pre><code>cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))
</code></pre>
<p>Any good mini-tutorial about string formatting and inserting variables into strings with Python?</p>
| 5 | 2008-11-25T13:43:04Z | 317,478 | <p>Having the column names inserted using string formatting isn't so bad so long as they aren't user-provided. The values should be query parameters though:</p>
<pre><code>stmt = "INSERT INTO mastertickets (%s, %s) VALUES (?, ?)" % srcdest
...
cursor.execute( stmt, (self.tkt.id, n) )
</code></pre>
| 3 | 2008-11-25T14:16:47Z | [
"python",
"string"
] |
Newbie Python question about strings with parameters: "%%s"? | 317,368 | <p>I'm trying to figure out what the following line does exactly - specifically the %%s part?</p>
<pre><code>cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))
</code></pre>
<p>Any good mini-tutorial about string formatting and inserting variables into strings with Python?</p>
| 5 | 2008-11-25T13:43:04Z | 317,484 | <p>It does the same:</p>
<pre><code>cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (:%s, :%s)' % \
tuple(sourcedest + sourcedest), dict(zip(sourcedest, (self.tkt.id, n))))
</code></pre>
<p>Never do that.</p>
| 0 | 2008-11-25T14:18:06Z | [
"python",
"string"
] |
Get Element value with minidom with Python | 317,413 | <p>I am creating a GUI frontend for the Eve Online API in Python.</p>
<p>I have successfully pulled the XML data from their server.</p>
<p>I am trying to grab the value from a node called "name":</p>
<pre><code>from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
</code></pre>
<p>This seems to find the node, but the output is below:</p>
<pre><code>[<DOM Element: name at 0x11e6d28>]
</code></pre>
<p>How could I get it to print the value of the node?</p>
| 78 | 2008-11-25T13:57:02Z | 317,421 | <p>It should just be</p>
<pre><code>name[0].firstChild.nodeValue
</code></pre>
| 100 | 2008-11-25T13:59:13Z | [
"python",
"dom",
"minidom"
] |
Get Element value with minidom with Python | 317,413 | <p>I am creating a GUI frontend for the Eve Online API in Python.</p>
<p>I have successfully pulled the XML data from their server.</p>
<p>I am trying to grab the value from a node called "name":</p>
<pre><code>from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
</code></pre>
<p>This seems to find the node, but the output is below:</p>
<pre><code>[<DOM Element: name at 0x11e6d28>]
</code></pre>
<p>How could I get it to print the value of the node?</p>
| 78 | 2008-11-25T13:57:02Z | 317,494 | <p>Probably something like this if it's the text part you want...</p>
<pre><code>from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)
</code></pre>
<p>The text part of a node is considered a node in itself placed as a child-node of the one you asked for. Thus you will want to go through all its children and find all child nodes that are text nodes. A node can have several text nodes; eg.</p>
<pre><code><name>
blabla
<somestuff>asdf</somestuff>
znylpx
</name>
</code></pre>
<p>You want both 'blabla' and 'znylpx'; hence the " ".join(). You might want to replace the space with a newline or so, or perhaps by nothing.</p>
| 50 | 2008-11-25T14:21:08Z | [
"python",
"dom",
"minidom"
] |
Get Element value with minidom with Python | 317,413 | <p>I am creating a GUI frontend for the Eve Online API in Python.</p>
<p>I have successfully pulled the XML data from their server.</p>
<p>I am trying to grab the value from a node called "name":</p>
<pre><code>from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
</code></pre>
<p>This seems to find the node, but the output is below:</p>
<pre><code>[<DOM Element: name at 0x11e6d28>]
</code></pre>
<p>How could I get it to print the value of the node?</p>
| 78 | 2008-11-25T13:57:02Z | 2,626,246 | <p>I know this question is pretty old now, but I thought you might have an easier time with <a href="http://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow">ElementTree</a></p>
<pre><code>from xml.etree import ElementTree as ET
import datetime
f = ET.XML(data)
for element in f:
if element.tag == "currentTime":
# Handle time data was pulled
currentTime = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
if element.tag == "cachedUntil":
# Handle time until next allowed update
cachedUntil = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
if element.tag == "result":
# Process list of skills
pass
</code></pre>
<p>I know that's not super specific, but I just discovered it, and so far it's a lot easier to get my head around than the minidom (since so many nodes are essentially white space).</p>
<p>For instance, you have the tag name and the actual text together, just as you'd probably expect:</p>
<pre><code>>>> element[0]
<Element currentTime at 40984d0>
>>> element[0].tag
'currentTime'
>>> element[0].text
'2010-04-12 02:45:45'e
</code></pre>
| 6 | 2010-04-13T00:18:27Z | [
"python",
"dom",
"minidom"
] |
Get Element value with minidom with Python | 317,413 | <p>I am creating a GUI frontend for the Eve Online API in Python.</p>
<p>I have successfully pulled the XML data from their server.</p>
<p>I am trying to grab the value from a node called "name":</p>
<pre><code>from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
</code></pre>
<p>This seems to find the node, but the output is below:</p>
<pre><code>[<DOM Element: name at 0x11e6d28>]
</code></pre>
<p>How could I get it to print the value of the node?</p>
| 78 | 2008-11-25T13:57:02Z | 4,835,703 | <p>you can use something like this.It worked out for me</p>
<pre><code>doc = parse('C:\\eve.xml')
my_node_list = doc.getElementsByTagName("name")
my_n_node = my_node_list[0]
my_child = my_n_node.firstChild
my_text = my_child.data
print my_text
</code></pre>
| 10 | 2011-01-29T07:28:23Z | [
"python",
"dom",
"minidom"
] |
Get Element value with minidom with Python | 317,413 | <p>I am creating a GUI frontend for the Eve Online API in Python.</p>
<p>I have successfully pulled the XML data from their server.</p>
<p>I am trying to grab the value from a node called "name":</p>
<pre><code>from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
</code></pre>
<p>This seems to find the node, but the output is below:</p>
<pre><code>[<DOM Element: name at 0x11e6d28>]
</code></pre>
<p>How could I get it to print the value of the node?</p>
| 78 | 2008-11-25T13:57:02Z | 7,669,965 | <p>I had a similar case, what worked for me was:</p>
<p>name.firstChild.childNodes[0].data</p>
<p>XML is supposed to be simple and it really is and I don't know why python's minidom did it so complicated... but it's how it's made</p>
| 2 | 2011-10-06T03:10:30Z | [
"python",
"dom",
"minidom"
] |
Get Element value with minidom with Python | 317,413 | <p>I am creating a GUI frontend for the Eve Online API in Python.</p>
<p>I have successfully pulled the XML data from their server.</p>
<p>I am trying to grab the value from a node called "name":</p>
<pre><code>from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
</code></pre>
<p>This seems to find the node, but the output is below:</p>
<pre><code>[<DOM Element: name at 0x11e6d28>]
</code></pre>
<p>How could I get it to print the value of the node?</p>
| 78 | 2008-11-25T13:57:02Z | 7,880,363 | <p>Here is a slightly modified answer of Henrik's for multiple nodes (ie. when getElementsByTagName returns more than one instance)</p>
<pre><code>images = xml.getElementsByTagName("imageUrl")
for i in images:
print " ".join(t.nodeValue for t in i.childNodes if t.nodeType == t.TEXT_NODE)
</code></pre>
| 2 | 2011-10-24T18:51:35Z | [
"python",
"dom",
"minidom"
] |
Get Element value with minidom with Python | 317,413 | <p>I am creating a GUI frontend for the Eve Online API in Python.</p>
<p>I have successfully pulled the XML data from their server.</p>
<p>I am trying to grab the value from a node called "name":</p>
<pre><code>from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
</code></pre>
<p>This seems to find the node, but the output is below:</p>
<pre><code>[<DOM Element: name at 0x11e6d28>]
</code></pre>
<p>How could I get it to print the value of the node?</p>
| 78 | 2008-11-25T13:57:02Z | 33,012,116 | <p>This should work:</p>
<pre><code>from xml.dom.minidom import parse
doc = minidom.parseString("C:\\eve.xml")
name = doc.getElementsByTagName('name')
print(name)
</code></pre>
| 0 | 2015-10-08T09:43:21Z | [
"python",
"dom",
"minidom"
] |
Get Element value with minidom with Python | 317,413 | <p>I am creating a GUI frontend for the Eve Online API in Python.</p>
<p>I have successfully pulled the XML data from their server.</p>
<p>I am trying to grab the value from a node called "name":</p>
<pre><code>from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
</code></pre>
<p>This seems to find the node, but the output is below:</p>
<pre><code>[<DOM Element: name at 0x11e6d28>]
</code></pre>
<p>How could I get it to print the value of the node?</p>
| 78 | 2008-11-25T13:57:02Z | 38,481,043 | <p>The above answer is correct, namely:</p>
<pre><code>name[0].firstChild.nodeValue
</code></pre>
<p>However for me, like others, my value was further down the tree:</p>
<pre><code>name[0].firstChild.firstChild.nodeValue
</code></pre>
<p>To find this I used the following:</p>
<pre><code>def scandown( elements, indent ):
for el in elements:
print(" " * indent + "nodeName: " + str(el.nodeName) )
print(" " * indent + "nodeValue: " + str(el.nodeValue) )
print(" " * indent + "childNodes: " + str(el.childNodes) )
scandown(el.childNodes, indent + 1)
scandown( doc.getElementsByTagName('text'), 0 )
</code></pre>
<p>Running this for my simple SVG file created with Inkscape this gave me:</p>
<pre><code>nodeName: text
nodeValue: None
childNodes: [<DOM Element: tspan at 0x10392c6d0>]
nodeName: tspan
nodeValue: None
childNodes: [<DOM Text node "'MY STRING'">]
nodeName: #text
nodeValue: MY STRING
childNodes: ()
nodeName: text
nodeValue: None
childNodes: [<DOM Element: tspan at 0x10392c800>]
nodeName: tspan
nodeValue: None
childNodes: [<DOM Text node "'MY WORDS'">]
nodeName: #text
nodeValue: MY WORDS
childNodes: ()
</code></pre>
<p>I used xml.dom.minidom, the various fields are <a href="https://wiki.python.org/moin/MiniDom" rel="nofollow">explained on this page, MiniDom Python.</a></p>
| 1 | 2016-07-20T12:15:18Z | [
"python",
"dom",
"minidom"
] |
Python: packing an ip address as a ctype.c_ulong() for use with DLL | 317,531 | <p>given the following code: </p>
<pre><code>import ctypes
ip="192.168.1.1"
thisdll = ctypes.cdll['aDLL']
thisdll.functionThatExpectsAnIP(ip)
</code></pre>
<p>how can I correctly pack this for a DLL that expects it as a c_ulong datatype?</p>
<p>I've tried using: </p>
<pre><code>ip_netFrmt = socket.inet_aton(ip)
ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt)
</code></pre>
<p>however, the <code>c_ulong()</code> method returns an error because it needs an integer. </p>
<p>is there a way to use <code>struct.pack</code> to accomplish this? </p>
| 3 | 2008-11-25T14:30:37Z | 317,572 | <p>First a disclaimer: This is just an educated guess.</p>
<p>an ip-address is traditionally represented as four bytes - i.e. xxx.xxx.xxx.xxx, but is really a unsigned long. So you should convert the representation 192.168.1.1 to an unsiged int. you could convert it like this.</p>
<pre><code>ip="192.168.1.1"
ip_long = reduce(lambda x,y:x*256+int(y), ip.split('.'), 0)
</code></pre>
| 0 | 2008-11-25T14:45:24Z | [
"python",
"dll",
"ip-address",
"ctypes"
] |
Python: packing an ip address as a ctype.c_ulong() for use with DLL | 317,531 | <p>given the following code: </p>
<pre><code>import ctypes
ip="192.168.1.1"
thisdll = ctypes.cdll['aDLL']
thisdll.functionThatExpectsAnIP(ip)
</code></pre>
<p>how can I correctly pack this for a DLL that expects it as a c_ulong datatype?</p>
<p>I've tried using: </p>
<pre><code>ip_netFrmt = socket.inet_aton(ip)
ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt)
</code></pre>
<p>however, the <code>c_ulong()</code> method returns an error because it needs an integer. </p>
<p>is there a way to use <code>struct.pack</code> to accomplish this? </p>
| 3 | 2008-11-25T14:30:37Z | 317,577 | <p>There's probably a better way, but this works:</p>
<pre><code>>>> ip = "192.168.1.1"
>>> struct.unpack('>I', struct.pack('BBBB', *map(int, ip.split('.'))))[0]
3232235777L
</code></pre>
| 0 | 2008-11-25T14:46:04Z | [
"python",
"dll",
"ip-address",
"ctypes"
] |
Python: packing an ip address as a ctype.c_ulong() for use with DLL | 317,531 | <p>given the following code: </p>
<pre><code>import ctypes
ip="192.168.1.1"
thisdll = ctypes.cdll['aDLL']
thisdll.functionThatExpectsAnIP(ip)
</code></pre>
<p>how can I correctly pack this for a DLL that expects it as a c_ulong datatype?</p>
<p>I've tried using: </p>
<pre><code>ip_netFrmt = socket.inet_aton(ip)
ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt)
</code></pre>
<p>however, the <code>c_ulong()</code> method returns an error because it needs an integer. </p>
<p>is there a way to use <code>struct.pack</code> to accomplish this? </p>
| 3 | 2008-11-25T14:30:37Z | 317,583 | <p>The inet_aton returns a string of bytes. This used to be the <em>lingua franca</em> for C-language interfaces.</p>
<p>Here's how to unpack those bytes into a more useful value.</p>
<pre><code>>>> import socket
>>> packed_n= socket.inet_aton("128.0.0.1")
>>> import struct
>>> struct.unpack( "!L", packed_n )
(2147483649L,)
>>> hex(_[0])
'0x80000001L'
</code></pre>
<p>This unpacked value can be used with ctypes. The hex thing is just to show you that the unpacked value looks a lot like an IP address.</p>
| 6 | 2008-11-25T14:47:23Z | [
"python",
"dll",
"ip-address",
"ctypes"
] |
Python: packing an ip address as a ctype.c_ulong() for use with DLL | 317,531 | <p>given the following code: </p>
<pre><code>import ctypes
ip="192.168.1.1"
thisdll = ctypes.cdll['aDLL']
thisdll.functionThatExpectsAnIP(ip)
</code></pre>
<p>how can I correctly pack this for a DLL that expects it as a c_ulong datatype?</p>
<p>I've tried using: </p>
<pre><code>ip_netFrmt = socket.inet_aton(ip)
ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt)
</code></pre>
<p>however, the <code>c_ulong()</code> method returns an error because it needs an integer. </p>
<p>is there a way to use <code>struct.pack</code> to accomplish this? </p>
| 3 | 2008-11-25T14:30:37Z | 317,642 | <p>For a more thorough way of handling IPs (v6, CIDR-style stuff etc) check out how it's done in <a href="http://www.mindrot.org/projects/py-radix/" rel="nofollow">py-radix</a>, esp. <a href="http://anoncvs.mindrot.org/index.cgi/py-radix/radix.c?revision=1.17&view=markup" rel="nofollow">prefix_pton</a>.</p>
| 0 | 2008-11-25T15:07:11Z | [
"python",
"dll",
"ip-address",
"ctypes"
] |
Standard C or Python libraries to compute standard deviation of normal distribution | 317,963 | <p>Say we have normal distribution n(x): mean=0 and \int_{-a}^{a} n(x) = P.</p>
<p>What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task?</p>
| 4 | 2008-11-25T16:25:34Z | 317,979 | <p>Take a look at the <a href="http://scipy.org/" rel="nofollow">sciPy Project</a>, it should have what you need.</p>
| 1 | 2008-11-25T16:29:05Z | [
"python",
"c",
"algorithm",
"math",
"probability"
] |
Standard C or Python libraries to compute standard deviation of normal distribution | 317,963 | <p>Say we have normal distribution n(x): mean=0 and \int_{-a}^{a} n(x) = P.</p>
<p>What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task?</p>
| 4 | 2008-11-25T16:25:34Z | 317,980 | <p><a href="http://www.scipy.org/" rel="nofollow">SciPy</a> has a <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/#scipy-organization" rel="nofollow">stats</a> sub-package.</p>
| 3 | 2008-11-25T16:29:17Z | [
"python",
"c",
"algorithm",
"math",
"probability"
] |
Standard C or Python libraries to compute standard deviation of normal distribution | 317,963 | <p>Say we have normal distribution n(x): mean=0 and \int_{-a}^{a} n(x) = P.</p>
<p>What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task?</p>
| 4 | 2008-11-25T16:25:34Z | 318,986 | <p>If X is normal with mean 0 and standard deviation sigma, it must hold </p>
<pre><code>P = Prob[ -a <= X <= a ] = Prob[ -a/sigma <= N <= a/sigma ]
= 2 Prob[ 0 <= N <= a/sigma ]
= 2 ( Prob[ N <= a/sigma ] - 1/2 )
</code></pre>
<p>where N is normal with mean 0 and standard deviation 1. Hence</p>
<pre><code>P/2 + 1/2 = Prob[ N <= a/sigma ] = Phi(a/sigma)
</code></pre>
<p>Where Phi is the cumulative distribution function (cdf) of a normal variable with mean 0 and stddev 1. Now we need the <em>inverse</em> normal cdf (or the "percent point function"), which in Python is scipy.stats.norm.ppf(). Sample code:</p>
<pre><code>from scipy.stats import norm
P = 0.3456
a = 3.0
a_sigma = float(norm.ppf(P/2 + 0.5)) # a/sigma
sigma = a/a_sigma # Here is the standard deviation
</code></pre>
<p>For example, we know that the probability of a N(0,1) variable falling int the interval [-1.1] is ~ 0.682 (the dark blue area in <a href="http://en.wikipedia.org/wiki/Image:Standard_deviation_diagram.svg" rel="nofollow">this figure</a>). If you set P = 0.682 and a = 1.0 you obtain sigma ~ 1.0, which is indeed the standard deviation. </p>
| 7 | 2008-11-25T21:44:54Z | [
"python",
"c",
"algorithm",
"math",
"probability"
] |
Standard C or Python libraries to compute standard deviation of normal distribution | 317,963 | <p>Say we have normal distribution n(x): mean=0 and \int_{-a}^{a} n(x) = P.</p>
<p>What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task?</p>
| 4 | 2008-11-25T16:25:34Z | 319,878 | <p>The standard deviation of a mean-zero gaussian distribution with Pr(-a < X < a) = P is</p>
<pre><code>a/(sqrt(2)*inverseErf(P))
</code></pre>
<p>which is the expression you're looking for, where inverseErf is the inverse of the error function (commonly known as erf).</p>
<p>For C, the Gnu Scientific Library (GSL) is a good resource. However it only has erf, not inverseErf, so you'd have to invert it yourself (a simple binary search would do the trick). Alternatively, here's a nice way to approximate erf and inverseErf: </p>
<p><a href="http://homepages.physik.uni-muenchen.de/~Winitzki/erf-approx.pdf" rel="nofollow">http://homepages.physik.uni-muenchen.de/~Winitzki/erf-approx.pdf</p>
<p>For Python, inverseErf is available as <code>erfinv</code> in the SciPy</a> library, so the following gives the standard deviation:</p>
<pre><code>a/(math.sqrt(2)*erfinv(P))
</code></pre>
<p>PS: There's some kind of bug in Stackoverflow's URL rendering and it wouldn't let me link to GSL above: <a href="http://www.gnu.org/software/gsl" rel="nofollow">http://www.gnu.org/software/gsl</a>.
It also renders wrong when I make the URL above with a pdf a proper link.</p>
| 5 | 2008-11-26T06:05:02Z | [
"python",
"c",
"algorithm",
"math",
"probability"
] |
Python: converting strings for use with ctypes.c_void_p() | 318,067 | <p>given a string:</p>
<pre><code>msg="hello world"
</code></pre>
<p><strong>How can I define this as a <code>ctypes.c_void_p()</code> data type?</strong></p>
<p>the following code yields a "cannot be converted to pointer" exception:</p>
<pre><code>data=ctypes.c_void_p(msg)
</code></pre>
<p><code>data</code> is required to be a <code>void*</code> type in C, because it is being passed to a DLL. </p>
<p>I'm assuming there is a way to pack/unpack the string using the <code>struct</code> package, but unfortunately I am very unfamiliar with this process.</p>
| 7 | 2008-11-25T16:49:18Z | 318,140 | <p>Something like this? Using <code>ctypes.cast</code>?</p>
<pre><code>>>> import ctypes
>>> p1= ctypes.c_char_p("hi mom")
>>> ctypes.cast( p1, ctypes.c_void_p )
c_void_p(11133300)
</code></pre>
| 10 | 2008-11-25T17:12:04Z | [
"python",
"dll",
"types",
"ctypes"
] |
Running numpy from cygwin | 318,390 | <p>I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. </p>
<p>This all works great when I run the Python (command line) tool that comes with Python.</p>
<p>However, if I run cygwin and then run Python from within, it cannot find the numpy package.</p>
<p>What environment variable do I need to set? What value should it be set to? </p>
| 2 | 2008-11-25T18:23:15Z | 318,419 | <p>Cygwin comes with its own version of Python, so it's likely that you have two Python installs on your system; one that installed under Windows and one which came with Cygwin.</p>
<p>To test this, try opening a bash prompt in Cygwin and typing <code>which python</code> to see where the Python executable is located. If it says <code>/cygdrive/c/Python25/python.exe</code> or something similar then you'll know you're running the Windows executable. If you see <code>/usr/local/bin/python</code> or something like that, then you'll know that you're running the Cygwin version.</p>
<p>I recommend opening a DOS prompt and running Python from there when you need interactive usage. This will keep your two Python installs nicely separate (it can be very useful to have both; I do this on my own machine). Also, you may have some problems running a program designed for Windows interactive console use from within a Cygwin shell.</p>
| 3 | 2008-11-25T18:32:43Z | [
"python",
"numpy"
] |
Running numpy from cygwin | 318,390 | <p>I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. </p>
<p>This all works great when I run the Python (command line) tool that comes with Python.</p>
<p>However, if I run cygwin and then run Python from within, it cannot find the numpy package.</p>
<p>What environment variable do I need to set? What value should it be set to? </p>
| 2 | 2008-11-25T18:23:15Z | 318,422 | <p>You're running a separate copy of python provided by cygwin.</p>
<p>You can run /cygdrive/c/python25/python (or wherever you installed it)
to get your win32 one, or just install another copy of numpy.</p>
| 1 | 2008-11-25T18:33:31Z | [
"python",
"numpy"
] |
Running numpy from cygwin | 318,390 | <p>I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. </p>
<p>This all works great when I run the Python (command line) tool that comes with Python.</p>
<p>However, if I run cygwin and then run Python from within, it cannot find the numpy package.</p>
<p>What environment variable do I need to set? What value should it be set to? </p>
| 2 | 2008-11-25T18:23:15Z | 318,423 | <p>Ensure that PYTHONPATH has NumPy. Refer <a href="http://www.python.org/doc/2.5.2/tut/node8.html" rel="nofollow">The Module Search Path (section 6.1.2)</a> and <a href="http://www.python.org/doc/2.5.2/inst/search-path.html" rel="nofollow">Modifying Python's Search Path (section 4.1)</a>.</p>
| 0 | 2008-11-25T18:33:33Z | [
"python",
"numpy"
] |
Running numpy from cygwin | 318,390 | <p>I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. </p>
<p>This all works great when I run the Python (command line) tool that comes with Python.</p>
<p>However, if I run cygwin and then run Python from within, it cannot find the numpy package.</p>
<p>What environment variable do I need to set? What value should it be set to? </p>
| 2 | 2008-11-25T18:23:15Z | 798,145 | <p>numpy built for windows is not compatible with cygwin python. You have to build it by yourself on cygwin.</p>
| 1 | 2009-04-28T14:08:41Z | [
"python",
"numpy"
] |
Does anyone know where there is a recipe for serializing data and preserving its order in the output? | 318,700 | <p>I am working with a set of data that I have converted to a list of dictionaries</p>
<p>For example one item in my list is </p>
<pre><code>{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'}
</code></pre>
<p>Per request </p>
<p>The second item in my list could be:</p>
<pre><code> {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2006',
'actionDate': u'C20070627', 'data': u'86,000', 'rowLabel': u'Sales of Bananas'}
</code></pre>
<p>The third item could be:</p>
<pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2005',
'actionDate': u'C20070627', 'data': u'116,000', 'rowLabel': u'Sales of Cherries'}
</code></pre>
<p>The fourth item could be:</p>
<pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2006',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Sales of Cherries'}
</code></pre>
<p>The reason I need to pickle this is because I need to find out all of the ways the columns were labeled before I consolidate the results and put them into a database. The first and second items will be one row in the results, the third and fourth would be the next line in the results (after someone decides what the uniform column header label should be)</p>
<p>I tested pickle and was able to save and retrieve my data. However, I need to be able to preserve the order in the output. One idea I have is to add another key that would be a counter so I could retrieve my data and then sort by the counter. Is there a better way?</p>
<p>I don't want to put this into a database because it is not permanent. </p>
<p>I marked an answer down below. It is not what I am getting, so I need to figure out if the problem is somewhere else in my code.</p>
| 1 | 2008-11-25T20:17:52Z | 318,719 | <p>Python does not retain order in dictionaries.<br>
However, there is the <a href="http://docs.python.org/2/library/collections.html?highlight=collections#ordereddict-objects" rel="nofollow">OrderedDict</a> class in the <em>collections</em> module.</p>
<p>Another option would be to use a list of tuples:</p>
<pre><code>[('reportDate', u'R20080501'), ('idnum', u'1078099'), ...etc]
</code></pre>
<p>You can use the built in <code>dict()</code> if you need to convert this to a dictionary later.</p>
| 1 | 2008-11-25T20:23:43Z | [
"python",
"serialization"
] |
Does anyone know where there is a recipe for serializing data and preserving its order in the output? | 318,700 | <p>I am working with a set of data that I have converted to a list of dictionaries</p>
<p>For example one item in my list is </p>
<pre><code>{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'}
</code></pre>
<p>Per request </p>
<p>The second item in my list could be:</p>
<pre><code> {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2006',
'actionDate': u'C20070627', 'data': u'86,000', 'rowLabel': u'Sales of Bananas'}
</code></pre>
<p>The third item could be:</p>
<pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2005',
'actionDate': u'C20070627', 'data': u'116,000', 'rowLabel': u'Sales of Cherries'}
</code></pre>
<p>The fourth item could be:</p>
<pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2006',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Sales of Cherries'}
</code></pre>
<p>The reason I need to pickle this is because I need to find out all of the ways the columns were labeled before I consolidate the results and put them into a database. The first and second items will be one row in the results, the third and fourth would be the next line in the results (after someone decides what the uniform column header label should be)</p>
<p>I tested pickle and was able to save and retrieve my data. However, I need to be able to preserve the order in the output. One idea I have is to add another key that would be a counter so I could retrieve my data and then sort by the counter. Is there a better way?</p>
<p>I don't want to put this into a database because it is not permanent. </p>
<p>I marked an answer down below. It is not what I am getting, so I need to figure out if the problem is somewhere else in my code.</p>
| 1 | 2008-11-25T20:17:52Z | 318,722 | <p>The Python dict is an unordered container. If you need to preserve the order of the entries, you should consider using a list of 2-tuples.</p>
<p>Another option would be to keep an extra, ordered list of the keys. This way you can benefit from the quick, keyed access offered by the dictionary, while still being able to iterate through its values in an ordered fashion:</p>
<pre><code>data = {'reportDate': u'R20070501', 'idnum': u'1078099',
'columnLabel': u'2005', 'actionDate': u'C20070627',
'data': u'76,000', 'rowLabel': u'Sales of Bananas'}
dataOrder = ['reportDate', 'idnum', 'columnLabel',
'actionDate', 'data', 'rowLabel']
for key in dataOrder:
print key, data[key]
</code></pre>
| 1 | 2008-11-25T20:24:43Z | [
"python",
"serialization"
] |
Does anyone know where there is a recipe for serializing data and preserving its order in the output? | 318,700 | <p>I am working with a set of data that I have converted to a list of dictionaries</p>
<p>For example one item in my list is </p>
<pre><code>{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'}
</code></pre>
<p>Per request </p>
<p>The second item in my list could be:</p>
<pre><code> {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2006',
'actionDate': u'C20070627', 'data': u'86,000', 'rowLabel': u'Sales of Bananas'}
</code></pre>
<p>The third item could be:</p>
<pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2005',
'actionDate': u'C20070627', 'data': u'116,000', 'rowLabel': u'Sales of Cherries'}
</code></pre>
<p>The fourth item could be:</p>
<pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2006',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Sales of Cherries'}
</code></pre>
<p>The reason I need to pickle this is because I need to find out all of the ways the columns were labeled before I consolidate the results and put them into a database. The first and second items will be one row in the results, the third and fourth would be the next line in the results (after someone decides what the uniform column header label should be)</p>
<p>I tested pickle and was able to save and retrieve my data. However, I need to be able to preserve the order in the output. One idea I have is to add another key that would be a counter so I could retrieve my data and then sort by the counter. Is there a better way?</p>
<p>I don't want to put this into a database because it is not permanent. </p>
<p>I marked an answer down below. It is not what I am getting, so I need to figure out if the problem is somewhere else in my code.</p>
| 1 | 2008-11-25T20:17:52Z | 318,864 | <p>So what's wrong with pickle? If you structure your data as a list of dicts, then everything should work as you want it to (if I understand your problem).</p>
<pre><code>>>> import pickle
>>> d1 = {1:'one', 2:'two', 3:'three'}
>>> d2 = {1:'eleven', 2:'twelve', 3:'thirteen'}
>>> d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty-three'}
>>> data = [d1, d2, d3]
>>> out = open('data.pickle', 'wb')
>>> pickle.dump(data, out)
>>> out.close()
>>> input = open('data.pickle')
>>> data2 = pickle.load(input)
>>> data == data2
True
</code></pre>
| 5 | 2008-11-25T21:05:56Z | [
"python",
"serialization"
] |
How to call python2.5 function from x86asm/x64asm? | 319,232 | <p>I'll have couple of python functions I must interface with from the assembly code. The solution doesn't need to be a complete solution because I'm not going to interface with python code for too long. Anyway, I chewed it a bit:</p>
<ul>
<li>What does a python object look like in memory?</li>
<li>How can I call a python function?</li>
<li>How can I pass python objects as python objects for ctypes interface?</li>
<li>Could ctypes interface make my work easier in any alternative way?</li>
</ul>
| 2 | 2008-11-25T23:14:51Z | 319,274 | <p>You will want to read and understand <a href="http://python.org/doc/2.5/ext/ext.html" rel="nofollow">Extending and Embedding the Python Interpreter</a> and the <a href="http://python.org/doc/2.5/api/api.html" rel="nofollow">Python/C API Reference Manual</a>. This describes how to interface with Python from C. Everything you can do in C you can equivalently do in assembly code too, but you're on your own for this as it is not directly described from a Python perspective.</p>
| 2 | 2008-11-25T23:37:39Z | [
"python",
"assembly"
] |
How to call python2.5 function from x86asm/x64asm? | 319,232 | <p>I'll have couple of python functions I must interface with from the assembly code. The solution doesn't need to be a complete solution because I'm not going to interface with python code for too long. Anyway, I chewed it a bit:</p>
<ul>
<li>What does a python object look like in memory?</li>
<li>How can I call a python function?</li>
<li>How can I pass python objects as python objects for ctypes interface?</li>
<li>Could ctypes interface make my work easier in any alternative way?</li>
</ul>
| 2 | 2008-11-25T23:14:51Z | 327,529 | <p>It's certainly doable, but you'd have a much easier time reading the C API docs and writing a go-between function in C.</p>
<p>Come to think of it, C is highly recommended, since it may be hard to tell which of the routines you're calling might be implemented as preprocessor macros.</p>
| 1 | 2008-11-29T13:35:58Z | [
"python",
"assembly"
] |
How do I do a case insensitive string comparison in Python? | 319,426 | <p>What's the best way to do case insensitive string comparison in Python?</p>
<p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
| 270 | 2008-11-26T01:06:44Z | 319,435 | <p>Assuming ASCII strings:</p>
<pre><code>string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print "The strings are the same (case insensitive)"
else:
print "The strings are not the same (case insensitive)"
</code></pre>
| 288 | 2008-11-26T01:09:22Z | [
"python",
"comparison",
"case-insensitive"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.