title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How can I traverse a file system with a generator?
1,698,596
<p>I'm trying to create a utility class for traversing all the files in a directory, including those within subdirectories and sub-subdirectories. I tried to use a generator because generators are cool; however, I hit a snag.</p> <pre><code> def grab_files(directory): for name in os.listdir(directory): ful...
12
2009-11-09T01:00:46Z
22,948,232
<p>Starting with Python 3.4, you can use the <a href="https://docs.python.org/3.4/library/pathlib.html" rel="nofollow">Pathlib</a> module:</p> <pre><code>In [48]: def alliter(p): ....: yield p ....: for sub in p.iterdir(): ....: if sub.is_dir(): ....: yield from alliter(sub) ...
2
2014-04-08T21:09:37Z
[ "python", "recursion", "iterator", "generator", "yield" ]
How can I traverse a file system with a generator?
1,698,596
<p>I'm trying to create a utility class for traversing all the files in a directory, including those within subdirectories and sub-subdirectories. I tried to use a generator because generators are cool; however, I hit a snag.</p> <pre><code> def grab_files(directory): for name in os.listdir(directory): ful...
12
2009-11-09T01:00:46Z
37,117,157
<p>addendum to the answer of gerrit. I wanted to make something more flexible.</p> <p>list all files in <code>pth</code> matching a given <code>pattern</code>, can also list dirs if <code>only_file</code> is <code>False</code></p> <pre><code>from pathlib import Path def walk(pth=Path('.'), pattern='*', only_file=Tru...
0
2016-05-09T13:33:28Z
[ "python", "recursion", "iterator", "generator", "yield" ]
BeautifulSoup is omitting body of page
1,698,627
<p>BeautifulSoup newbe... Need help</p> <p>Here is the code sample...</p> <pre><code>from mechanize import Browser from BeautifulSoup import BeautifulSoup mec = Browser() #url1 = "http://www.wines.com/catalog/index.php?cPath=21" url2 = "http://www.wines.com/catalog/product_info.php?products_id=4866" page = mec.open(...
2
2009-11-09T01:12:02Z
1,698,700
<p>Yes. The HTML is bad. </p> <p>Step 1a, <code>print soup.prettify()</code> and see where it stops indenting correctly. </p> <p>Step 1b (if 1a doesn't work). Just print the raw through any HTML prettifying. I use BBEdit for things that confuse Beautiful Soup.</p> <p>Look closely at the HTML. There will be some ...
2
2009-11-09T01:38:46Z
[ "python", "screen-scraping", "beautifulsoup" ]
BeautifulSoup is omitting body of page
1,698,627
<p>BeautifulSoup newbe... Need help</p> <p>Here is the code sample...</p> <pre><code>from mechanize import Browser from BeautifulSoup import BeautifulSoup mec = Browser() #url1 = "http://www.wines.com/catalog/index.php?cPath=21" url2 = "http://www.wines.com/catalog/product_info.php?products_id=4866" page = mec.open(...
2
2009-11-09T01:12:02Z
1,698,717
<p>Running on the HTML in question a <a href="http://validator.w3.org/check?uri=http%3A//www.wines.com/catalog/product%5Finfo.php%3Fproducts%5Fid%3D4866&amp;charset=%28detect+automatically%29&amp;doctype=Inline&amp;group=0" rel="nofollow">validator</a> shows 116 errors -- just too many to track down which one Beautiful...
0
2009-11-09T01:46:32Z
[ "python", "screen-scraping", "beautifulsoup" ]
BeautifulSoup is omitting body of page
1,698,627
<p>BeautifulSoup newbe... Need help</p> <p>Here is the code sample...</p> <pre><code>from mechanize import Browser from BeautifulSoup import BeautifulSoup mec = Browser() #url1 = "http://www.wines.com/catalog/index.php?cPath=21" url2 = "http://www.wines.com/catalog/product_info.php?products_id=4866" page = mec.open(...
2
2009-11-09T01:12:02Z
1,698,718
<p>The HTML is indeed horrible :-) BeautifulSoup 3.0.7 is much better at handling malformed HTML than the current version. The project website warns: "Currently the 3.0.x series is better at parsing bad HTML than the 3.1 series."... and there's a great page <a href="http://www.crummy.com/software/BeautifulSoup/3.1-prob...
1
2009-11-09T01:46:46Z
[ "python", "screen-scraping", "beautifulsoup" ]
BeautifulSoup is omitting body of page
1,698,627
<p>BeautifulSoup newbe... Need help</p> <p>Here is the code sample...</p> <pre><code>from mechanize import Browser from BeautifulSoup import BeautifulSoup mec = Browser() #url1 = "http://www.wines.com/catalog/index.php?cPath=21" url2 = "http://www.wines.com/catalog/product_info.php?products_id=4866" page = mec.open(...
2
2009-11-09T01:12:02Z
1,698,721
<p>It seems to be getting tripped up by this bad tag:</p> <pre><code>&lt;META NAME="description" CONTENT="$49 at Wines.com "Deep red. Red- and blackcurrant, cherry and menthol on the nose, with subtle vanilla, cola and tobacco notes adding complexity. Tightly wound red berry and bitter cherry flavors are framed by dus...
2
2009-11-09T01:47:37Z
[ "python", "screen-scraping", "beautifulsoup" ]
Python data structure recommendation?
1,698,734
<p>I currently have a structure that is a dict: each value is a list that contains numeric values. Each of these numeric lists contain what (to borrow a SQL idiom) you could call a primary key containing the first three values which are: a year, a player identifier, and a team identifier. This is the key for the dict.<...
4
2009-11-09T01:53:12Z
1,698,756
<p>Put your data into SQLite, and use its relational engine to do the work. You can create an in-memory database and not even have to touch the disk.</p>
4
2009-11-09T02:02:22Z
[ "python" ]
Python data structure recommendation?
1,698,734
<p>I currently have a structure that is a dict: each value is a list that contains numeric values. Each of these numeric lists contain what (to borrow a SQL idiom) you could call a primary key containing the first three values which are: a year, a player identifier, and a team identifier. This is the key for the dict.<...
4
2009-11-09T01:53:12Z
1,698,774
<p>The syntax <code>stats[year=2001, idx=3]</code> is invalid Python and there is no way you can make it work with those square brackets and "keyword arguments"; you'll need to have a function or method call in order to accept keyword arguments.</p> <p>So, say we make it a function, to be called like <code>wells(stats...
1
2009-11-09T02:10:53Z
[ "python" ]
Python data structure recommendation?
1,698,734
<p>I currently have a structure that is a dict: each value is a list that contains numeric values. Each of these numeric lists contain what (to borrow a SQL idiom) you could call a primary key containing the first three values which are: a year, a player identifier, and a team identifier. This is the key for the dict.<...
4
2009-11-09T01:53:12Z
1,698,791
<p>Read up on Data Warehousing. Any book. </p> <p>Read up on Star Schema Design. Any book. Seriously. </p> <p>You have several dimensions: Year, Player, Team. </p> <p>You have one fact: score</p> <p>You want to have a structure like this.</p> <p>You then want to create a set of dimension indexes like this.<...
4
2009-11-09T02:19:30Z
[ "python" ]
Python data structure recommendation?
1,698,734
<p>I currently have a structure that is a dict: each value is a list that contains numeric values. Each of these numeric lists contain what (to borrow a SQL idiom) you could call a primary key containing the first three values which are: a year, a player identifier, and a team identifier. This is the key for the dict.<...
4
2009-11-09T01:53:12Z
1,698,795
<pre><code>def getSum(d, year, idx): sum = 0 for key in d.keys(): if key[0] == year: sum += d[key][idx] return sum </code></pre> <p>This should get you started. I have made the assumption in this code, that ONLY year will be asked for, but it should be easy enough for you to manipulate ...
0
2009-11-09T02:20:40Z
[ "python" ]
"Slice lists" and "the ellipsis" in Python; slicing lists and lists of lists with lists of slices
1,698,753
<p>Original question: Can someone tell me how to use "slice lists" and the "ellipsis"? When are they useful? Thanks.</p> <p>Here's what the language definition says about "slice_list" and "ellipsis"; Alex Martelli's answer points out their origin, which is not what I had envisioned.</p> <p>[<a href="http://docs.py...
2
2009-11-09T02:01:45Z
1,698,758
<p>Numpy uses them to implement array slicing.</p>
3
2009-11-09T02:03:14Z
[ "python", "list", "slice", "itertools" ]
"Slice lists" and "the ellipsis" in Python; slicing lists and lists of lists with lists of slices
1,698,753
<p>Original question: Can someone tell me how to use "slice lists" and the "ellipsis"? When are they useful? Thanks.</p> <p>Here's what the language definition says about "slice_list" and "ellipsis"; Alex Martelli's answer points out their origin, which is not what I had envisioned.</p> <p>[<a href="http://docs.py...
2
2009-11-09T02:01:45Z
1,698,779
<p>Slice lists and ellipsis were originally introduced in Python to supply nice syntax sugar for the precedessor of numpy (good old Numeric). If you're using numpy (no reason to go back to any of its predecessors!-) you should of course use them; if for whatever strange reason you're doing your own implementation of s...
10
2009-11-09T02:13:13Z
[ "python", "list", "slice", "itertools" ]
"Slice lists" and "the ellipsis" in Python; slicing lists and lists of lists with lists of slices
1,698,753
<p>Original question: Can someone tell me how to use "slice lists" and the "ellipsis"? When are they useful? Thanks.</p> <p>Here's what the language definition says about "slice_list" and "ellipsis"; Alex Martelli's answer points out their origin, which is not what I had envisioned.</p> <p>[<a href="http://docs.py...
2
2009-11-09T02:01:45Z
1,698,780
<p>I'm not too sure about ellipsis, so I will not address that, lest I give you a bad answer.</p> <p>Here goes list slicing:</p> <p>I hope you know that list indeces begin at 0.</p> <pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p>Indexing into a list:</p> <pre><code>l[0] &gt;&gt;&gt; 0 l[5] &gt;&gt...
2
2009-11-09T02:13:52Z
[ "python", "list", "slice", "itertools" ]
Local import statements in Python
1,699,108
<p>I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea?</p> <pre><code>def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i ...
30
2009-11-09T04:34:04Z
1,699,112
<p>Please see <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>Please note that this is purely a stylistic choice as ...
11
2009-11-09T04:35:55Z
[ "python", "python-import" ]
Local import statements in Python
1,699,108
<p>I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea?</p> <pre><code>def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i ...
30
2009-11-09T04:34:04Z
1,699,127
<p>Style aside, it is true that an imported module will only be imported once (unless <code>reload</code> is called on said module). However, each call to <code>import Foo</code> will have implicitly check to see if that module is already loaded (by checking <a href="http://docs.python.org/library/sys.html#sys.modules...
9
2009-11-09T04:41:17Z
[ "python", "python-import" ]
Local import statements in Python
1,699,108
<p>I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea?</p> <pre><code>def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i ...
30
2009-11-09T04:34:04Z
1,699,139
<p>When the Python interpreter hits an import statement, it starts reading all the function definitions in the file that is being imported. This explains why sometimes, imports can take a while.</p> <p>The idea behind doing all the importing at the start IS a stylistic convention as Andrew Hare points out. However, yo...
3
2009-11-09T04:45:57Z
[ "python", "python-import" ]
Local import statements in Python
1,699,108
<p>I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea?</p> <pre><code>def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i ...
30
2009-11-09T04:34:04Z
1,699,178
<p>I can see two ways when you need to import it locally</p> <ol> <li><p>For testing purpose or for temporary usage, you need to import something, in that case you should put import at the place of usage.</p></li> <li><p>Sometime to avoid cyclic dependency you will need to import it inside a function but that would me...
0
2009-11-09T05:03:23Z
[ "python", "python-import" ]
Local import statements in Python
1,699,108
<p>I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea?</p> <pre><code>def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i ...
30
2009-11-09T04:34:04Z
1,704,204
<p>I've done this, and then wished I hadn't. Ordinarily, if I'm writing a function, and that function needs to use <code>StringIO</code>, I can look at the top of the module, see if it's being imported, and then add it if it's not. </p> <p>Suppose I don't do this; suppose I add it locally within my function. And th...
8
2009-11-09T22:03:22Z
[ "python", "python-import" ]
Local import statements in Python
1,699,108
<p>I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea?</p> <pre><code>def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i ...
30
2009-11-09T04:34:04Z
1,716,375
<p>The other answers evince a mild confusion as to how <code>import</code> really works.</p> <p>This statement:</p> <pre><code>import foo </code></pre> <p>is roughly equivalent to this statement:</p> <pre><code>foo = __import__('foo', globals(), locals(), [], -1) </code></pre> <p>That is, it creates a variable in ...
50
2009-11-11T16:31:37Z
[ "python", "python-import" ]
UnicodeDecodeError with Django's request.FILES
1,699,126
<p>I have the following code in the view call..</p> <pre><code>def view(request): body = u"" for filename, f in request.FILES.items(): body = body + 'Filename: ' + filename + '\n' + f.read() + '\n' </code></pre> <p>On some cases I get</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode by...
5
2009-11-09T04:41:13Z
1,699,159
<p>you are appending f.read() directly to unicode string, without decoding it, if the data you are reading from file is utf-8 encoded use utf-8, else use whatever encoding it is in.</p> <p><strong>decode it first and then append to body</strong> e.g.</p> <pre><code>data = f.read().decode("utf-8") body = body + 'Filen...
4
2009-11-09T04:56:29Z
[ "python", "django" ]
UnicodeDecodeError with Django's request.FILES
1,699,126
<p>I have the following code in the view call..</p> <pre><code>def view(request): body = u"" for filename, f in request.FILES.items(): body = body + 'Filename: ' + filename + '\n' + f.read() + '\n' </code></pre> <p>On some cases I get</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode by...
5
2009-11-09T04:41:13Z
1,699,299
<p>Anurag's answer is correct. However another problem here is you can't for certain know the encoding of the files that users upload. It may be useful to loop over a tuple of the most common ones till you get the correct one:</p> <pre><code>encodings = ('windows-xxx', 'iso-yyy', 'utf-8',) for e in encodings: try:...
3
2009-11-09T05:55:56Z
[ "python", "django" ]
UnicodeDecodeError with Django's request.FILES
1,699,126
<p>I have the following code in the view call..</p> <pre><code>def view(request): body = u"" for filename, f in request.FILES.items(): body = body + 'Filename: ' + filename + '\n' + f.read() + '\n' </code></pre> <p>On some cases I get</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode by...
5
2009-11-09T04:41:13Z
1,699,322
<p>If you are not in control of the file encoding for files that can be uploaded , you can guess what encoding a file is in using the <a href="http://chardet.feedparser.org/" rel="nofollow">Universal Encoding Detector</a> module <code>chardet</code>.</p>
3
2009-11-09T06:04:55Z
[ "python", "django" ]
UnicodeDecodeError with Django's request.FILES
1,699,126
<p>I have the following code in the view call..</p> <pre><code>def view(request): body = u"" for filename, f in request.FILES.items(): body = body + 'Filename: ' + filename + '\n' + f.read() + '\n' </code></pre> <p>On some cases I get</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode by...
5
2009-11-09T04:41:13Z
1,699,348
<p>Django has some <a href="http://docs.djangoproject.com/en/dev/ref/unicode/#conversion-functions" rel="nofollow">utilities</a> that handle this (smart_unicode, force_unicode, smart_str). Generally you just need smart_unicode.</p> <pre><code>from django.utils.encoding import smart_unicode def view(request): body...
4
2009-11-09T06:13:22Z
[ "python", "django" ]
What does the brackets mean in python: table[r][pos+i]?
1,699,342
<p>This is the full code:</p> <pre><code>def checkRow(table, r, pos, word): # done for you! for i in range(0, len(word)): if table[r][pos+i] != word[i]: return False return True </code></pre> <p>I know the bracket mean the index value (in this case r some value of the index table) but what...
0
2009-11-09T06:12:08Z
1,699,360
<p>It means that the value of <code>table[r]</code> is <em>another</em> array (an array within an array), which you are indexing into with <code>[pos+i]</code>. So it's the equivalent of:</p> <pre><code>foo = table[r] if foo[pos+i] != word[i]: </code></pre>
1
2009-11-09T06:16:17Z
[ "python" ]
What does the brackets mean in python: table[r][pos+i]?
1,699,342
<p>This is the full code:</p> <pre><code>def checkRow(table, r, pos, word): # done for you! for i in range(0, len(word)): if table[r][pos+i] != word[i]: return False return True </code></pre> <p>I know the bracket mean the index value (in this case r some value of the index table) but what...
0
2009-11-09T06:12:08Z
1,699,440
<p>table[r][pos+i]</p> <p>To get the pos+i character of the string table[r]</p>
0
2009-11-09T06:51:04Z
[ "python" ]
What does the brackets mean in python: table[r][pos+i]?
1,699,342
<p>This is the full code:</p> <pre><code>def checkRow(table, r, pos, word): # done for you! for i in range(0, len(word)): if table[r][pos+i] != word[i]: return False return True </code></pre> <p>I know the bracket mean the index value (in this case r some value of the index table) but what...
0
2009-11-09T06:12:08Z
1,703,256
<p>If r was length 2 and the pos was length 3 the table could be represented this way:</p> <pre><code> | pos+0 | pos+1 | pos+2 | ---------------------------- r+0| ???1 | ???2 | ???3 | ---------------------------- r+1| ???4 | ???5 | ???6 | ---------------------------- </code></pre> <p>Where the ??? represent t...
0
2009-11-09T19:39:55Z
[ "python" ]
regex in for loop
1,699,467
<p>How do you use a regex with a for loop in Python</p> <pre><code> example data abc 1 xyz 0 abc 2 xyz 1 abc 3 xyz 2 </code></pre> <p>How do you write regex for something like below</p> <pre><code>for i in range(1, 3): re.match(abc +i xyz +(i-1)) </code></pre>
1
2009-11-09T06:56:53Z
1,699,544
<p>This substitutes <code>i</code> into the first <code>%s</code> and <code>i-1</code> into the second <code>%s</code></p> <pre><code>re.match("abc %s xyz %s"%(i,i-1), data) </code></pre> <p>another way to write it would be</p> <pre><code>re.match("abc "+str(i)+" xyz "+str(i-1), data) </code></pre>
3
2009-11-09T07:15:46Z
[ "python", "regex" ]
regex in for loop
1,699,467
<p>How do you use a regex with a for loop in Python</p> <pre><code> example data abc 1 xyz 0 abc 2 xyz 1 abc 3 xyz 2 </code></pre> <p>How do you write regex for something like below</p> <pre><code>for i in range(1, 3): re.match(abc +i xyz +(i-1)) </code></pre>
1
2009-11-09T06:56:53Z
1,699,571
<p>You can't make a single regex that includes math expressions which are evaluated at regex matching time. However, you can dynamically generate regex expressions, using the usual Python string formatting techniques:</p> <pre><code>import re example_data = """ this line will not match abc 1 xyz 0 this line will not...
2
2009-11-09T07:27:09Z
[ "python", "regex" ]
Python file manipulation
1,699,552
<p>Assume I have such folders</p> <pre><code> rootfolder | / \ \ 01 02 03 .... | 13_itemname.xml </code></pre> <p>So under my rootfolder, each directory represents a month like 01 02 03 and under these directories I have items with their create hour and item name such as 16_item1.xml, 24_item1...
1
2009-11-09T07:19:51Z
1,699,667
<p>Here are two methods doing what you ask (if I understood it properly). One with regex, one without. You choose which one you prefer ;)</p> <p>One bit which may seem like magic is the "setdefault" line. For an explanation, see <a href="http://docs.python.org/library/stdtypes.html#dict.setdefault" rel="nofollow">the ...
5
2009-11-09T08:06:24Z
[ "python", "file", "directory", "pattern-matching" ]
Python file manipulation
1,699,552
<p>Assume I have such folders</p> <pre><code> rootfolder | / \ \ 01 02 03 .... | 13_itemname.xml </code></pre> <p>So under my rootfolder, each directory represents a month like 01 02 03 and under these directories I have items with their create hour and item name such as 16_item1.xml, 24_item1...
1
2009-11-09T07:19:51Z
1,699,690
<p>Assuming that item names have a fixed length prefix and suffix (ie, a 3 character prefix such as '01_' and a 4 character suffix of '.xml'), you could solve the first part of the problem like this:</p> <pre><code>names = set(name[3:-4] for name in os.listdir('01') if name.endswith('.xml')] </code></pre> <p>That wil...
0
2009-11-09T08:17:09Z
[ "python", "file", "directory", "pattern-matching" ]
Python file manipulation
1,699,552
<p>Assume I have such folders</p> <pre><code> rootfolder | / \ \ 01 02 03 .... | 13_itemname.xml </code></pre> <p>So under my rootfolder, each directory represents a month like 01 02 03 and under these directories I have items with their create hour and item name such as 16_item1.xml, 24_item1...
1
2009-11-09T07:19:51Z
1,699,719
<p>Not sure exactly what you want to do, but here are some pointers that might be useful</p> <p><hr></p> <p>creating filenames ("%02d" means pad left with zeros)</p> <p><code>foldernames = ["%02d"%i for i in range(1,13)]</code></p> <p><code>filenames = ["%02d"%i for i in range(1,24)]</code></p> <p><hr></p> <p>use...
0
2009-11-09T08:23:44Z
[ "python", "file", "directory", "pattern-matching" ]
How to retrieve a directory of files from a remote server?
1,699,634
<p>If I have a directory on a remote web server that allows directory browsing, how would I go about to fetch all those files listed there from my other web server? I know I can use urllib2.urlopen to fetch individual files, but how would I get a list of all the files in that remote directory?</p>
3
2009-11-09T07:55:04Z
1,699,735
<p>If the webserver has directory browsing enabled, it will return a HTML document with links to all the files. You could parse the HTML document and extract all the links. This would give you the list of files.</p> <p>You can use the <a href="http://docs.python.org/library/htmlparser.html" rel="nofollow">HTMLParser</...
6
2009-11-09T08:29:24Z
[ "python", "file", "directory", "screen-scraping" ]
How to retrieve a directory of files from a remote server?
1,699,634
<p>If I have a directory on a remote web server that allows directory browsing, how would I go about to fetch all those files listed there from my other web server? I know I can use urllib2.urlopen to fetch individual files, but how would I get a list of all the files in that remote directory?</p>
3
2009-11-09T07:55:04Z
1,699,759
<p>Why don't you use <a href="http://curl.haxx.se/" rel="nofollow">curl</a> or <a href="http://www.gnu.org/software/wget/" rel="nofollow">wget</a> to recursively download the given page, and limit it upto 1 level. You will save all the trouble of writing the script.</p> <p>e.g. something like</p> <pre><code>wget -H -...
2
2009-11-09T08:35:38Z
[ "python", "file", "directory", "screen-scraping" ]
C# or other .net equivalents of core python modules for IronPython?
1,699,856
<p>I would like to compile and distribute (on .net) some python programs that work well with IronPython, but I am new to .net and am getting errors related to particular python modules. There is a utility for compiling to low level .net and it works well, but I get errors when dealing with common libraries; code that ...
1
2009-11-09T09:00:22Z
1,700,001
<p>The <code>os</code> (and <code>shutil</code> ) replacements in .NET are in the <a href="http://msdn.microsoft.com/en-us/library/system.io.aspx" rel="nofollow"><code>System.IO</code> namespace</a>.</p> <blockquote> <p>The System.IO namespace contains types that allow reading and writing to files and data streams, ...
2
2009-11-09T09:37:13Z
[ "c#", ".net", "python", "ironpython" ]
C# or other .net equivalents of core python modules for IronPython?
1,699,856
<p>I would like to compile and distribute (on .net) some python programs that work well with IronPython, but I am new to .net and am getting errors related to particular python modules. There is a utility for compiling to low level .net and it works well, but I get errors when dealing with common libraries; code that ...
1
2009-11-09T09:00:22Z
6,392,451
<p>For the <code>os</code> module you can use the <code>nt</code> module which provides some of the same functions as <code>os</code> including <code>stat</code>, <code>remove</code>, and <code>mkdir</code>. (It also includes others like <code>environ</code>, <code>getcwd</code>, <code>chdir</code>,and <code>popen</co...
0
2011-06-17T22:27:58Z
[ "c#", ".net", "python", "ironpython" ]
django, uni_form and python's __init__() function - how to pass arguments to a form?
1,700,043
<p>I'm having a bit of difficulty understanding how the python <code>__init__</code>( ) function works. What I'm trying to do is create a new form in django, and use the uni_form helper to display the form in a custom manner using fieldsets, however I'm passing an argument to the form that should slightly change the la...
2
2009-11-09T09:50:32Z
1,700,102
<p>You have misunderstood the way classes work in Python. You're trying to run code inside a class but outside of any function, which is unlikely to work, especially if it depends on something that happens inside <code>__init__</code>. That code will be evaluated when the class is first imported, whereas <code>__init__...
4
2009-11-09T10:03:10Z
[ "python", "django", "django-forms", "init" ]
Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests)
1,700,113
<p>I want to do something like:</p> <pre><code>all = [ x for x in t[1] for t in tests ] </code></pre> <p>tests looks like:</p> <pre><code>[ ("foo",[a,b,c]), ("bar",[d,e,f]) ] </code></pre> <p>So I want to have the result</p> <pre><code>all = [a,b,c,d,e,f] </code></pre> <p>My code does not work, Python says:</p> ...
6
2009-11-09T10:04:46Z
1,700,122
<p>It should work the other way around:</p> <pre><code>all = [x for t in tests for x in t[1]] </code></pre>
14
2009-11-09T10:07:11Z
[ "python", "list-comprehension" ]
Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests)
1,700,113
<p>I want to do something like:</p> <pre><code>all = [ x for x in t[1] for t in tests ] </code></pre> <p>tests looks like:</p> <pre><code>[ ("foo",[a,b,c]), ("bar",[d,e,f]) ] </code></pre> <p>So I want to have the result</p> <pre><code>all = [a,b,c,d,e,f] </code></pre> <p>My code does not work, Python says:</p> ...
6
2009-11-09T10:04:46Z
1,700,192
<p>When in doubt, don't use list comprehensions.</p> <p>Try <code>import this</code> in your Python shell and read the second line:</p> <pre><code>Explicit is better than implicit </code></pre> <p>This type of compounding of list comprehensions will puzzle a lot of Python programmers so at least add a comment to exp...
5
2009-11-09T10:26:17Z
[ "python", "list-comprehension" ]
Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests)
1,700,113
<p>I want to do something like:</p> <pre><code>all = [ x for x in t[1] for t in tests ] </code></pre> <p>tests looks like:</p> <pre><code>[ ("foo",[a,b,c]), ("bar",[d,e,f]) ] </code></pre> <p>So I want to have the result</p> <pre><code>all = [a,b,c,d,e,f] </code></pre> <p>My code does not work, Python says:</p> ...
6
2009-11-09T10:04:46Z
1,702,290
<p>That looks like a reduce to me. Unfortunately Python does not offer any syntactic sugar for reduce, so we have to use lambda:</p> <pre><code>reduce(lambda x, y: x+y[1], tests, []) </code></pre>
1
2009-11-09T16:50:47Z
[ "python", "list-comprehension" ]
Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests)
1,700,113
<p>I want to do something like:</p> <pre><code>all = [ x for x in t[1] for t in tests ] </code></pre> <p>tests looks like:</p> <pre><code>[ ("foo",[a,b,c]), ("bar",[d,e,f]) ] </code></pre> <p>So I want to have the result</p> <pre><code>all = [a,b,c,d,e,f] </code></pre> <p>My code does not work, Python says:</p> ...
6
2009-11-09T10:04:46Z
1,702,331
<p>If all you are doing is adding together some lists, try the sum builtin, using [] as a starting value:</p> <pre><code>all = sum((t[1] for t in tests), []) </code></pre>
2
2009-11-09T16:57:37Z
[ "python", "list-comprehension" ]
Editing both sides of M2M in Admin Page
1,700,202
<p>First I'll lay out what I'm trying to achieve in case there's a different way to go about it!</p> <p>I want to be able to edit both sides of an M2M relationship (preferably on the admin page although if needs be it could be on a normal page) using any of the multi select interfaces.</p> <p>The problem obviously co...
7
2009-11-09T10:27:46Z
1,700,420
<p>The reason why nothing happens automatically is that the "projects" field is not a part of the Tag model. Which means you have to do all the work yourself. Something like (in TagForm):</p> <pre><code>def __init__(self, *args, **kwargs): super(TagForm, self).__init__(*args, **kwargs) if 'instance' in kwargs:...
2
2009-11-09T11:19:08Z
[ "python", "django", "django-admin", "django-forms", "m2m" ]
IPC between Python and C#
1,700,228
<p>I want to pass data between a Python and a C# application in Windows (I want the channel to be bi-directional) In fact I wanna pass a struct containing data about a network packet that I've captured with C# (SharpPcap) to the Python app and then send back a modified packet to the C# program. What do you propose ? (I...
6
2009-11-09T10:33:08Z
1,700,287
<p>Use JSON-RPC because the experience that you gain will have more practical use. JSON is widely used in web applications written in all of the dozen or so most popular languages.</p>
2
2009-11-09T10:44:21Z
[ "c#", "python", "ipc", "rpc", "bidirectional" ]
IPC between Python and C#
1,700,228
<p>I want to pass data between a Python and a C# application in Windows (I want the channel to be bi-directional) In fact I wanna pass a struct containing data about a network packet that I've captured with C# (SharpPcap) to the Python app and then send back a modified packet to the C# program. What do you propose ? (I...
6
2009-11-09T10:33:08Z
1,700,631
<p>Why not use a simple socket communication, or if you wish you can start a simple http server, and/or do json-rpc over it.</p>
2
2009-11-09T12:13:23Z
[ "c#", "python", "ipc", "rpc", "bidirectional" ]
Any tutorial for Python PalmDB library?
1,700,229
<p>I've downloaded the <a href="http://sourceforge.net/projects/pythonpalmdb/" rel="nofollow">Python PalmDB</a> lib, but can't find any info on how to use it. I've tried reading docstrings and so far I've been able to come up with the following code:</p> <pre><code>from pprint import pprint from PalmDB.PalmDatabase im...
0
2009-11-09T10:33:10Z
2,076,029
<p>There are two problems with the PalmDB module. The first is that it comes with almost no documentation. The other is that in order to do anything useful with the records in the database you need to figure out the binary structure for the particular record type you're dealing with (it's different for each type) and...
2
2010-01-16T02:59:54Z
[ "python", "pdb-palm", "palmdb" ]
How to unquote URL quoted UTF-8 strings in Python
1,700,427
<pre><code>thestring = urllib.quote(thestring.encode('utf-8')) </code></pre> <p>This will encode it. How to decode it?</p>
1
2009-11-09T11:20:38Z
1,700,442
<p>What about</p> <pre><code>backtonormal = urllib.unquote(thestring) </code></pre>
6
2009-11-09T11:24:55Z
[ "python" ]
How to unquote URL quoted UTF-8 strings in Python
1,700,427
<pre><code>thestring = urllib.quote(thestring.encode('utf-8')) </code></pre> <p>This will encode it. How to decode it?</p>
1
2009-11-09T11:20:38Z
1,700,466
<p>if you mean to decode a string from utf-8, you can first transform the string to unicode and then to any other encoding you would like (or leave it in unicode), like this</p> <pre><code>unicodethestring = unicode(thestring, 'utf-8') latin1thestring = unicodethestring.encode('latin-1','ignore') </code></pre> <p>'ig...
2
2009-11-09T11:31:07Z
[ "python" ]
Environment on google Appengine
1,700,441
<p>does someone have an idea how to get the environment variables on Google-AppEngine ? </p> <p>I'm trying to write a simple Script that shall use the Client-IP (for Authentication) and a parameter (geturl or so) from the URL (for e.g. <code>http://thingy.appspot.dom/index?geturl=www.google.at</code>)</p> <p>I red th...
0
2009-11-09T11:24:40Z
1,700,530
<p>Are you using webapp or doing CGI-style? The webapp request class is documented at <a href="http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html" rel="nofollow">the appengine docs</a>.</p>
1
2009-11-09T11:49:00Z
[ "python", "google-app-engine" ]
Environment on google Appengine
1,700,441
<p>does someone have an idea how to get the environment variables on Google-AppEngine ? </p> <p>I'm trying to write a simple Script that shall use the Client-IP (for Authentication) and a parameter (geturl or so) from the URL (for e.g. <code>http://thingy.appspot.dom/index?geturl=www.google.at</code>)</p> <p>I red th...
0
2009-11-09T11:24:40Z
1,700,571
<p>In short, assuming you're using webapp: you can get the client ip address via self.request.remote_addr and the parameter with self.request.get("geturl")</p> <p>See the <a href="http://code.google.com/appengine/docs/python/gettingstarted/handlingforms.html" rel="nofollow">Handling Forms with webapp</a> section of th...
2
2009-11-09T11:59:58Z
[ "python", "google-app-engine" ]
Environment on google Appengine
1,700,441
<p>does someone have an idea how to get the environment variables on Google-AppEngine ? </p> <p>I'm trying to write a simple Script that shall use the Client-IP (for Authentication) and a parameter (geturl or so) from the URL (for e.g. <code>http://thingy.appspot.dom/index?geturl=www.google.at</code>)</p> <p>I red th...
0
2009-11-09T11:24:40Z
1,701,239
<p>To answer the actual question from the title of your post, assuming you're still wondering: to get environment variables, simple <code>import os</code> and the environment is available in <code>os.environ</code>.</p>
3
2009-11-09T14:21:23Z
[ "python", "google-app-engine" ]
How to close not responsive Win32 Internet Explorer COM interface?
1,700,551
<p>actually this is not hang status, i mean..it slow response, <br> so in that case, i would like to close IE and want to restart from start.<br> so closing is no problem ,problem is ,how to set timeout ,for example if i set 15sec,<br> if not webpage open less than 15 sec i want to close it and restart from start.<br>...
0
2009-11-09T11:53:50Z
1,700,604
<p>To avoid blocking problem use IE COM object in a thread.</p> <p>Here is a simple but powerful example demonstrating how can you use thread and IE com object together. You can improve it for your purpose.</p> <p>This example starts a thread a uses a queue to communicate with main thread, in main thread user can add...
0
2009-11-09T12:07:39Z
[ "python", "win32com" ]
Is it possible to redefine reverse in a Django project?
1,700,577
<p>I have some custom logic that needs to be executed every single time a URL is reversed, even for third-party apps. My project is a multitenant web app, and the tenant is identified based on the URL. There isn't a single valid URL that doesn't include a tenant identifier.</p> <p>I already have a wrapper function aro...
3
2009-11-09T12:01:21Z
1,700,673
<p>only way so that django reverse is replaced by ur_reverse is</p> <pre><code>django.core.urlresolvers.reverse = ur_reverse </code></pre> <p>or if you like decorator syntactic sugar</p> <pre><code>django.core.urlresolvers.reverse = ur_reverse_decorator(django.core.urlresolvers.reverse ) </code></pre> <p>which i wo...
5
2009-11-09T12:22:26Z
[ "python", "django", "decorator", "reverse", "monkeypatching" ]
embed python in matlab mex file on os x
1,700,628
<p>I'm trying to embed Python into a MATLAB mex function on OS X. I've seen references that this can be done (eg <a href="http://www.daniweb.com/forums/thread171969.html#" rel="nofollow">here</a>) but I can't find any OS X specific information. So far I can successfully build an embedded Python (so my linker flags must...
3
2009-11-09T12:12:38Z
1,701,078
<p>I think I found the answer - by including the mysterious apple linker flags:</p> <pre><code>-undefined dynamic_lookup -bundle </code></pre> <p>I was able to get it built and it seems to work OK. I'd be very interested if anyone has any references about these flags or library handling on OS X in general. Now I see ...
4
2009-11-09T13:48:29Z
[ "python", "osx", "matlab", "mex", "python-embedding" ]
Start gnome-terminal with multiple virtualenv tabs and services, pre-titled
1,700,995
<p>I'm working on a server-side project that consists of several services. Each service is run in interactive (i.e. non-daemon) mode, this is handy while active development. The project is in virtualenv. So the typical way to start a service is:</p> <pre><code>$ cd ~/to/vitualenv/subdir/where/service/code/located $ so...
0
2009-11-09T13:29:26Z
1,701,224
<p>The following works for me and do what you requested:</p> <p><code>gnome-terminal --working-directory=/path/to/wd --tab-with-profile=profile1 --title=title1 -e 'bash --rcfile /path/to/rcfile1.sh' --tab-with-profile=profile2 --title=title2 -e 'bash --rcfile /path/to/rcfile2.sh'</code></p>
1
2009-11-09T14:17:52Z
[ "python", "terminal", "virtualenv", "gnome-terminal" ]
Start gnome-terminal with multiple virtualenv tabs and services, pre-titled
1,700,995
<p>I'm working on a server-side project that consists of several services. Each service is run in interactive (i.e. non-daemon) mode, this is handy while active development. The project is in virtualenv. So the typical way to start a service is:</p> <pre><code>$ cd ~/to/vitualenv/subdir/where/service/code/located $ so...
0
2009-11-09T13:29:26Z
5,071,841
<p>Create a gnome-terminal profile named "service" (Edit > Profiles > New).</p> <p>In Edit > Profile Preferences > Title and Command > Run a custom command instead of my shell, set the custom command to:</p> <pre><code>bash --rcfile ../path/to/virtualenv/bin/activate </code></pre> <p>Then use gnome-terminal to launc...
0
2011-02-21T22:11:23Z
[ "python", "terminal", "virtualenv", "gnome-terminal" ]
change gtk.Paned handle size
1,701,114
<p>gtk.Paned contains a style property called 'handle-size' which i assume will change the size of the handle, it's read only, so how do i change it?(in PyGtk)</p>
4
2009-11-09T13:56:38Z
1,702,036
<p>From the documentation for <code>gtk.Widget</code>:</p> <blockquote> <p><code>gtk.Widget</code> introduces style properties - these are basically object properties that are stored not on the object, but in the style object associated to the widget. Style properties are set in <a href="http://library.gnome.o...
3
2009-11-09T16:13:52Z
[ "python", "gtk", "pygtk" ]
change gtk.Paned handle size
1,701,114
<p>gtk.Paned contains a style property called 'handle-size' which i assume will change the size of the handle, it's read only, so how do i change it?(in PyGtk)</p>
4
2009-11-09T13:56:38Z
1,710,728
<p>You can feed a custom resource file before starting your own application. In C (hopefully the translation to python is straightforward) that would be:</p> <pre><code>#include &lt;gtk/gtk.h&gt; int main(gint argc, gchar **argv) { GtkWidget *window; GtkPaned *paned; gtk_init(&amp;argc, &amp;argv); ...
2
2009-11-10T19:53:43Z
[ "python", "gtk", "pygtk" ]
Is there an analogue to Java IllegalStateException in Python?
1,701,199
<p>IllegalStateException is often used in Java when a method is invoked on an object in inappropriate state. What would you use instead in Python?</p>
32
2009-11-09T14:12:55Z
1,701,317
<p><a href="http://docs.python.org/library/exceptions.html?highlight=valueerror#exceptions.ValueError">ValueError</a> sounds appropriate to me: </p> <blockquote> <p>Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described...
8
2009-11-09T14:31:27Z
[ "java", "python", "exception" ]
Is there an analogue to Java IllegalStateException in Python?
1,701,199
<p>IllegalStateException is often used in Java when a method is invoked on an object in inappropriate state. What would you use instead in Python?</p>
32
2009-11-09T14:12:55Z
1,701,327
<p>In Python, that would be <code>ValueError</code>, or a subclass of it.</p> <p>For example, trying to <code>.read()</code> a closed file raises "ValueError: I/O operation on closed file".</p>
23
2009-11-09T14:32:15Z
[ "java", "python", "exception" ]
Python: return the index of the first element of a list which makes a passed function true
1,701,211
<p>the <code>list.index(x)</code> function returns the index in the list of the first item whose value is <code>x</code>.</p> <p>is there a function, <code>list_func_index()</code>, similar to the <code>index()</code> function that has a function, <code>f()</code>, as a parameter. the function, <code>f()</code> is run...
22
2009-11-09T14:14:32Z
1,701,229
<p>One possibility is the built-in <a href="http://docs.python.org/tutorial/datastructures.html#looping-techniques">enumerate</a> function:</p> <pre><code>def index_of_first(lst, pred): for i,v in enumerate(lst): if pred(v): return i return None </code></pre> <p>It's typical to refer a fun...
6
2009-11-09T14:19:36Z
[ "python", "list", "function", "indexing" ]
Python: return the index of the first element of a list which makes a passed function true
1,701,211
<p>the <code>list.index(x)</code> function returns the index in the list of the first item whose value is <code>x</code>.</p> <p>is there a function, <code>list_func_index()</code>, similar to the <code>index()</code> function that has a function, <code>f()</code>, as a parameter. the function, <code>f()</code> is run...
22
2009-11-09T14:14:32Z
1,701,242
<p>you could do this with a list-comprehension:</p> <pre><code>l = [8,10,4,5,7] filterl = [a for a in l if a % 2 != 0] </code></pre> <p>Then filterl will return all members of the list fulfilling the expression a % 2 != 0. I would say a more elegant method...</p>
0
2009-11-09T14:21:53Z
[ "python", "list", "function", "indexing" ]
Python: return the index of the first element of a list which makes a passed function true
1,701,211
<p>the <code>list.index(x)</code> function returns the index in the list of the first item whose value is <code>x</code>.</p> <p>is there a function, <code>list_func_index()</code>, similar to the <code>index()</code> function that has a function, <code>f()</code>, as a parameter. the function, <code>f()</code> is run...
22
2009-11-09T14:14:32Z
1,701,259
<p>Not one single function, but you can do it pretty easily:</p> <pre><code>&gt;&gt;&gt; test = lambda c: c == 'x' &gt;&gt;&gt; data = ['a', 'b', 'c', 'x', 'y', 'z', 'x'] &gt;&gt;&gt; map(test, data).index(True) 3 &gt;&gt;&gt; </code></pre> <p>If you don't want to evaluate the entire list at once you can use itertool...
2
2009-11-09T14:23:52Z
[ "python", "list", "function", "indexing" ]
Python: return the index of the first element of a list which makes a passed function true
1,701,211
<p>the <code>list.index(x)</code> function returns the index in the list of the first item whose value is <code>x</code>.</p> <p>is there a function, <code>list_func_index()</code>, similar to the <code>index()</code> function that has a function, <code>f()</code>, as a parameter. the function, <code>f()</code> is run...
22
2009-11-09T14:14:32Z
1,701,404
<p>You could do that in a one-liner using generators:</p> <pre><code>(i for i,v in enumerate(l) if is_odd(v)).next() </code></pre> <p>The nice thing about generators is that they only compute up to the requested amount. So requesting the first two indices is (almost) just as easy:</p> <pre><code>y = (i for i,v in en...
40
2009-11-09T14:39:57Z
[ "python", "list", "function", "indexing" ]
Python: return the index of the first element of a list which makes a passed function true
1,701,211
<p>the <code>list.index(x)</code> function returns the index in the list of the first item whose value is <code>x</code>.</p> <p>is there a function, <code>list_func_index()</code>, similar to the <code>index()</code> function that has a function, <code>f()</code>, as a parameter. the function, <code>f()</code> is run...
22
2009-11-09T14:14:32Z
1,701,922
<p>@Paul's accepted answer is best, but here's a little lateral-thinking variant, mostly for amusement and instruction purposes...:</p> <pre><code>&gt;&gt;&gt; class X(object): ... def __init__(self, pred): self.pred = pred ... def __eq__(self, other): return self.pred(other) ... &gt;&gt;&gt; l = [8,10,4,5,7] &gt...
7
2009-11-09T15:51:44Z
[ "python", "list", "function", "indexing" ]
Python: return the index of the first element of a list which makes a passed function true
1,701,211
<p>the <code>list.index(x)</code> function returns the index in the list of the first item whose value is <code>x</code>.</p> <p>is there a function, <code>list_func_index()</code>, similar to the <code>index()</code> function that has a function, <code>f()</code>, as a parameter. the function, <code>f()</code> is run...
22
2009-11-09T14:14:32Z
11,200,751
<p>A variation on Alex's answer. This avoids having to type <code>X</code> every time you want to use <code>is_odd</code> or whichever predicate</p> <pre><code>&gt;&gt;&gt; class X(object): ... def __init__(self, pred): self.pred = pred ... def __eq__(self, other): return self.pred(other) ... &gt;&gt;&gt; L =...
1
2012-06-26T04:22:33Z
[ "python", "list", "function", "indexing" ]
Pragmatically adding give-aways/freebies to an online store
1,701,956
<p>Our business currently has an online store and recently we've been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the extra free items to their order after they checkout. Of course, it'd be nice to automate this entire process.</p> <...
1
2009-11-09T15:59:13Z
1,702,027
<p>I don't quiet get the question - but if you select DISTINCT (I'm writing "pseudo logic" in SQL) all free items that match the items in the car , and then if you wish to give only one or n of them - SELECT TOP(n) DISTINCT from tblFREE where freebeid in (select freebdid from tbl itemsfreebe where items in (Select Ite...
0
2009-11-09T16:12:17Z
[ "python", "django", "e-commerce", "logic" ]
Pragmatically adding give-aways/freebies to an online store
1,701,956
<p>Our business currently has an online store and recently we've been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the extra free items to their order after they checkout. Of course, it'd be nice to automate this entire process.</p> <...
1
2009-11-09T15:59:13Z
1,702,037
<p>Welcome to hell. Stay a while. ;) <em>Ahem.</em></p> <p>Discounts are a mess, so it's not surprising that you feel tainted by having to work with them. From a design point of view, the testing should be part of the <code>Discount</code> instance, i.e. there should be an <code>appliesTo(cart)</code> method and an <c...
2
2009-11-09T16:13:53Z
[ "python", "django", "e-commerce", "logic" ]
How do I profile `paster serve`'s startup time?
1,702,024
<p>Python's <code>paster serve app.ini</code> is taking longer than I would like to be ready for the first request. </p> <p>I know how to profile requests with middleware, but how do I profile the initialization time? I would like it to not fork a thread pool and quit as soon as it is ready to serve so the time after ...
2
2009-11-09T16:11:39Z
1,702,044
<p>In general your methodology could be to do timing blocks around the sections of code and then issue logging statements. As far as the shutdown after init, I'm not familiar with the specifics of what you're using. </p> <p>Edit: I've used this middleware to help me find performance sinkholes. It's currently a werk...
1
2009-11-09T16:15:03Z
[ "python", "performance", "profiling", "paster" ]
How do I profile `paster serve`'s startup time?
1,702,024
<p>Python's <code>paster serve app.ini</code> is taking longer than I would like to be ready for the first request. </p> <p>I know how to profile requests with middleware, but how do I profile the initialization time? I would like it to not fork a thread pool and quit as soon as it is ready to serve so the time after ...
2
2009-11-09T16:11:39Z
1,703,170
<p>Even if you'd profile it - I doubt you get to much hints to optimize.</p> <p>We use Paster inside a mod_wsgi setup, and to mitigate the startup time so that the user doesn't suffer from it, and make sure that e.g. toscawidgets are set up properly, we do this:</p> <pre><code>app = paste.fixture.TestApp(application)...
1
2009-11-09T19:23:18Z
[ "python", "performance", "profiling", "paster" ]
How do I profile `paster serve`'s startup time?
1,702,024
<p>Python's <code>paster serve app.ini</code> is taking longer than I would like to be ready for the first request. </p> <p>I know how to profile requests with middleware, but how do I profile the initialization time? I would like it to not fork a thread pool and quit as soon as it is ready to serve so the time after ...
2
2009-11-09T16:11:39Z
1,710,186
<p>I almost always use <code>paster serve --reload ...</code> during development. That command executes itself as a subprocess (it executes its own script using the <code>subprocess</code> module, not <code>fork()</code>).</p> <p>The subprocess polls for source code changes, quits when it detects a change, and gets re...
1
2009-11-10T18:35:08Z
[ "python", "performance", "profiling", "paster" ]
How can I make the PyDev editor selectively ignore errors?
1,702,043
<p>I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this:</p> <pre><code>import com.work.project.component.client.Interface.ISubInterface as ISubInterface </code></pre> <p>The problem is that PyDev will always flag this as an error and say "Unreso...
27
2009-11-09T16:14:56Z
1,703,140
<p>You can add a comment</p> <pre><code>#@UnresolvedImport #@UnusedVariable </code></pre> <p>So your import becomes:</p> <pre><code>import com.work.project.component.client.Interface.ISubInterface as ISubInterface #@UnresolvedImport </code></pre> <p>That should remove the error/warning. There are other comments you...
45
2009-11-09T19:18:33Z
[ "python", "pydev", "jython", "python-import" ]
How can I make the PyDev editor selectively ignore errors?
1,702,043
<p>I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this:</p> <pre><code>import com.work.project.component.client.Interface.ISubInterface as ISubInterface </code></pre> <p>The problem is that PyDev will always flag this as an error and say "Unreso...
27
2009-11-09T16:14:56Z
1,704,887
<p>Add the hash character # at the end of the line then with the cursor on the flagged error, press Ctrl-1. One of the options in the menu will be something like <code>@UndefinedVariable</code>. Adding this comment will cause PyDev to ignore the error.</p>
26
2009-11-10T00:25:09Z
[ "python", "pydev", "jython", "python-import" ]
How can I make the PyDev editor selectively ignore errors?
1,702,043
<p>I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this:</p> <pre><code>import com.work.project.component.client.Interface.ISubInterface as ISubInterface </code></pre> <p>The problem is that PyDev will always flag this as an error and say "Unreso...
27
2009-11-09T16:14:56Z
2,017,023
<p>You can make the ignore like the other posts suggest, but the real problem is that Pydev cannot find that class... If you add a .jar that contains that class to your PYTHONPATH it should be able to resolve it (or if you have a Java project that has that class, you should be able to mark that project as a Pydev proje...
6
2010-01-06T23:03:59Z
[ "python", "pydev", "jython", "python-import" ]
How can I make the PyDev editor selectively ignore errors?
1,702,043
<p>I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this:</p> <pre><code>import com.work.project.component.client.Interface.ISubInterface as ISubInterface </code></pre> <p>The problem is that PyDev will always flag this as an error and say "Unreso...
27
2009-11-09T16:14:56Z
2,815,019
<p>It is not a PYTHONPATH issue. It is related to importing/using static class-internal members of a Java class. I am getting the same sort of thing all over the place e.g. when trying to use constants in java.awt.Color:</p> <pre><code>import java.awt.Color as Color borderColor = Color.BLACK # get "Undefined variabl...
-1
2010-05-11T22:58:21Z
[ "python", "pydev", "jython", "python-import" ]
Something disturbing about PyDev content assist
1,702,255
<p>I created a simple class in Python as follows, </p> <pre><code>from UserDict import UserDict class Person(UserDict): def __init__(self,personName=None): UserDict.__init__(self) self["name"]=personName </code></pre> <p>In another module I try to instantiate an object of class Person and print its <strong>d...
0
2009-11-09T16:45:10Z
1,702,526
<p>Not sure if anyone outside of the PyDev development team can really help you here, as this basically boils down to a feature question/request.</p> <p>I'd suggest creating an item on their <a href="http://sourceforge.net/tracker/?group%5Fid=85796&amp;atid=577332" rel="nofollow">Feature Request tracker</a> or their <...
2
2009-11-09T17:31:17Z
[ "python", "eclipse", "pydev" ]
Something disturbing about PyDev content assist
1,702,255
<p>I created a simple class in Python as follows, </p> <pre><code>from UserDict import UserDict class Person(UserDict): def __init__(self,personName=None): UserDict.__init__(self) self["name"]=personName </code></pre> <p>In another module I try to instantiate an object of class Person and print its <strong>d...
0
2009-11-09T16:45:10Z
1,703,086
<p>EDIT:</p> <p>Your class Person is a so-called old-style class because it is subclassed from the <code>UserDict</code> class, an old-style class. There are fundamental differences between old-style and new-style (i.e. classes that subclass from <code>object</code>) in the availability and treatment of special attri...
1
2009-11-09T19:10:50Z
[ "python", "eclipse", "pydev" ]
Speeding Up the First Page Load in django
1,702,562
<p>When I update the code on my website I (naturally) restart my apache instance so that the changes will take effect.</p> <p>Unfortunately the first page served by each apache instance is quite slow while it loads everything into RAM for the first time (5-7 sec for this particular site).</p> <p>Subsequent requests o...
22
2009-11-09T17:38:17Z
1,702,626
<p>How are you running Django (mod_python vs mod_wsgi)? </p> <p>If you're running mod_wsgi (in daemon mode), restarting Apache isn't necessary to reload your application. All you need to do is update the mtime of your wsgi script (which is done easily with <code>touch</code>). </p> <p>mod_wsgi's documentation has a...
3
2009-11-09T17:47:43Z
[ "python", "django", "performance", "mod-wsgi", "pageload" ]
Speeding Up the First Page Load in django
1,702,562
<p>When I update the code on my website I (naturally) restart my apache instance so that the changes will take effect.</p> <p>Unfortunately the first page served by each apache instance is quite slow while it loads everything into RAM for the first time (5-7 sec for this particular site).</p> <p>Subsequent requests o...
22
2009-11-09T17:38:17Z
1,704,310
<p>The default for Apache/mod_wsgi is to only load application code on first request to a process which requires that applications. So, first step is to configure mod_wsgi to preload your code when the process starts and not only the first request. This can be done in mod_wsgi 2.X using the WSGIImportScript directive.<...
30
2009-11-09T22:18:59Z
[ "python", "django", "performance", "mod-wsgi", "pageload" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
1,702,605
<p><em>I would go for option three.</em></p> <ul> <li><p><strong>First option:</strong> (Not safe)</p> <blockquote> <p>The code opens “HKEY_CURRENT_USER\Software\Python\PythonCore”, if the key exists it will get the path from the first child key of this key.</p> </blockquote> <p>Check if this key exists, and i...
76
2009-11-09T17:44:25Z
[ "python", "notepad++" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
10,335,994
<p>I use the NPP_Exec plugin (Found in the plugins manager). Once that is installed, open the console window (ctrl+~) and type:</p> <pre><code>cmd </code></pre> <p>This will launch command prompt. Then type:</p> <pre><code>C:\Program Files\Notepad++&gt; **python "$(FULL_CURRENT_PATH)"** </code></pre> <p>to execute ...
5
2012-04-26T14:54:49Z
[ "python", "notepad++" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
21,991,705
<p>@<a href="http://stackoverflow.com/questions/1702586/how-to-execute-a-python-file-in-notepad#comment1908592_1702605">Ramiz Uddin's answer</a> definitely deserves more visibility : </p> <ul> <li>Open Notepad++.</li> <li>On the menu go to: Run -> Run.. (F5).</li> <li>Type in: <code>cmd /K python "$(FULL_CURRENT_PATH)...
20
2014-02-24T15:18:39Z
[ "python", "notepad++" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
23,391,084
<p>None of the previously proposed solutions worked for me. Slight modification needed.</p> <p>After hitting F5 in Notepad++, type:</p> <pre><code>cmd /k "C:\Python27\python.exe $(FULL_CURRENT_PATH)" </code></pre> <p>The command prompt stays open so you can see the output of your script.</p>
2
2014-04-30T14:38:34Z
[ "python", "notepad++" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
24,143,304
<p>I wish people here would post steps instead of just overall concepts. I eventually got the cmd /k version to work.</p> <p>The step-by-step instructions are:</p> <ol> <li>In NPP, click on the menu item: Run</li> <li>In the submenu, click on: Run</li> <li>In the Run... dialog box, in the field The Program to Run, de...
3
2014-06-10T14:14:02Z
[ "python", "notepad++" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
26,572,928
<p>Got it to work by just. Using the name "python" and not the full directory. Now I can read The 'Stack traces' and errors in my program</p> <p>This Works Perfect: Cmd /k python "$(FULL_CURRENT_PATH)"</p> <p>-python is already in my path -so no need to use the full path("c:/python27/python.exe") Although this will w...
-1
2014-10-26T12:21:12Z
[ "python", "notepad++" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
27,038,786
<p>Here is what's worked for me:</p> <p>Open notepad++ and press F5.</p> <blockquote> <p>Type: <strong><em>C:\Python27\python.exe -i "$(FULL_CURRENT_PATH)"</em></strong> for Python 2.7.</p> <p>and then <strong><em>Save As...</em></strong>, and pick your own key combo to start it each time you want to run somet...
8
2014-11-20T11:44:19Z
[ "python", "notepad++" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
28,825,139
<p>I started using Notepad++ for Python very recently and I found this method very easy. Once you are ready to run the code,right-click on the tab of your code in Notepad++ window and select "Open Containing Folder in cmd". This will open the Command Prompt into the folder where the current program is stored. All you n...
0
2015-03-03T06:03:33Z
[ "python", "notepad++" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
30,627,460
<p>In Notepad++, go to RUN, select path and idle.py file of you python instalation:</p> <p>C:\Python27\Lib\idlelib\idle.py</p> <p>add a space and this:</p> <p>"$(FULL_CURRENT_PATH)"</p> <p>and here you are!</p> <p>Video demostration:</p> <p><a href="https://www.youtube.com/watch?v=sJipYE1JT38" rel="nofollow">http...
0
2015-06-03T18:02:10Z
[ "python", "notepad++" ]
How to Execute a Python File in Notepad ++?
1,702,586
<p>I prefer using Notepad ++ for developing,</p> <p>How do I execute the files in Python through Notepad++?</p>
60
2009-11-09T17:41:54Z
37,897,821
<p>First <strong>install Pyton from</strong> <a href="https://www.python.org/downloads/release/python-351/" rel="nofollow">https://www.python.org/downloads/release/python-351/</a></p> <p>Scroll down and chose <strong>Windows x86 executable installer</strong> and run it</p> <p>Be sure you check both :</p> <ul> <li>In...
3
2016-06-18T14:03:05Z
[ "python", "notepad++" ]
What is suggested seed value to use with random.seed()?
1,703,012
<p>Simple enough question:</p> <p>I'm using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this default to the current time, but this is not ideal. It seems like a string literal constant (similar to a passw...
4
2009-11-09T18:56:16Z
1,703,021
<p>According to the documentation for <a href="http://docs.python.org/library/random.html"><code>random.seed</code></a>:</p> <blockquote> <p>If x is omitted or <strong>None</strong>, current system time is used; current system time is also used to initialize the generator when the module is first imported. If random...
12
2009-11-09T18:58:11Z
[ "python", "random" ]
What is suggested seed value to use with random.seed()?
1,703,012
<p>Simple enough question:</p> <p>I'm using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this default to the current time, but this is not ideal. It seems like a string literal constant (similar to a passw...
4
2009-11-09T18:56:16Z
1,703,027
<p>For most cases using current time is good enough. Occasionally you need to use a fixed number to generate pseudo random numbers for comparison purposes.</p>
3
2009-11-09T18:59:18Z
[ "python", "random" ]
What is suggested seed value to use with random.seed()?
1,703,012
<p>Simple enough question:</p> <p>I'm using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this default to the current time, but this is not ideal. It seems like a string literal constant (similar to a passw...
4
2009-11-09T18:56:16Z
1,703,231
<p>If you are using random for generating test data I would like to suggest that reproducibility can be important.</p> <p>Just think to an use case: for data set X you get some weird behaviour (eg crash). Turns out that data set X shows some feature that was not so apparent from the other data sets Y and Z and uncover...
0
2009-11-09T19:34:42Z
[ "python", "random" ]
What is suggested seed value to use with random.seed()?
1,703,012
<p>Simple enough question:</p> <p>I'm using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this default to the current time, but this is not ideal. It seems like a string literal constant (similar to a passw...
4
2009-11-09T18:56:16Z
1,703,241
<p>Setting the seed is for repeatability, not security. If anything, you make the system <em>less</em> secure by having a fixed seed than one that is constantly changing.</p>
2
2009-11-09T19:36:50Z
[ "python", "random" ]
What is suggested seed value to use with random.seed()?
1,703,012
<p>Simple enough question:</p> <p>I'm using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this default to the current time, but this is not ideal. It seems like a string literal constant (similar to a passw...
4
2009-11-09T18:56:16Z
1,703,327
<p>Perhaps it is not a problem in your case, but ont problem with using the system time as the seed is that someone who knows roughly when your system was started may be able to guess your seed (by trial) after seeing a few numbers from the sequence.<br> eg, <strong>don't use system time as the seed for your online pok...
1
2009-11-09T19:53:23Z
[ "python", "random" ]
How can I make WSGI(Python) stateful?
1,703,440
<p>I'm quite new in Python world. I come from java and ABAP world, where their application server are able to handle stateful request. </p> <p>Is it also possible in python using WSGI?</p> <p>Or stateful and stateless are handled in other layer?</p>
1
2009-11-09T20:11:38Z
1,703,470
<p>Usually, you don't work with "bare" WSGI. You work with web-frameworks, such as Pylons or TurboGears2.</p> <p>And these contain a session-middleware, based on WSGI - called "Beaker". But if you work with the framework, you don't have to worry about that - you just use it.</p> <p>But if you insist, you can of cours...
5
2009-11-09T20:15:57Z
[ "python", "wsgi" ]
How can I make WSGI(Python) stateful?
1,703,440
<p>I'm quite new in Python world. I come from java and ABAP world, where their application server are able to handle stateful request. </p> <p>Is it also possible in python using WSGI?</p> <p>Or stateful and stateless are handled in other layer?</p>
1
2009-11-09T20:11:38Z
1,703,477
<p>Your question is a little vague and open-ended. First of all, WSGI itself isn't a framework, it's just the glue to connect a framework to the web server. Secondly, I'm not clear on what you mean when you say "state" -- do you mean storing information about a client on the server? If so, web frameworks (Pylons, Djang...
1
2009-11-09T20:17:01Z
[ "python", "wsgi" ]
How can I make WSGI(Python) stateful?
1,703,440
<p>I'm quite new in Python world. I come from java and ABAP world, where their application server are able to handle stateful request. </p> <p>Is it also possible in python using WSGI?</p> <p>Or stateful and stateless are handled in other layer?</p>
1
2009-11-09T20:11:38Z
1,718,144
<p>I prefer working directly on wsgi, along with mako and psycopg.<br> It's good to know about Beaker, though I usually don't hold state in the server because I believe it reduces scalability. I either put it in the user's cookie, in the database tied to a token in the user's cookie, or in a redirect url.</p>
2
2009-11-11T21:18:24Z
[ "python", "wsgi" ]
Basic Python loop question - problem reading a list from a text file
1,703,471
<p>I'm trying to read a list of items from a text file and format with square brackets and separators like this: ['item1','item2', .... 'last_item'] but I'm having trouble with the beginning and end item for which I always get: ...,'last_item','], so I do not want the last ,' to be there.</p> <p>In python I've write...
0
2009-11-09T20:16:20Z
1,703,486
<p>You "right strip" for "," the result before adding the last "]".</p> <p>e.g. use the <code>string.rstrip(",")</code></p>
0
2009-11-09T20:19:10Z
[ "python", "loops" ]
Basic Python loop question - problem reading a list from a text file
1,703,471
<p>I'm trying to read a list of items from a text file and format with square brackets and separators like this: ['item1','item2', .... 'last_item'] but I'm having trouble with the beginning and end item for which I always get: ...,'last_item','], so I do not want the last ,' to be there.</p> <p>In python I've write...
0
2009-11-09T20:16:20Z
1,703,496
<p>Read in all your lines and use the <code>string.join()</code> method to join them together.</p> <pre><code>lines = open(file_in).readlines() out_list = "['" + "','".join(lines) + "']" </code></pre> <p>Additionally, <code>join()</code> can take any sequence, so reading the lines isn't necessary. The above code ca...
4
2009-11-09T20:20:37Z
[ "python", "loops" ]
Basic Python loop question - problem reading a list from a text file
1,703,471
<p>I'm trying to read a list of items from a text file and format with square brackets and separators like this: ['item1','item2', .... 'last_item'] but I'm having trouble with the beginning and end item for which I always get: ...,'last_item','], so I do not want the last ,' to be there.</p> <p>In python I've write...
0
2009-11-09T20:16:20Z
1,703,497
<pre><code>out_list = [] for line in open(file_in): out_list.append("'" + line + "'") return "[" + ",".join(out_list) + "]" </code></pre>
1
2009-11-09T20:21:01Z
[ "python", "loops" ]
Basic Python loop question - problem reading a list from a text file
1,703,471
<p>I'm trying to read a list of items from a text file and format with square brackets and separators like this: ['item1','item2', .... 'last_item'] but I'm having trouble with the beginning and end item for which I always get: ...,'last_item','], so I do not want the last ,' to be there.</p> <p>In python I've write...
0
2009-11-09T20:16:20Z
1,703,507
<p>Or</p> <pre><code>result = "['" for line in open(file_in): if len(result) &gt; 0: result += "','" result += line result += "']" return result </code></pre>
0
2009-11-09T20:22:08Z
[ "python", "loops" ]
Basic Python loop question - problem reading a list from a text file
1,703,471
<p>I'm trying to read a list of items from a text file and format with square brackets and separators like this: ['item1','item2', .... 'last_item'] but I'm having trouble with the beginning and end item for which I always get: ...,'last_item','], so I do not want the last ,' to be there.</p> <p>In python I've write...
0
2009-11-09T20:16:20Z
1,703,510
<p>Your desired output format is exactly Python's standard printable representation of a list. So an easy solution is to read the file, create a list with each line as a string element (stripping the end-of-line of each), and call the Python built-in function <a href="http://docs.python.org/library/functions.html#repr...
0
2009-11-09T20:22:33Z
[ "python", "loops" ]