title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
What does this function do?
1,577,031
<pre><code>def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a </code></pre>
-4
2009-10-16T09:16:10Z
1,577,040
<p>it multiplies each element of the array "a" with itself and stores the results back in the array.</p>
2
2009-10-16T09:18:48Z
[ "python" ]
What does this function do?
1,577,031
<pre><code>def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a </code></pre>
-4
2009-10-16T09:16:10Z
1,577,044
<p>a is passed as a list , I assume.</p> <p>It squares each element of the list and returns the list.</p>
2
2009-10-16T09:19:07Z
[ "python" ]
What does this function do?
1,577,031
<pre><code>def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a </code></pre>
-4
2009-10-16T09:16:10Z
1,577,045
<p>It will go through your List and multiply each value by itself.</p> <p><strong>Example</strong></p> <pre><code>a = [ 1, 2, 3, 4, 5, 6 ] </code></pre> <p>After that function a would look like this:</p> <pre><code>a = [ 1, 4, 9, 16, 25, 36 ] </code></pre>
3
2009-10-16T09:19:19Z
[ "python" ]
What does this function do?
1,577,031
<pre><code>def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a </code></pre>
-4
2009-10-16T09:16:10Z
1,577,051
<p>It <em>squares</em> every element in the input array and returns the squared array.</p> <p>So with <code>a = [1,2,3,4,5]</code></p> <p>result is: <code>[1,4,9,16,25]</code></p>
1
2009-10-16T09:21:10Z
[ "python" ]
What does this function do?
1,577,031
<pre><code>def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a </code></pre>
-4
2009-10-16T09:16:10Z
1,577,056
<p>It's a trivial function that could be replaced with the one-liner:</p> <pre><code>a = [x*x for x in a] </code></pre>
3
2009-10-16T09:22:42Z
[ "python" ]
Lossless PDF rotation
1,577,168
<p><br /> is there a way to rotate a PDF 90 degrees <strong>losslessly</strong>, with Python or using the command line?</p> <p>I'm looking for a REAL rotation, not just adding a "/ROTATE 90" inside the PDF, because afterwards I have to send the PDF via Hylafax and it looks like that it ignores those commands.</p> <p>I tried with ImageMagick's <em>convert</em> but the quality of the resulting PDF is quite low.</p> <p>(Python 2.6.2, Xubuntu 9.04)</p> <p>Thanks for your attention!</p>
2
2009-10-16T09:51:31Z
1,577,268
<p>The best resolution you will normally obtain from a standard fax machine is about 200dpi; standard faxes are about 100dpi. If you need your faxed documents to work with an artitrary fax machine you can't go above this.</p> <p>Ergo, rendering your PDF to a 100 or 200dpi bitmap and rotating it 90 degress should work as well as anything. Various ghostscript based tool chains can do the rendering. Alternatively, there are a number of PDF and postscript based tools that can do this type of manipulatiion (e.g. <a href="http://orion.math.iastate.edu/burkardt/g%5Fsrc/pdf2ps/pdf2ps.html" rel="nofollow">PDF2PS</a> and <a href="http://www.tardis.ed.ac.uk/~ajcd/psutils/" rel="nofollow">psutils</a>) directly off the PDF.</p>
3
2009-10-16T10:18:59Z
[ "python", "pdf", "ubuntu", "rotation", "lossless" ]
Lossless PDF rotation
1,577,168
<p><br /> is there a way to rotate a PDF 90 degrees <strong>losslessly</strong>, with Python or using the command line?</p> <p>I'm looking for a REAL rotation, not just adding a "/ROTATE 90" inside the PDF, because afterwards I have to send the PDF via Hylafax and it looks like that it ignores those commands.</p> <p>I tried with ImageMagick's <em>convert</em> but the quality of the resulting PDF is quite low.</p> <p>(Python 2.6.2, Xubuntu 9.04)</p> <p>Thanks for your attention!</p>
2
2009-10-16T09:51:31Z
1,577,370
<p>In the <a href="http://packages.ubuntu.com/search?keywords=pdfjam" rel="nofollow">pdfjam package</a> there is a shell script <code>pdf90</code> which does the rotation via pdflatex.</p>
3
2009-10-16T10:43:38Z
[ "python", "pdf", "ubuntu", "rotation", "lossless" ]
Python GUI Library for Windows/Gnome
1,577,175
<p>I need to create a desktop app that will work with Windows and Gnome(Ubuntu). I would like to use Python to do this. The GUI part of the app will be a single form with a message area and a couple of buttons.</p> <p>The list of GUI's for Python seems overwhelming. I am looking for something simple if possible, the main requirements is it must work with Gnome(2.26 and up) and Windows XP/Vista/7.</p>
4
2009-10-16T09:53:16Z
1,577,187
<p>Have you checked the <a href="http://wiki.python.org/moin/GuiProgramming" rel="nofollow">extensive list of GUI libs</a> for Python? For something simple I recommend, as does the list, <a href="http://easygui.sourceforge.net/" rel="nofollow">EasyGUI</a>.</p>
2
2009-10-16T09:57:06Z
[ "python", "user-interface", "cross-platform" ]
Python GUI Library for Windows/Gnome
1,577,175
<p>I need to create a desktop app that will work with Windows and Gnome(Ubuntu). I would like to use Python to do this. The GUI part of the app will be a single form with a message area and a couple of buttons.</p> <p>The list of GUI's for Python seems overwhelming. I am looking for something simple if possible, the main requirements is it must work with Gnome(2.26 and up) and Windows XP/Vista/7.</p>
4
2009-10-16T09:53:16Z
1,577,197
<p>You might want to check out wxPython. It's a mature project and should work on Windows and Linux (Gnome).</p>
4
2009-10-16T09:58:53Z
[ "python", "user-interface", "cross-platform" ]
Python GUI Library for Windows/Gnome
1,577,175
<p>I need to create a desktop app that will work with Windows and Gnome(Ubuntu). I would like to use Python to do this. The GUI part of the app will be a single form with a message area and a couple of buttons.</p> <p>The list of GUI's for Python seems overwhelming. I am looking for something simple if possible, the main requirements is it must work with Gnome(2.26 and up) and Windows XP/Vista/7.</p>
4
2009-10-16T09:53:16Z
1,577,319
<p><a href="http://www.pygtk.org/" rel="nofollow">PyGTK</a> is a very popular GUI toolkit, but usually quite a bit easier to use on Linux than on Windows.</p>
3
2009-10-16T10:30:36Z
[ "python", "user-interface", "cross-platform" ]
Python GUI Library for Windows/Gnome
1,577,175
<p>I need to create a desktop app that will work with Windows and Gnome(Ubuntu). I would like to use Python to do this. The GUI part of the app will be a single form with a message area and a couple of buttons.</p> <p>The list of GUI's for Python seems overwhelming. I am looking for something simple if possible, the main requirements is it must work with Gnome(2.26 and up) and Windows XP/Vista/7.</p>
4
2009-10-16T09:53:16Z
1,578,854
<p>You can also try <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt</a> or <a href="http://www.pyside.org" rel="nofollow">PySide</a>. Both are Python wrappers to Qt. PyQt is the original wrapper; PySide is a new project by <a href="http://qt.nokia.com" rel="nofollow">Qt Development Frameworks</a>/Nokia that has pretty much the same aims as PyQt, just with different licensing. PyQt is more mature, but licensing is more restrictive; PySide is quite new (in alpha/beta) but with more liberal licensing. However, for real information on licensing, check their site and preferably with a lawyer if it concerns you.</p>
2
2009-10-16T15:37:40Z
[ "python", "user-interface", "cross-platform" ]
How to get path of an element in lxml?
1,577,293
<p>I'm searching in a HTML document using XPath from lxml in python. How can I get the path to a certain element? Here's the example from ruby nokogiri:</p> <pre><code>page.xpath('//text()').each do |textnode| path = textnode.path puts path end </code></pre> <p>print for example '<strong>/html/body/div/div[1]/div[1]/p/text()[1]</strong>' and this is the string I want to get in python.</p>
15
2009-10-16T10:24:06Z
1,577,495
<p>Use <a href="http://codespeak.net/lxml/api/lxml.etree.%5FElementTree-class.html#getpath"><code>getpath</code></a> from ElementTree objects.</p> <pre><code>from lxml import etree root = etree.fromstring('&lt;foo&gt;&lt;bar&gt;Data&lt;/bar&gt;&lt;bar&gt;&lt;baz&gt;data&lt;/baz&gt;' '&lt;baz&gt;data&lt;/baz&gt;&lt;/bar&gt;&lt;/foo&gt;') tree = etree.ElementTree(root) for e in root.iter(): print tree.getpath(e) </code></pre> <p>Prints</p> <pre><code>/foo /foo/bar[1] /foo/bar[2] /foo/bar[2]/baz[1] /foo/bar[2]/baz[2] </code></pre>
30
2009-10-16T11:23:32Z
[ "python", "xpath", "lxml" ]
How to get path of an element in lxml?
1,577,293
<p>I'm searching in a HTML document using XPath from lxml in python. How can I get the path to a certain element? Here's the example from ruby nokogiri:</p> <pre><code>page.xpath('//text()').each do |textnode| path = textnode.path puts path end </code></pre> <p>print for example '<strong>/html/body/div/div[1]/div[1]/p/text()[1]</strong>' and this is the string I want to get in python.</p>
15
2009-10-16T10:24:06Z
1,577,498
<p>See the <a href="http://lxml.de/xpathxslt.html" rel="nofollow">Xpath and XSLT with lxml from the lxml documentation</a> This gives the path of the element containg the text</p> <p>An example would be</p> <pre><code>import cStringIO from lxml import etree f = cStringIO.StringIO('&lt;foo&gt;&lt;bar&gt;&lt;x1&gt;hello&lt;/x1&gt;&lt;x1&gt;world&lt;/x1&gt;&lt;/bar&gt;&lt;/foo&gt;') tree = lxml.etree.parse(f) find_text = etree.XPath("//text()") # and print out the required data print [tree.getpath( text.getparent()) for text in find_text(tree)] # answer I get is &gt;&gt;&gt; ['/foo/bar/x1[1]', '/foo/bar/x1[2]'] </code></pre>
16
2009-10-16T11:24:53Z
[ "python", "xpath", "lxml" ]
How to get path of an element in lxml?
1,577,293
<p>I'm searching in a HTML document using XPath from lxml in python. How can I get the path to a certain element? Here's the example from ruby nokogiri:</p> <pre><code>page.xpath('//text()').each do |textnode| path = textnode.path puts path end </code></pre> <p>print for example '<strong>/html/body/div/div[1]/div[1]/p/text()[1]</strong>' and this is the string I want to get in python.</p>
15
2009-10-16T10:24:06Z
12,964,427
<pre><code>root = etree.parse(open('tmp.txt')) for e in root.iter(): print root.getpath(e) </code></pre>
3
2012-10-18T21:59:15Z
[ "python", "xpath", "lxml" ]
How to get path of an element in lxml?
1,577,293
<p>I'm searching in a HTML document using XPath from lxml in python. How can I get the path to a certain element? Here's the example from ruby nokogiri:</p> <pre><code>page.xpath('//text()').each do |textnode| path = textnode.path puts path end </code></pre> <p>print for example '<strong>/html/body/div/div[1]/div[1]/p/text()[1]</strong>' and this is the string I want to get in python.</p>
15
2009-10-16T10:24:06Z
39,538,304
<p>If all you have in your section of code is the element and you want the element's xpath do then <code>element.getroottree().getpath(element)</code> will do the job.</p> <pre><code>from lxml import etree xml = ''' &lt;test&gt; &lt;a/&gt; &lt;b&gt; &lt;i/&gt; &lt;ii/&gt; &lt;/b&gt; &lt;/test&gt; ''' tree = etree.fromstring(xml) for element in tree.iter(): print element.getroottree().getpath(element) </code></pre>
0
2016-09-16T18:48:18Z
[ "python", "xpath", "lxml" ]
python, lxml and xpath - html table parsing
1,577,487
<p>I 'am new to lxml, quite new to python and could not find a solution to the following:</p> <p>I need to import a few tables with 3 columns and an undefined number of rows starting at row 3.</p> <p>When the second column of any row is empty, this row is discarded and the processing of the table is aborted.</p> <p>The following code prints the table's data fine (but I'm unable to reuse the data afterwards): </p> <pre><code>from lxml.html import parse def process_row(row): for cell in row.xpath('./td'): print cell.text_content() yield cell.text_content() def process_table(table): return [process_row(row) for row in table.xpath('./tr')] doc = parse(url).getroot() tbl = doc.xpath("/html//table[2]")[0] data = process_table(tbl) </code></pre> <p>This only prints the first column :( </p> <pre><code>for i in data: print i.next() </code></pre> <p>The following only import the third row, and not the subsequent </p> <pre><code>tbl = doc.xpath("//body/table[2]//tr[position()&gt;2]")[0] </code></pre> <p>Anyone knows a fancy solution to get all the data from row 3 into tbl and copy it into an array so it can be processed into a module with no lxml dependency?</p> <p>Thanks in advance for your help, Alex</p>
5
2009-10-16T11:21:50Z
1,577,771
<p>You need to use a loop to access the row's data, like this:</p> <pre><code>for row in data: for col in row: print col </code></pre> <p>Calling next() once as you did will access only the first item, which is why you see one column.</p> <p>Note that due to the nature of generators, you can only access them once. If you changed the call <code>process_row(row)</code> into <code>list(process_row(row))</code>, the generator would be converted to a list which can be reused.</p> <p>Update: If you need just the 3rd row and on, use <code>data[2:]</code></p>
0
2009-10-16T12:29:58Z
[ "python", "xpath", "lxml" ]
python, lxml and xpath - html table parsing
1,577,487
<p>I 'am new to lxml, quite new to python and could not find a solution to the following:</p> <p>I need to import a few tables with 3 columns and an undefined number of rows starting at row 3.</p> <p>When the second column of any row is empty, this row is discarded and the processing of the table is aborted.</p> <p>The following code prints the table's data fine (but I'm unable to reuse the data afterwards): </p> <pre><code>from lxml.html import parse def process_row(row): for cell in row.xpath('./td'): print cell.text_content() yield cell.text_content() def process_table(table): return [process_row(row) for row in table.xpath('./tr')] doc = parse(url).getroot() tbl = doc.xpath("/html//table[2]")[0] data = process_table(tbl) </code></pre> <p>This only prints the first column :( </p> <pre><code>for i in data: print i.next() </code></pre> <p>The following only import the third row, and not the subsequent </p> <pre><code>tbl = doc.xpath("//body/table[2]//tr[position()&gt;2]")[0] </code></pre> <p>Anyone knows a fancy solution to get all the data from row 3 into tbl and copy it into an array so it can be processed into a module with no lxml dependency?</p> <p>Thanks in advance for your help, Alex</p>
5
2009-10-16T11:21:50Z
1,580,418
<p>This is a generator:</p> <pre><code>def process_row(row): for cell in row.xpath('./td'): print cell.text_content() yield cell.text_content() </code></pre> <p>You're calling it as though you thought it returns a list. It doesn't. There are contexts in which it <em>behaves</em> like a list:</p> <pre><code>print [r for r in process_row(row)] </code></pre> <p>but that's only because a generator and a list both expose the same interface to <code>for</code> loops. Using it in a context where it gets evaluated just one time, e.g.:</p> <pre><code>return [process_row(row) for row in table.xpath('./tr')] </code></pre> <p>just calls a new instance of the generator once for each new value of <code>row</code>, returning the first result yielded.</p> <p>So that's your first problem. Your second one is that you're expecting:</p> <pre><code>tbl = doc.xpath("//body/table[2]//tr[position()&gt;2]")[0] </code></pre> <p>to give you the third and all subsequent rows, and it's only setting <code>tbl</code> to the third row. Well, the call to <code>xpath</code> <em>is</em> returning the third and all subsequent rows. It's the <code>[0]</code> at the end that's messing you up.</p>
2
2009-10-16T21:04:38Z
[ "python", "xpath", "lxml" ]
How can I get all days between two days?
1,577,538
<p>I need all the weekdays between two days.</p> <p>Example:</p> <pre> Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 </pre> <p>I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an <code>if</code> statement.</p> <p>There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too.</p> <p>The best I could come up with:</p> <pre><code>def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 &gt; d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2] </code></pre>
3
2009-10-16T11:33:53Z
1,577,588
<p>How about (in pseudo code):</p> <pre><code>weekday[] = {"Mon" .. "Sun"} for(i = wkday_start; (i % 7) != wkday_end; i = (i+1) % 7) printf("%s ", weekday[i]); </code></pre> <p>It works like a circular buffer, wkday_start being the index to start at (0-based), wkday_end being the end index.</p> <p>Hope this helps</p> <p>George.</p>
9
2009-10-16T11:45:27Z
[ "python", "algorithm" ]
How can I get all days between two days?
1,577,538
<p>I need all the weekdays between two days.</p> <p>Example:</p> <pre> Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 </pre> <p>I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an <code>if</code> statement.</p> <p>There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too.</p> <p>The best I could come up with:</p> <pre><code>def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 &gt; d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2] </code></pre>
3
2009-10-16T11:33:53Z
1,577,614
<p>You asked for an algorithm, and I understand that should be language independent; however, following code works using C# and LINQ expressions:</p> <pre><code>DayOfWeek start = DayOfWeek.Wednesday; DayOfWeek end = DayOfWeek.Friday; IEnumerable&lt;DayOfWeek&gt; interval = Enum.GetValues(typeof(DayOfWeek)).OfType&lt;DayOfWeek&gt;() .Where(d =&gt; d &gt;= start &amp;&amp; d &lt;= end); Console.WriteLine( String.Join(", ", interval.Select(d =&gt; d.ToString()).ToArray())); </code></pre> <p>Probably, using any language, your should attribute values to each day (<code>Sunday=0</code> and so on) and look for all values which matches your desired interval.</p>
0
2009-10-16T11:49:41Z
[ "python", "algorithm" ]
How can I get all days between two days?
1,577,538
<p>I need all the weekdays between two days.</p> <p>Example:</p> <pre> Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 </pre> <p>I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an <code>if</code> statement.</p> <p>There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too.</p> <p>The best I could come up with:</p> <pre><code>def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 &gt; d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2] </code></pre>
3
2009-10-16T11:33:53Z
1,577,626
<pre><code>&gt;&gt;&gt; def weekdays_between(s, e): ... return [n % 7 for n in range(s, e + (1 if e &gt; s else 8))] ... &gt;&gt;&gt; weekdays_between(2, 4) [2, 3, 4] &gt;&gt;&gt; weekdays_between(5, 1) [5, 6, 0, 1] </code></pre> <p>It's a bit more complex if you have to convert from/to actual days.</p> <pre><code>&gt;&gt;&gt; days = 'Mon Tue Wed Thu Fri Sat Sun'.split() &gt;&gt;&gt; days_1 = {d: n for n, d in enumerate(days)} &gt;&gt;&gt; def weekdays_between(s, e): ... s, e = days_1[s], days_1[e] ... return [days[n % 7] for n in range(s, e + (1 if e &gt; s else 8))] ... &gt;&gt;&gt; weekdays_between('Wed', 'Fri') ['Wed', 'Thu', 'Fri'] &gt;&gt;&gt; weekdays_between('Sat', 'Tue') ['Sat', 'Sun', 'Mon', 'Tue'] </code></pre>
8
2009-10-16T11:52:20Z
[ "python", "algorithm" ]
How can I get all days between two days?
1,577,538
<p>I need all the weekdays between two days.</p> <p>Example:</p> <pre> Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 </pre> <p>I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an <code>if</code> statement.</p> <p>There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too.</p> <p>The best I could come up with:</p> <pre><code>def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 &gt; d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2] </code></pre>
3
2009-10-16T11:33:53Z
1,577,744
<p>The following code returns 1 for Monday - Monday.</p> <pre><code>bool isWeekday(int d) { return d &gt;= 1 &amp;&amp; d &lt;= 5; } int f(int d1, int d2) { int res = isWeekday(d1) ? 1 : 0; return d1 == d2 ? res : res + f(d1 % 7 + 1, d2); } </code></pre>
0
2009-10-16T12:25:09Z
[ "python", "algorithm" ]
How can I get all days between two days?
1,577,538
<p>I need all the weekdays between two days.</p> <p>Example:</p> <pre> Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 </pre> <p>I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an <code>if</code> statement.</p> <p>There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too.</p> <p>The best I could come up with:</p> <pre><code>def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 &gt; d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2] </code></pre>
3
2009-10-16T11:33:53Z
1,577,992
<p>The solutions provided already answer the question, but I want to suggest something extra. I don't know what you're doing, but maybe you want the actual dates instead?</p> <pre><code>&gt;&gt;&gt; from datetime import timedelta, date &gt;&gt;&gt; from dateutil.rrule import rrule, DAILY &gt;&gt;&gt; today = date(2009, 10, 13) # A tuesday &gt;&gt;&gt; week = today - timedelta(days=6) &gt;&gt;&gt; list(rrule(DAILY, byweekday=xrange(5), dtstart=week, until=today)) [datetime.datetime(2009, 10, 7, 0, 0), datetime.datetime(2009, 10, 8, 0, 0), datetime.datetime(2009, 10, 9, 0, 0), datetime.datetime(2009, 10, 12, 0, 0), datetime.datetime(2009, 10, 13, 0, 0)] </code></pre> <p>That uses the excellent <a href="http://labix.org/python-dateutil" rel="nofollow">python-dateutil</a> module.</p>
1
2009-10-16T13:16:46Z
[ "python", "algorithm" ]
How can I get all days between two days?
1,577,538
<p>I need all the weekdays between two days.</p> <p>Example:</p> <pre> Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 </pre> <p>I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an <code>if</code> statement.</p> <p>There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too.</p> <p>The best I could come up with:</p> <pre><code>def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 &gt; d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2] </code></pre>
3
2009-10-16T11:33:53Z
1,579,588
<p>Use the calendar module for your list of day names:</p> <pre><code>import calendar def intervening_days(day1, day2): weektest = list(calendar.day_name)*2 d1 = weektest.index(day1) d2 = weektest.index(day2,d1+1) return weektest[d1:d2+1] print intervening_days("Monday","Sunday") print intervening_days("Monday","Tuesday") print intervening_days("Thursday","Tuesday") print intervening_days("Monday","Monday") </code></pre> <p>Prints:</p> <pre><code>['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] ['Monday', 'Tuesday'] ['Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday'] ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday'] </code></pre> <p>If you don't want Monday-to-Monday to return a full week of days, change the determination of d2 to <code>d2 = weektest.index(day2,d1)</code>.</p>
1
2009-10-16T18:18:39Z
[ "python", "algorithm" ]
How can I get all days between two days?
1,577,538
<p>I need all the weekdays between two days.</p> <p>Example:</p> <pre> Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 </pre> <p>I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an <code>if</code> statement.</p> <p>There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too.</p> <p>The best I could come up with:</p> <pre><code>def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 &gt; d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2] </code></pre>
3
2009-10-16T11:33:53Z
1,579,729
<p>Building on the <a href="http://stackoverflow.com/questions/1577538/how-can-i-get-all-days-between-two-days/1577626#1577626">excellent answer from Stephan202</a>, you can generalize the concept of a circular slice.</p> <pre><code>&gt;&gt;&gt; def circular_slice(r, s, e): ... return [r[n % len(r)] for n in range(s, e + (1 if e&gt;s else len(r)+1))] ... &gt;&gt;&gt; circular_slice(range(0,7), 2, 4) [2, 3, 4] &gt;&gt;&gt; circular_slice(range(0,7), 5, 1) [5, 6, 0, 1] &gt;&gt;&gt; circular_slice('Mon Tue Wed Thu Fri Sat Sun'.split(), 5, 1) ['Sat', 'Sun', 'Mon', 'Tue'] </code></pre>
2
2009-10-16T18:46:22Z
[ "python", "algorithm" ]
Weird lxml behavior
1,577,732
<p>Consider the following snippet:</p> <pre><code>import lxml.html html = '&lt;div&gt;&lt;br /&gt;Hello text&lt;/div&gt;' doc = lxml.html.fromstring(html) text = doc.xpath('//text()')[0] print lxml.html.tostring(text.getparent()) #prints &lt;br&gt;Hello text </code></pre> <p>I was expecting to see <code>'&lt;div&gt;&lt;br /&gt;Hello text&lt;/div&gt;'</code>, because <code>br</code> can't have nested text and is "self-closed" (I mean <code>/&gt;</code>). How to make <code>lxml</code> handle it right?</p>
1
2009-10-16T12:22:42Z
1,577,897
<p>HTML doesn't have self-closing tags. It is a xml thing.</p> <pre><code>import lxml.etree html = '&lt;div&gt;&lt;br /&gt;Hello text&lt;/div&gt;' doc = lxml.etree.fromstring(html) text = doc.xpath('//text()')[0] print lxml.etree.tostring(text.getparent()) </code></pre> <p>prints</p> <pre><code>&lt;br/&gt;Hello text </code></pre> <p>Note that the text is not inside the tag. <code>lxml</code> has a "<code>tail</code>" concept.</p> <pre><code>&gt;&gt;&gt; print text.text None &gt;&gt;&gt; print text.tail Hello text </code></pre>
8
2009-10-16T12:55:34Z
[ "python", "lxml" ]
Weird lxml behavior
1,577,732
<p>Consider the following snippet:</p> <pre><code>import lxml.html html = '&lt;div&gt;&lt;br /&gt;Hello text&lt;/div&gt;' doc = lxml.html.fromstring(html) text = doc.xpath('//text()')[0] print lxml.html.tostring(text.getparent()) #prints &lt;br&gt;Hello text </code></pre> <p>I was expecting to see <code>'&lt;div&gt;&lt;br /&gt;Hello text&lt;/div&gt;'</code>, because <code>br</code> can't have nested text and is "self-closed" (I mean <code>/&gt;</code>). How to make <code>lxml</code> handle it right?</p>
1
2009-10-16T12:22:42Z
1,577,913
<p>When you are dealing with valid XHTML you can use the etree instead of html.</p> <pre><code>import lxml.etree html = '&lt;div&gt;&lt;br /&gt;Hello text&lt;/div&gt;' doc = lxml.etree.fromstring(html) text = doc.xpath('//text()')[0] print lxml.etree.tostring(text.getparent()) </code></pre> <p>Fun thing, you can typically use this to convert HTML to XHTML:</p> <pre><code>import lxml.etree import lxml.html html = '&lt;div&gt;&lt;br&gt;Hello text&lt;/div&gt;' doc = lxml.html.fromstring(html) text = doc.xpath('//text()')[0] print lxml.etree.tostring(text.getparent()) </code></pre> <p>Output: <code>"&lt;br/&gt;Hello text"</code></p>
2
2009-10-16T12:59:20Z
[ "python", "lxml" ]
Django - Custom SQL in the connection string
1,577,800
<p>I have had some issues with downtime as a result of hitting the <code>max_user_connections</code> limit in MySql.</p> <p>The <strong>default connection timeout is 8 hours</strong>, so once we hit the limit (and having no access to kill the connections on our shared hosting) I simply had to wait 8 hours for the connections to time out.</p> <p>I would like to add the following code to my connection string:</p> <pre><code>SET wait_timeout=300; </code></pre> <p>Which would <strong>change the timeout to 5 minutes</strong>. As you can imagine, I'm much happier to deal with 5 minutes of downtime than 8 hours. ;)</p> <p>Is there a good way of adding <strong>custom SQL to the connection string in django</strong>?</p> <p>If not, it has been suggested that we write some <strong>middleware</strong> that runs the SQL before the view is processed.</p> <p>That might work, but I would feel more comfortable knowing that the query was absolutely <strong>guaranteed to run for every connection</strong>, even if more than one connection is opened for each view.</p> <p>Thanks!</p> <p>PS - before you tell me I should just hunt down the code that is keeping the connections from being closed - <strong><em>Never Fear!</em></strong> - we are doing that, but I would like to have this extra insurance against another 8 hour block of downtime</p>
0
2009-10-16T12:35:24Z
1,578,117
<p>You can specify a list of commands to send to MySQL when the connection is open, by setting the DATABASE_OPTIONS dictionary in <code>settings.py</code>. </p> <p>(Incidentally, note that Django doesn't open a new connection for every view.)</p>
1
2009-10-16T13:42:21Z
[ "python", "sql", "django", "connection-string" ]
Communication between Windows Client and Linux Server
1,577,804
<p><br /> I want to provide my colleagues with an interface (using Windows Forms or WPF) to control the states of virtual machines (KVM based) on a linux host. On the command line of this server, I'm using a tool, called <a href="http://libvirt.org/index.html" rel="nofollow">libvirt</a>, which provides python bindings to access its functionality.</p> <p>What whould be the best pratice to remotely access several function like libvirt or reading logfiles on the server. I thought about a REST Full Webservice generated by Python. Are there other viable options to consider?</p> <p>Thanks,<br /> Henrik </p>
0
2009-10-16T12:36:00Z
1,577,862
<p>I'd develop an intranet web application, using any python web framework of choice.</p> <p>That way you don't have to develop/install software on your client. They just point the browser and it works.</p>
2
2009-10-16T12:48:29Z
[ "python", "windows", "linux", "communication" ]
Communication between Windows Client and Linux Server
1,577,804
<p><br /> I want to provide my colleagues with an interface (using Windows Forms or WPF) to control the states of virtual machines (KVM based) on a linux host. On the command line of this server, I'm using a tool, called <a href="http://libvirt.org/index.html" rel="nofollow">libvirt</a>, which provides python bindings to access its functionality.</p> <p>What whould be the best pratice to remotely access several function like libvirt or reading logfiles on the server. I thought about a REST Full Webservice generated by Python. Are there other viable options to consider?</p> <p>Thanks,<br /> Henrik </p>
0
2009-10-16T12:36:00Z
1,577,906
<p><a href="http://pve.proxmox.com/wiki/Main%5FPage" rel="nofollow">Proxmox VE</a> is a complete solution to manage KVM (and OpenVZ) based virtual machines, including a comprehensive web console, so maybe you can get a full solution without developing anything?</p>
1
2009-10-16T12:56:58Z
[ "python", "windows", "linux", "communication" ]
Communication between Windows Client and Linux Server
1,577,804
<p><br /> I want to provide my colleagues with an interface (using Windows Forms or WPF) to control the states of virtual machines (KVM based) on a linux host. On the command line of this server, I'm using a tool, called <a href="http://libvirt.org/index.html" rel="nofollow">libvirt</a>, which provides python bindings to access its functionality.</p> <p>What whould be the best pratice to remotely access several function like libvirt or reading logfiles on the server. I thought about a REST Full Webservice generated by Python. Are there other viable options to consider?</p> <p>Thanks,<br /> Henrik </p>
0
2009-10-16T12:36:00Z
1,578,801
<p>Because you are using a server-side tool that has Python bindings, you should give a serious look at PYRO which is a Python RPC library. </p> <p><a href="http://pyro.sourceforge.net/" rel="nofollow">http://pyro.sourceforge.net/</a></p> <p>To use this you would also have to use Python on the client, but that shouldn't be a problem. If you haven't start writing your client, then you could do it all in IronPython. Or, if you need to add this to an already existing client, then you could still bind in either IronPython or CPython as an embedded scripting engine. </p> <p>For more on PYRO and Ironpython, see this wiki page <a href="http://www.razorvine.net/python/PyroAndIronpython" rel="nofollow">http://www.razorvine.net/python/PyroAndIronpython</a></p>
1
2009-10-16T15:26:53Z
[ "python", "windows", "linux", "communication" ]
Django admin won't let me delete a user in its auth admin application
1,578,372
<p>This may be more of a serverfault question I'm not sure.</p> <p>I have two practically identical servers - I cloned the DB from one to the other, and now when I try to delete a user in the <code>Admin &gt; Auth</code> application Django gives the following error:</p> <pre><code>File "/usr/lib/python2.5/site-packages/django/db/models/sql/query.py", line 206, in results_iter for rows in self.execute_sql(MULTI): File "/usr/lib/python2.5/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql cursor.execute(sql, params) ProgrammingError: relation "django_openidauth_useropenid" does not exist </code></pre> <p>So the issue seems to be <code>django_openidauth_useropenid</code> but what is it referencing - something missing in the DB, or an application?</p> <p>My site is based on the PINAX collection apps.</p>
0
2009-10-16T14:24:02Z
1,590,343
<p>This was resolved by doing a <code>./manage.py syncdb</code></p> <p>It must have got out of date somehow.</p>
0
2009-10-19T18:36:55Z
[ "python", "django", "pinax" ]
Where should I check state / throw exception?
1,578,395
<p>My situation is something like this:</p> <pre><code>class AbstractClass: def __init__(self, property_a): self.property_a = property_a @property def some_value(self): """Code here uses property_a but not property_b to determine some_value""" @property def property_a(self): return self.property_a @property def property_b(self): """Has to be implemented in subclass.""" raise NotImplementedError class Concrete1(AbstractClass): """Code here including an implementation of property_b""" class Concrete2(AbstractClass): """Code here including an implementation of property_b""" </code></pre> <p>There is also a condition that if <code>property_b</code> is less than <code>property_a</code>, then <code>property_a</code> is invalid and thus the result of <code>some_value</code> is also invalid.</p> <p>What I mean is this... if at any time during the object's lifetime, calling <code>property_b</code> would yield a number lower than calling <code>property_a</code>, there's a problem. However, property_b is <strong>not a field</strong>. It is determined dynamically based on <em>n</em> fields, where <em>n</em> >= 1. It is impossible to check this condition while setting <code>property_b</code> because <code>property_b</code> itself is never set. Really, setters are not anticipated to be used <em>anywhere</em> here. All fields are likely to be set in the constructors and then left alone. This means that <code>property_a</code> will be known in the constructor for <code>AbstractClass</code> and <code>property_b</code> only <em>after</em> evaluating the constructor for the concrete classes.</p> <p><strong>&lt;update&gt;</strong><br /> The fundamental problem is this: I need to check <code>property_a</code> for validity, but when <code>property_a</code> is set (the most intuitive place to check it), <code>property_b</code> is undefined.<br /> <strong>&lt;/update&gt;</strong></p> <p>I want to ensure that <code>property_b</code> is never less than <code>property_a</code>. How should I handle it?</p> <p>Check <code>property_a</code> against <code>property_b</code> in...</p> <ol> <li><code>AbstractClass.__init__</code>. This is actually impossible because <code>property_b</code> hasn't been defined yet.</li> <li><code>AbstractClass.property_a</code>. This seems problematic because I would be throwing an exception in a getter.</li> <li>Each concrete implementation of <code>property_b</code>. Not only would I be throwing an exception in a getter, I would be duplicating code. Also <code>property_b</code> does not logically depend on <code>property_a</code>.</li> <li><code>AbstractClass.some_value</code>. This is still throwing an exception in a getter. Also, it is logically impossible for <code>property_b</code> to be less than <code>property_a</code> <em>all the time</em>, not just when trying to determine <code>some_value</code>. Further, if subclasses decide to add other properties that depend on <code>property_a</code>, they may forget to check it against <code>property_b</code>.</li> <li>Concrete setters for <code>property_b</code>. These don't exist. <code>property_b</code> is sometimes determined from a value set in the constructor, sometimes calculated from multiple values. Also, code duplication.</li> <li>Concrete class <code>__init__</code> methods. Code duplication. Someone may forget.</li> <li>???</li> </ol> <p><strong>UPDATE</strong></p> <p>I think what is causing confusion is that <code>property_b</code> is not simply a field. <code>property_b</code> relies on calculations. It is really more a function than a property, if it helps to think about it that way.</p>
1
2009-10-16T14:28:38Z
1,578,442
<p>I suggest that you don't raise <code>raise NotImplementedError</code> but call a method instead which raises this error. Subclasses then have to override that method (instead of <code>property_b</code>). In <code>property_b</code>, you call the method and then verify the result.</p> <p>Rationale: You should check the value as soon as possible (which is when someone changes it). Otherwise, an illegal value could be set and cause a problem much later in the code when no one can say how it got there.</p> <p>Alternatively, you could store the value and a stack trace. When the value is used, you can then check the value and print the original stack trace as "value was changed here".</p>
0
2009-10-16T14:37:04Z
[ "python", "exception" ]
Where should I check state / throw exception?
1,578,395
<p>My situation is something like this:</p> <pre><code>class AbstractClass: def __init__(self, property_a): self.property_a = property_a @property def some_value(self): """Code here uses property_a but not property_b to determine some_value""" @property def property_a(self): return self.property_a @property def property_b(self): """Has to be implemented in subclass.""" raise NotImplementedError class Concrete1(AbstractClass): """Code here including an implementation of property_b""" class Concrete2(AbstractClass): """Code here including an implementation of property_b""" </code></pre> <p>There is also a condition that if <code>property_b</code> is less than <code>property_a</code>, then <code>property_a</code> is invalid and thus the result of <code>some_value</code> is also invalid.</p> <p>What I mean is this... if at any time during the object's lifetime, calling <code>property_b</code> would yield a number lower than calling <code>property_a</code>, there's a problem. However, property_b is <strong>not a field</strong>. It is determined dynamically based on <em>n</em> fields, where <em>n</em> >= 1. It is impossible to check this condition while setting <code>property_b</code> because <code>property_b</code> itself is never set. Really, setters are not anticipated to be used <em>anywhere</em> here. All fields are likely to be set in the constructors and then left alone. This means that <code>property_a</code> will be known in the constructor for <code>AbstractClass</code> and <code>property_b</code> only <em>after</em> evaluating the constructor for the concrete classes.</p> <p><strong>&lt;update&gt;</strong><br /> The fundamental problem is this: I need to check <code>property_a</code> for validity, but when <code>property_a</code> is set (the most intuitive place to check it), <code>property_b</code> is undefined.<br /> <strong>&lt;/update&gt;</strong></p> <p>I want to ensure that <code>property_b</code> is never less than <code>property_a</code>. How should I handle it?</p> <p>Check <code>property_a</code> against <code>property_b</code> in...</p> <ol> <li><code>AbstractClass.__init__</code>. This is actually impossible because <code>property_b</code> hasn't been defined yet.</li> <li><code>AbstractClass.property_a</code>. This seems problematic because I would be throwing an exception in a getter.</li> <li>Each concrete implementation of <code>property_b</code>. Not only would I be throwing an exception in a getter, I would be duplicating code. Also <code>property_b</code> does not logically depend on <code>property_a</code>.</li> <li><code>AbstractClass.some_value</code>. This is still throwing an exception in a getter. Also, it is logically impossible for <code>property_b</code> to be less than <code>property_a</code> <em>all the time</em>, not just when trying to determine <code>some_value</code>. Further, if subclasses decide to add other properties that depend on <code>property_a</code>, they may forget to check it against <code>property_b</code>.</li> <li>Concrete setters for <code>property_b</code>. These don't exist. <code>property_b</code> is sometimes determined from a value set in the constructor, sometimes calculated from multiple values. Also, code duplication.</li> <li>Concrete class <code>__init__</code> methods. Code duplication. Someone may forget.</li> <li>???</li> </ol> <p><strong>UPDATE</strong></p> <p>I think what is causing confusion is that <code>property_b</code> is not simply a field. <code>property_b</code> relies on calculations. It is really more a function than a property, if it helps to think about it that way.</p>
1
2009-10-16T14:28:38Z
1,578,875
<p>Add a method <code>_validate_b(self, b)</code> (single leading underscore to indicate "protected", i.e., callable from derived classes but not by general client code) that validates the value of b (which only subclasses know) vs the value of a (which the abstract superclass does know).</p> <p>Make subclasses responsible for calling the validation method whenever they're doing something that could change their internal value for b. In your very general case, the superclass cannot identify when b's value changes; since the responsibility of that change lies entirely with the subclasses, then the responsibility for triggering validation must also be with them (the superclass can <em>perform</em> validation, given the proposed new value of b, but it cannot know <em>when</em> validity must be checked). So, document that clearly.</p> <p>If most subclasses fall into broad categories in terms of the strategies they use to affect their b's values, you can factor that out into either intermediate abstract classes (inheriting from the general one and specializing the general approach to "determining b", including the validation call), or (better, if feasible) some form of Strategy design pattern (typically implemented via either composition, or mix-in inheritance). But this has more to do with convenience (for concrete-subclass authors) than with "guaranteeing correctness", since a given concrete subclass <em>might</em> bypass such mechanisms.</p> <p>If you need to, you can offer a "debug/test mode" where properties are validated redundantly on access (probably not advisable in production use, but for debugging and testing it would help catch errant subclasses that are not properly calling validation methods).</p>
3
2009-10-16T15:43:29Z
[ "python", "exception" ]
Where should I check state / throw exception?
1,578,395
<p>My situation is something like this:</p> <pre><code>class AbstractClass: def __init__(self, property_a): self.property_a = property_a @property def some_value(self): """Code here uses property_a but not property_b to determine some_value""" @property def property_a(self): return self.property_a @property def property_b(self): """Has to be implemented in subclass.""" raise NotImplementedError class Concrete1(AbstractClass): """Code here including an implementation of property_b""" class Concrete2(AbstractClass): """Code here including an implementation of property_b""" </code></pre> <p>There is also a condition that if <code>property_b</code> is less than <code>property_a</code>, then <code>property_a</code> is invalid and thus the result of <code>some_value</code> is also invalid.</p> <p>What I mean is this... if at any time during the object's lifetime, calling <code>property_b</code> would yield a number lower than calling <code>property_a</code>, there's a problem. However, property_b is <strong>not a field</strong>. It is determined dynamically based on <em>n</em> fields, where <em>n</em> >= 1. It is impossible to check this condition while setting <code>property_b</code> because <code>property_b</code> itself is never set. Really, setters are not anticipated to be used <em>anywhere</em> here. All fields are likely to be set in the constructors and then left alone. This means that <code>property_a</code> will be known in the constructor for <code>AbstractClass</code> and <code>property_b</code> only <em>after</em> evaluating the constructor for the concrete classes.</p> <p><strong>&lt;update&gt;</strong><br /> The fundamental problem is this: I need to check <code>property_a</code> for validity, but when <code>property_a</code> is set (the most intuitive place to check it), <code>property_b</code> is undefined.<br /> <strong>&lt;/update&gt;</strong></p> <p>I want to ensure that <code>property_b</code> is never less than <code>property_a</code>. How should I handle it?</p> <p>Check <code>property_a</code> against <code>property_b</code> in...</p> <ol> <li><code>AbstractClass.__init__</code>. This is actually impossible because <code>property_b</code> hasn't been defined yet.</li> <li><code>AbstractClass.property_a</code>. This seems problematic because I would be throwing an exception in a getter.</li> <li>Each concrete implementation of <code>property_b</code>. Not only would I be throwing an exception in a getter, I would be duplicating code. Also <code>property_b</code> does not logically depend on <code>property_a</code>.</li> <li><code>AbstractClass.some_value</code>. This is still throwing an exception in a getter. Also, it is logically impossible for <code>property_b</code> to be less than <code>property_a</code> <em>all the time</em>, not just when trying to determine <code>some_value</code>. Further, if subclasses decide to add other properties that depend on <code>property_a</code>, they may forget to check it against <code>property_b</code>.</li> <li>Concrete setters for <code>property_b</code>. These don't exist. <code>property_b</code> is sometimes determined from a value set in the constructor, sometimes calculated from multiple values. Also, code duplication.</li> <li>Concrete class <code>__init__</code> methods. Code duplication. Someone may forget.</li> <li>???</li> </ol> <p><strong>UPDATE</strong></p> <p>I think what is causing confusion is that <code>property_b</code> is not simply a field. <code>property_b</code> relies on calculations. It is really more a function than a property, if it helps to think about it that way.</p>
1
2009-10-16T14:28:38Z
1,579,042
<p>The golden rule is to "encapsulate" <code>property_b</code> so that the subclass provides part of the implementation, but not all of it.</p> <pre><code>class AbstractClass: def __init__(self, property_a): self._value_of_a = property_a @property def get_b( self ): self.validate_a() self._value_of_b = self.compute_b() self.validate_other_things() return self._value_of_b def compute_b( self ): raise NotImplementedError </code></pre> <p>It's hard to say precisely what's supposed to happen when you have two classes and you're <em>asking</em> about allocation of responsibility. </p> <p>It appears that you want the superclass to be responsible for some aspect of the relationship between a and b </p> <p>It appears that you want the the subclass to be responsible for some other aspect of computing b, and not responsible for the relationship.</p> <p>If this is what you want, then your design must assign responsibility by decomposing things into the part the superclass is responsible for and the part the subclass is responsible for.</p>
1
2009-10-16T16:23:50Z
[ "python", "exception" ]
Python Singletons - How do you get rid of (__del__) them in your testbench?
1,578,566
<p>Many thanks for the advice you have given me thus far. Using testbenches is something this forum has really shown me the light on and for that I am appreciative. My problem is that I am playing with a singleton and normally I won't del it, but in a testbench I will need to. So can anyone show me how to del the thing? I've started with a <a href="http://code.activestate.com/recipes/52558/" rel="nofollow">basic example</a> and built it up into a testbench so I can see whats going on. Now I don't know how to get rid of it!</p> <p>Many thanks!!</p> <pre><code>import sys import logging import unittest LOGLEVEL = logging.DEBUG class Singleton: """ A python singleton """ class __impl: """ Implementation of the singleton interface """ def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) def id(self): """ Test method, return singleton id """ return id(self) # storage for the instance reference __instance = None def __init__(self): """ Create singleton instance """ # Check whether we already have an instance if Singleton.__instance is None: # Create and remember instance Singleton.__instance = Singleton.__impl() # Store instance reference as the only member in the handle self.__dict__['_Singleton__instance'] = Singleton.__instance def __getattr__(self, attr): """ Delegate access to implementation """ return getattr(self.__instance, attr) def __setattr__(self, attr, value): """ Delegate access to implementation """ return setattr(self.__instance, attr, value) class A: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = Singleton() self.id = self.lowclass.id() self.log.debug("ID: %s" % self.id) class B: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = Singleton() self.id = self.lowclass.id() self.log.debug("ID: %s" % self.id) class ATests(unittest.TestCase): def testOne(self): a = A() aid = a.id b = B() bid = b.id self.assertEqual(a.id, b.id) # # How do I destroy this thing?? # del a del b a1 = A() a1id = a1.id self.assertNotEqual(a1id, aid) if __name__ == '__main__': # Set's up a basic logger logging.basicConfig( format="%(asctime)s %(levelname)-8s %(module)s %(funcName)s %(message)s", datefmt="%H:%M:%S", stream=sys.stderr ) log = logging.getLogger("") log.setLevel(LOGLEVEL) # suite = unittest.TestLoader().loadTestsFromTestCase(ATests) sys.exit(unittest.TextTestRunner(verbosity=LOGLEVEL).run(suite)) </code></pre>
0
2009-10-16T14:53:50Z
1,578,792
<p>Considering you'll have many of those classes, I wouldn't exactly call them singletons. You just defer the attribute to a singleton class. It seems better to make sure the class actually is a singleton.</p> <p>The problem with your solution is that you would have to implement both a <strong>del</strong> method (which is fine) but also a reference-counter, which seems like a bad idea. :-)</p> <p>Here is a question with several implementations: <a href="http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python">http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python</a></p> <p>Which one is for you depends on what kind of singleton you want. One object per a certain value, but for any value? A set of predefined singletons? A proper singleton, ie, just one single object?</p>
0
2009-10-16T15:25:15Z
[ "python", "unit-testing", "singleton" ]
Python Singletons - How do you get rid of (__del__) them in your testbench?
1,578,566
<p>Many thanks for the advice you have given me thus far. Using testbenches is something this forum has really shown me the light on and for that I am appreciative. My problem is that I am playing with a singleton and normally I won't del it, but in a testbench I will need to. So can anyone show me how to del the thing? I've started with a <a href="http://code.activestate.com/recipes/52558/" rel="nofollow">basic example</a> and built it up into a testbench so I can see whats going on. Now I don't know how to get rid of it!</p> <p>Many thanks!!</p> <pre><code>import sys import logging import unittest LOGLEVEL = logging.DEBUG class Singleton: """ A python singleton """ class __impl: """ Implementation of the singleton interface """ def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) def id(self): """ Test method, return singleton id """ return id(self) # storage for the instance reference __instance = None def __init__(self): """ Create singleton instance """ # Check whether we already have an instance if Singleton.__instance is None: # Create and remember instance Singleton.__instance = Singleton.__impl() # Store instance reference as the only member in the handle self.__dict__['_Singleton__instance'] = Singleton.__instance def __getattr__(self, attr): """ Delegate access to implementation """ return getattr(self.__instance, attr) def __setattr__(self, attr, value): """ Delegate access to implementation """ return setattr(self.__instance, attr, value) class A: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = Singleton() self.id = self.lowclass.id() self.log.debug("ID: %s" % self.id) class B: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = Singleton() self.id = self.lowclass.id() self.log.debug("ID: %s" % self.id) class ATests(unittest.TestCase): def testOne(self): a = A() aid = a.id b = B() bid = b.id self.assertEqual(a.id, b.id) # # How do I destroy this thing?? # del a del b a1 = A() a1id = a1.id self.assertNotEqual(a1id, aid) if __name__ == '__main__': # Set's up a basic logger logging.basicConfig( format="%(asctime)s %(levelname)-8s %(module)s %(funcName)s %(message)s", datefmt="%H:%M:%S", stream=sys.stderr ) log = logging.getLogger("") log.setLevel(LOGLEVEL) # suite = unittest.TestLoader().loadTestsFromTestCase(ATests) sys.exit(unittest.TextTestRunner(verbosity=LOGLEVEL).run(suite)) </code></pre>
0
2009-10-16T14:53:50Z
1,578,800
<p>As Borg's author I obviously second @mjv's comment, but, with either Borg (aka "monostate") or Highlander (aka "singleton"), you need to add a "drop everything" method to support the <code>tearDown</code> in your test suite. Naming such method with a single leading underscore tells other parts of the sw to leave it alone, but tests are atypical beasts and often need to muck with such otherwise-internal attributes.</p> <p>So, for your specific case,</p> <pre><code>class Singleton: ... def _drop(self): "Drop the instance (for testing purposes)." Singleton.__instance = None del self._Singleton__instance </code></pre> <p>Similarly, for Borg, a <code>_drop</code> method would release and clear the shared dictionary and replace it with a brand new one.</p>
6
2009-10-16T15:26:45Z
[ "python", "unit-testing", "singleton" ]
IPython in unbuffered mode
1,578,592
<p>Is there a way to run IPython in unbuffered mode?</p> <p>The same way as <code>python -u</code> gives unbuffered IO for the standard python shell</p>
4
2009-10-16T14:57:12Z
1,578,832
<p>Try:</p> <pre><code>python -u `which ipython` </code></pre> <p>Not sure if it will work, though.</p>
0
2009-10-16T15:32:20Z
[ "python", "ipython" ]
IPython in unbuffered mode
1,578,592
<p>Is there a way to run IPython in unbuffered mode?</p> <p>The same way as <code>python -u</code> gives unbuffered IO for the standard python shell</p>
4
2009-10-16T14:57:12Z
1,703,558
<p>From Python's man page:</p> <pre><code> -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object itera‐ tors ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop. </code></pre> <p>If using unbuffered mode interferes with readline, it certainly would interfere even more with all the magic editing and auto-completion that iPython gives you. I'm inclined to suspect that's why that command line option isn't in iPython.</p>
1
2009-11-09T20:28:03Z
[ "python", "ipython" ]
Python: Extracting data from buffer with ctypes
1,578,752
<p>I am able to successfully call a function with ctypes in Python. I now have a buffer that is filled with Structures of data I want to extract. What is the best strategy for this? Anything else I should post?</p> <p>Function:</p> <pre><code>class list(): def __init__(self): #[...] def getdirentries(self, path): self.load_c() self.fd = os.open(path, os.O_RDONLY) self.statinfo = os.fstat(self.fd) self.buffer = ctypes.create_string_buffer(self.statinfo.st_size) nbytes = self.statinfo.st_size transferred_bytes = self.libc.getdirentries( self.fd, ctypes.byref(self.buffer), nbytes, ctypes.byref(self.basep) ) #[...] </code></pre> <p>Structure:</p> <pre><code>class dirent(ctypes.Structure): _fields_ = [ ("d_fileno", ctypes.c_uint32), # /* file number of entry */ ("d_reclen", ctypes.c_uint16), # /* length of this record */ ("d_type", ctypes.c_uint8), # /* file type */ ("d_namlen", ctypes.c_uint8), # /* length of string in d_name */ ("d_name", ctypes.c_char * (MAXNAMELEN + 1) ) ] </code></pre> <p>Some Output:<br /> Transferred bytes: 156<br /> sizeof buffer: 272<br /> Buffer: <code>&lt;ctypes.c_char_Array_272 object at 0x8c3f0&gt;</code> </p>
4
2009-10-16T15:20:59Z
1,579,000
<p>I wonder why you are using os.stat() instead of calling statinfo and os.path.walk() instead of calling getdirentries?</p> <p>Normally, when you have buffers of data that you want to pass in and out of C, you would use the struct modules pack and unpack methods to do this. </p>
0
2009-10-16T16:13:48Z
[ "python", "buffer", "extract", "ctypes" ]
Python Access to BaseRequestHandler
1,578,932
<p>My code basically needs to start up a simple chat server with a client. Where the server and the client can talk back and forth to each other. I've gotten everything to be implemented correctly, but I can't figure out how to shut down the server whenever I'm done. (I know it's <code>ss.shutdown()</code>). </p> <p>I'm wanting to end right now based on a keyword shared between the two (something like <code>"bye"</code>), but I don't know if I can somehow send a message to my <code>SocketServer</code> from <code>BaseRequestHandler</code> to <code>shutdown()</code> whenever it receives the message.</p> <p>Eventually, my goal is to incorporate <code>Tkinter</code> to make a GUI, but I wanted to get everything else to work first, and this is my first time dealing with sockets in Python.</p> <pre><code>from sys import argv, stderr from threading import Thread import socket import SocketServer import threading import sys class ThreadedRecv(Thread): def __init__(self,socket): Thread.__init__(self) self.__socket = socket self.__message = '' self.__done = False def recv(self): while self.__message.strip() != "bye" and not self.getStatus(): self.__message = self.__socket.recv(4096) print 'received',self.__message self.setStatus(True) def run(self): self.recv() def setStatus(self,status): self.__done = status def getStatus(self): return self.__done class ThreadedSend(Thread): def __init__(self,socket): Thread.__init__(self) self.__socket = socket self.__message = '' self.__done = False def send(self): while self.__message != "bye" and not self.getStatus(): self.__message = raw_input() self.__socket.send(self.__message) self.setStatus(True) def run(self): self.send() def setStatus(self,status): self.__done = status def getStatus(self): return self.__done class HostException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class EchoServer(SocketServer.BaseRequestHandler): def setup(self): print self.client_address, 'is connected!' self.request.send('Hello ' + str(self.client_address) + '\n') self.__done = False def handle(self): sender = ThreadedSend(self.request) recver = ThreadedRecv(self.request) sender.start() recver.start() while 1: if recver.getStatus(): sender.setStatus(True) break if sender.getStatus(): recver.setStatus(True) break def finish(self): print self.client_address, 'disconnected' self.request.send('bye client %s\n' % str(self.client_address)) self.setDone(True) def setDone(self,done): self.__done = done def getDone(self): return self.__done def setup(arg1, arg2, arg3): server = False defaultPort,defaultHost = 2358,"localhost" hosts = [] port = defaultPort serverNames = ["TRUE","SERVER","S","YES"] arg1 = arg1.upper() arg2 = arg2.upper() arg3 = arg3.upper() if arg1 in serverNames or arg2 in serverNames or arg3 in serverNames: server = True try: port = int(arg1) if arg2 != '': hosts.append(arg2) except ValueError: if arg1 != '': hosts.append(arg1) try: port = int(arg2) if arg3 != '': hosts.append(arg3) except ValueError: if arg2 != '': hosts.append(arg2) try: port = int(arg3) except ValueError: if arg3 != '': hosts.append(arg3) port = defaultPort for sn in serverNames: if sn in hosts: hosts.remove(sn) try: if len(hosts) != 1: raise HostException("Either more than one or no host "+ \ "declared. Setting host to localhost.") except HostException as error: print error.value, "Setting hosts to default" return (server,defaultHost,port) return (server,hosts[0].lower(),port) def main(): bufsize = 4096 while len(argv[1:4]) &lt; 3: argv.append('') settings = setup(*argv[1:4]) connections = (settings[1],settings[2]) print connections if not settings[0]: try: mySocket = socket.socket(socket.AF_INET,\ socket.SOCK_STREAM) except socket.error, msg: stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: mySocket.connect(connections) except socket.error, msg: stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(2) message = "" print "Enter a message to send to the server. "+\ "Enter \"bye\" to quit." sender = ThreadedSend(mySocket) recver = ThreadedRecv(mySocket) sender.start() recver.start() while 1: if sender.getStatus(): recver.setStatus(True) break if recver.getStatus(): sender.setStatus(True) break else: xserverhandler = EchoServer serversocket = SocketServer.ThreadedTCPServer(\ connections,xserverhandler) server_thread = Thread(target = serversocket.serve_forever) server_thread.setDaemon(True) server_thread.start() # I would like to shut down this server whenever # I get done talking to it. """while 1: if xserverhandler.getDone(): print 'This is now true!' serversocket.shutdown() break""" if __name__ == '__main__': main() </code></pre> <p>Yeah, I know setup() is a terrible function right now with the try's and catches, but it works for now, so I was going to fix it later.</p> <p>My question is basically: How can I get the server to actually end based on a message that it receives? If possible, is there a way to access the Request Handler after it's started?</p>
1
2009-10-16T15:56:04Z
1,579,227
<p>Request handler object is created for each new request. So you have to store "done" flag in server, not handler. Something like the following:</p> <pre><code>class EchoServer(SocketServer.BaseRequestHandler): ... def setDone(self): self.server.setDone() # or even better directly self.server.shutdown() </code></pre>
1
2009-10-16T17:01:33Z
[ "python", "sockets", "tcp", "serversocket", "requesthandler" ]
Python Access to BaseRequestHandler
1,578,932
<p>My code basically needs to start up a simple chat server with a client. Where the server and the client can talk back and forth to each other. I've gotten everything to be implemented correctly, but I can't figure out how to shut down the server whenever I'm done. (I know it's <code>ss.shutdown()</code>). </p> <p>I'm wanting to end right now based on a keyword shared between the two (something like <code>"bye"</code>), but I don't know if I can somehow send a message to my <code>SocketServer</code> from <code>BaseRequestHandler</code> to <code>shutdown()</code> whenever it receives the message.</p> <p>Eventually, my goal is to incorporate <code>Tkinter</code> to make a GUI, but I wanted to get everything else to work first, and this is my first time dealing with sockets in Python.</p> <pre><code>from sys import argv, stderr from threading import Thread import socket import SocketServer import threading import sys class ThreadedRecv(Thread): def __init__(self,socket): Thread.__init__(self) self.__socket = socket self.__message = '' self.__done = False def recv(self): while self.__message.strip() != "bye" and not self.getStatus(): self.__message = self.__socket.recv(4096) print 'received',self.__message self.setStatus(True) def run(self): self.recv() def setStatus(self,status): self.__done = status def getStatus(self): return self.__done class ThreadedSend(Thread): def __init__(self,socket): Thread.__init__(self) self.__socket = socket self.__message = '' self.__done = False def send(self): while self.__message != "bye" and not self.getStatus(): self.__message = raw_input() self.__socket.send(self.__message) self.setStatus(True) def run(self): self.send() def setStatus(self,status): self.__done = status def getStatus(self): return self.__done class HostException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class EchoServer(SocketServer.BaseRequestHandler): def setup(self): print self.client_address, 'is connected!' self.request.send('Hello ' + str(self.client_address) + '\n') self.__done = False def handle(self): sender = ThreadedSend(self.request) recver = ThreadedRecv(self.request) sender.start() recver.start() while 1: if recver.getStatus(): sender.setStatus(True) break if sender.getStatus(): recver.setStatus(True) break def finish(self): print self.client_address, 'disconnected' self.request.send('bye client %s\n' % str(self.client_address)) self.setDone(True) def setDone(self,done): self.__done = done def getDone(self): return self.__done def setup(arg1, arg2, arg3): server = False defaultPort,defaultHost = 2358,"localhost" hosts = [] port = defaultPort serverNames = ["TRUE","SERVER","S","YES"] arg1 = arg1.upper() arg2 = arg2.upper() arg3 = arg3.upper() if arg1 in serverNames or arg2 in serverNames or arg3 in serverNames: server = True try: port = int(arg1) if arg2 != '': hosts.append(arg2) except ValueError: if arg1 != '': hosts.append(arg1) try: port = int(arg2) if arg3 != '': hosts.append(arg3) except ValueError: if arg2 != '': hosts.append(arg2) try: port = int(arg3) except ValueError: if arg3 != '': hosts.append(arg3) port = defaultPort for sn in serverNames: if sn in hosts: hosts.remove(sn) try: if len(hosts) != 1: raise HostException("Either more than one or no host "+ \ "declared. Setting host to localhost.") except HostException as error: print error.value, "Setting hosts to default" return (server,defaultHost,port) return (server,hosts[0].lower(),port) def main(): bufsize = 4096 while len(argv[1:4]) &lt; 3: argv.append('') settings = setup(*argv[1:4]) connections = (settings[1],settings[2]) print connections if not settings[0]: try: mySocket = socket.socket(socket.AF_INET,\ socket.SOCK_STREAM) except socket.error, msg: stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: mySocket.connect(connections) except socket.error, msg: stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(2) message = "" print "Enter a message to send to the server. "+\ "Enter \"bye\" to quit." sender = ThreadedSend(mySocket) recver = ThreadedRecv(mySocket) sender.start() recver.start() while 1: if sender.getStatus(): recver.setStatus(True) break if recver.getStatus(): sender.setStatus(True) break else: xserverhandler = EchoServer serversocket = SocketServer.ThreadedTCPServer(\ connections,xserverhandler) server_thread = Thread(target = serversocket.serve_forever) server_thread.setDaemon(True) server_thread.start() # I would like to shut down this server whenever # I get done talking to it. """while 1: if xserverhandler.getDone(): print 'This is now true!' serversocket.shutdown() break""" if __name__ == '__main__': main() </code></pre> <p>Yeah, I know setup() is a terrible function right now with the try's and catches, but it works for now, so I was going to fix it later.</p> <p>My question is basically: How can I get the server to actually end based on a message that it receives? If possible, is there a way to access the Request Handler after it's started?</p>
1
2009-10-16T15:56:04Z
1,579,401
<p>Please fix your code so it works, and include some way to use it. You need to add</p> <pre><code>class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass </code></pre> <p>since SocketServer doesn't actually include that class (at least not in my version of 2.6 nor 2.7). Instead, it's an example from the <a href="http://docs.python.org/library/socketserver.html" rel="nofollow">SocketServer definition</a>.</p> <p>Please include an example of how to start/use the code. In this case to start the server you need to do:</p> <pre><code>ss.py SERVER localhost 8001 </code></pre> <p>and the client as</p> <pre><code>ss.py localhost 8001 </code></pre> <p>If you do that then you can't do server_thread.setDaemon(True) because there are no other threads running, which means the server will exit immediately.</p> <p>Once that's done the solution is to add a call (or two) to self.server.shutdown() insdie of your EchoServer.handle method, like:</p> <pre><code> while 1: if recver.getStatus(): sender.setStatus(True) self.server.shutdown() break </code></pre> <p>However, I can't get that to work, and I think it's because I inherited things wrong, or guessed wrong in what you did.</p> <p>What you should do is search for someone else who has done a chat server in Python. Using Google I found <a href="http://www.slideshare.net/didip/socket-programming-in-python" rel="nofollow">http://www.slideshare.net/didip/socket-programming-in-python</a> and there are certainly others.</p> <p>Also, if you are going to mix GUI and threaded programming then you should look into examples based on that. There are a number of hits when I searched for "tkinter chat". Also, you might want to look into twisted, which has solved a lot of these problems already.</p> <p>What problems? Well, for example, you likely want an SO_REUSEADDR socket option.</p>
2
2009-10-16T17:38:11Z
[ "python", "sockets", "tcp", "serversocket", "requesthandler" ]
Replace SRC of all IMG elements using Parser
1,579,133
<p>I am looking for a way to replace the SRC attribute in all IMG tags not using Regular expressions. (Would like to use any out-of-the box HTML parser included with default Python install) I need to reduce the source from what ever it may be to:</p> <pre><code>&lt;img src="cid:imagename"&gt; </code></pre> <p>I am trying to replace all src tags to point to the cid of an attachment for an HTML email so I will also need to change whatever the source is so it's simply the file name without the path or extension.</p>
2
2009-10-16T16:47:03Z
1,579,320
<p>You'll probably want to use <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html" rel="nofollow">BeautifulSoup</a> for parsing HTML.</p>
1
2009-10-16T17:21:46Z
[ "python", "html", "parsing", "image", "src" ]
Replace SRC of all IMG elements using Parser
1,579,133
<p>I am looking for a way to replace the SRC attribute in all IMG tags not using Regular expressions. (Would like to use any out-of-the box HTML parser included with default Python install) I need to reduce the source from what ever it may be to:</p> <pre><code>&lt;img src="cid:imagename"&gt; </code></pre> <p>I am trying to replace all src tags to point to the cid of an attachment for an HTML email so I will also need to change whatever the source is so it's simply the file name without the path or extension.</p>
2
2009-10-16T16:47:03Z
1,579,733
<p>There is a HTML parser in the Python standard library, but it’s not very useful and it’s deprecated since Python 2.6. Doing this kind of things with <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> is really easy:</p> <pre><code>from BeautifulSoup import BeautifulSoup from os.path import basename, splitext soup = BeautifulSoup(my_html_string) for img in soup.findAll('img'): img['src'] = 'cid:' + splitext(basename(img['src']))[0] my_html_string = str(soup) </code></pre>
15
2009-10-16T18:47:15Z
[ "python", "html", "parsing", "image", "src" ]
Replace SRC of all IMG elements using Parser
1,579,133
<p>I am looking for a way to replace the SRC attribute in all IMG tags not using Regular expressions. (Would like to use any out-of-the box HTML parser included with default Python install) I need to reduce the source from what ever it may be to:</p> <pre><code>&lt;img src="cid:imagename"&gt; </code></pre> <p>I am trying to replace all src tags to point to the cid of an attachment for an HTML email so I will also need to change whatever the source is so it's simply the file name without the path or extension.</p>
2
2009-10-16T16:47:03Z
1,580,945
<p>Here is a pyparsing approach to your problem. You'll need to do your own code to transform the http src attribute.</p> <pre><code>from pyparsing import * import urllib2 imgtag = makeHTMLTags("img")[0] page = urllib2.urlopen("http://www.yahoo.com") html = page.read() page.close() # print html def modifySrcRef(tokens): ret = "&lt;img" for k,i in tokens.items(): if k in ("startImg","empty"): continue if k.lower() == "src": # or do whatever with this i = i.upper() ret += ' %s="%s"' % (k,i) return ret + " /&gt;" imgtag.setParseAction(modifySrcRef) print imgtag.transformString(html) </code></pre> <p>The tags convert to:</p> <pre><code>&lt;img src="HTTP://L.YIMG.COM/A/I/WW/BETA/Y3.GIF" title="Yahoo" height="44" width="232" alt="Yahoo!" /&gt; &lt;a href="r/xy"&gt;&lt;img src="HTTP://L.YIMG.COM/A/I/WW/TBL/ALLYS.GIF" height="20" width="138" alt="All Yahoo! Services" border="0" /&gt;&lt;/a&gt; </code></pre>
1
2009-10-16T23:50:59Z
[ "python", "html", "parsing", "image", "src" ]
numpy.extract and numpy.any functions, is it possible to make it simpler way?
1,579,218
<p>If there is any possibility to make this code simpler, I'd really appreciate it! I am trying to get rid of rows with zeros. The first column is date. If all other columns are zero, they have to be deleted. Number of columns varies. </p> <pre><code>import numpy as np condition = [ np.any( list(x)[1:] ) for x in r] r = np.extract( condition, r ) </code></pre> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.extract.html" rel="nofollow"><code>numpy.extract</code> docs</a></p>
2
2009-10-16T17:00:45Z
1,579,608
<p>You can avoid the list comprehension and instead use fancy indexing:</p> <pre><code>#!/usr/bin/env python import numpy as np import datetime r=np.array([(datetime.date(2000,1,1),0,1), (datetime.date(2000,1,1),1,1), (datetime.date(2000,1,1),1,0), (datetime.date(2000,1,1),0,0), ]) r=r[r[:,1:].any(axis=1)] print(r) # [[2000-01-01 0 1] # [2000-01-01 1 1] # [2000-01-01 1 0] </code></pre> <p>if r is an ndarray, then r[:,1:] is a view with the first column removed. r[:,1:].any(axis=1) is a boolean array, which you can then use as a "fancy index"</p>
4
2009-10-16T18:25:03Z
[ "python", "numpy" ]
Running Tests From a Module
1,579,350
<p>I am attempting to run some unit tests in python from what I believe is a module. I have a directory structure like</p> <pre><code>TestSuite.py UnitTests |__init__.py |TestConvertStringToNumber.py </code></pre> <p>In testsuite.py I have</p> <pre><code>import unittest import UnitTests class TestSuite: def __init__(self): pass print "Starting testting" suite = unittest.TestLoader().loadTestsFromModule(UnitTests) unittest.TextTestRunner(verbosity=1).run(suite) </code></pre> <p>Which looks to kick off the testing okay but it doesn't pick up any of the test in TestConvertNumberToString.py. In that class I have a set of functions which start with 'test'. </p> <p>What should I be doing such that running python TestSuite.py actually kicks off all of my tests in UnitTests? </p>
2
2009-10-16T17:28:19Z
1,579,513
<p>Here is some code which will run all the unit tests in a directory:</p> <pre><code>#!/usr/bin/env python import unittest import sys import os unit_dir = sys.argv[1] if len(sys.argv) &gt; 1 else '.' os.chdir(unit_dir) suite = unittest.TestSuite() for filename in os.listdir('.'): if filename.endswith('.py') and filename.startswith('test_'): modname = filename[:-2] module = __import__(modname) suite.addTest(unittest.TestLoader().loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=2).run(suite) </code></pre> <p>If you call it testsuite.py, then you would run it like this:</p> <pre><code>testsuite.py UnitTests </code></pre>
4
2009-10-16T18:02:48Z
[ "python", "unit-testing", "import", "tdd", "pyunit" ]
Running Tests From a Module
1,579,350
<p>I am attempting to run some unit tests in python from what I believe is a module. I have a directory structure like</p> <pre><code>TestSuite.py UnitTests |__init__.py |TestConvertStringToNumber.py </code></pre> <p>In testsuite.py I have</p> <pre><code>import unittest import UnitTests class TestSuite: def __init__(self): pass print "Starting testting" suite = unittest.TestLoader().loadTestsFromModule(UnitTests) unittest.TextTestRunner(verbosity=1).run(suite) </code></pre> <p>Which looks to kick off the testing okay but it doesn't pick up any of the test in TestConvertNumberToString.py. In that class I have a set of functions which start with 'test'. </p> <p>What should I be doing such that running python TestSuite.py actually kicks off all of my tests in UnitTests? </p>
2
2009-10-16T17:28:19Z
1,579,630
<p>Using Twisted's "trial" test runner, you can get rid of TestSuite.py, and just do:</p> <pre><code>$ trial UnitTests.TestConvertStringToNumber </code></pre> <p>on the command line; or, better yet, just</p> <pre><code>$ trial UnitTests </code></pre> <p>to discover and run all tests in the package.</p>
0
2009-10-16T18:29:46Z
[ "python", "unit-testing", "import", "tdd", "pyunit" ]
Is there a random function in python that accepts variables?
1,579,741
<p>I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. However, <code>randint</code> will not accept a variable. Is there a way to do what I'm trying to do?</p> <p>code below:</p> <pre><code>import random a=0 final=0 working=0 sides = input("How many dice do you want to roll?") while a&lt;=sides: a=a+1 working=random.randint(1, 4) final=final+working print "Your total is:", final </code></pre>
-1
2009-10-16T18:47:48Z
1,579,761
<p>Try randrange(1, 5)</p> <p><a href="http://effbot.org/pyfaq/how-do-i-generate-random-numbers-in-python.htm" rel="nofollow">Generating random numbers in Python</a></p>
1
2009-10-16T18:50:45Z
[ "python", "random" ]
Is there a random function in python that accepts variables?
1,579,741
<p>I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. However, <code>randint</code> will not accept a variable. Is there a way to do what I'm trying to do?</p> <p>code below:</p> <pre><code>import random a=0 final=0 working=0 sides = input("How many dice do you want to roll?") while a&lt;=sides: a=a+1 working=random.randint(1, 4) final=final+working print "Your total is:", final </code></pre>
-1
2009-10-16T18:47:48Z
1,579,767
<p>you need to pass sides to <code>randint</code>, for example like this:</p> <pre><code>working = random.randint(1, int(sides)) </code></pre> <p>also, it's not the best practice to use <code>input</code> in python-2.x. please, use <code>raw_input</code> instead, you'll need to convert to number yourself, but it's safer.</p>
2
2009-10-16T18:51:36Z
[ "python", "random" ]
Is there a random function in python that accepts variables?
1,579,741
<p>I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. However, <code>randint</code> will not accept a variable. Is there a way to do what I'm trying to do?</p> <p>code below:</p> <pre><code>import random a=0 final=0 working=0 sides = input("How many dice do you want to roll?") while a&lt;=sides: a=a+1 working=random.randint(1, 4) final=final+working print "Your total is:", final </code></pre>
-1
2009-10-16T18:47:48Z
1,579,797
<p>random.randint accepts a variable as either of its two parameters. I'm not sure exactly what your issue is.</p> <p>This works for me:</p> <pre><code>import random # generate number between 1 and 6 sides = 6 print random.randint(1, sides) </code></pre>
1
2009-10-16T18:59:29Z
[ "python", "random" ]
Is there a random function in python that accepts variables?
1,579,741
<p>I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. However, <code>randint</code> will not accept a variable. Is there a way to do what I'm trying to do?</p> <p>code below:</p> <pre><code>import random a=0 final=0 working=0 sides = input("How many dice do you want to roll?") while a&lt;=sides: a=a+1 working=random.randint(1, 4) final=final+working print "Your total is:", final </code></pre>
-1
2009-10-16T18:47:48Z
1,580,211
<p>If looks like you're confused about the number of dice and the number of sides</p> <p>I've changed the code to use <code>raw_input()</code>. <code>input()</code>is not recommended because Python literally evaluates the user input which could be malicious python code</p> <pre><code>import random a=0 final=0 working=0 rolls = int(raw_input("How many dice do you want to roll? ")) sides = int(raw_input("How many sides? ")) while a&lt;rolls: a=a+1 working=random.randint(1, sides) final=final+working print "Your total is:", final </code></pre>
3
2009-10-16T20:24:40Z
[ "python", "random" ]
How do I know what data type to use in Python?
1,579,744
<p>I'm working through some tutorials on Python and am at a position where I am trying to decide what data type/structure to use in a certain situation.</p> <p>I'm not clear on the differences between arrays, lists, dictionaries and tuples.</p> <p>How do you decide which one is appropriate - my current understanding doesn't let me distinguish between them at all - they seem to be the same thing.</p> <p>What are the benefits/typical use cases for each one?</p>
3
2009-10-16T18:48:21Z
1,579,758
<p>Do you really require speed/efficiency? Then go with a pure and simple dict.</p>
0
2009-10-16T18:50:39Z
[ "python", "arrays", "types", "tuples" ]
How do I know what data type to use in Python?
1,579,744
<p>I'm working through some tutorials on Python and am at a position where I am trying to decide what data type/structure to use in a certain situation.</p> <p>I'm not clear on the differences between arrays, lists, dictionaries and tuples.</p> <p>How do you decide which one is appropriate - my current understanding doesn't let me distinguish between them at all - they seem to be the same thing.</p> <p>What are the benefits/typical use cases for each one?</p>
3
2009-10-16T18:48:21Z
1,579,759
<p>Best type for counting elements like this is usually <a href="http://docs.python.org/library/collections.html#defaultdict-objects" rel="nofollow"><code>defaultdict</code></a></p> <pre><code>from collections import defaultdict s = 'asdhbaklfbdkabhvsdybvailybvdaklybdfklabhdvhba' d = defaultdict(int) for c in s: d[c] += 1 print d['a'] # prints 7 </code></pre>
3
2009-10-16T18:50:42Z
[ "python", "arrays", "types", "tuples" ]
How do I know what data type to use in Python?
1,579,744
<p>I'm working through some tutorials on Python and am at a position where I am trying to decide what data type/structure to use in a certain situation.</p> <p>I'm not clear on the differences between arrays, lists, dictionaries and tuples.</p> <p>How do you decide which one is appropriate - my current understanding doesn't let me distinguish between them at all - they seem to be the same thing.</p> <p>What are the benefits/typical use cases for each one?</p>
3
2009-10-16T18:48:21Z
1,579,821
<p>How do you decide which data type to use? Easy:</p> <p>You look at which are available and choose the one that does what you want. And if there isn't one, you make one.</p> <p>In this case a dict is a pretty obvious solution.</p>
6
2009-10-16T19:03:38Z
[ "python", "arrays", "types", "tuples" ]
How do I know what data type to use in Python?
1,579,744
<p>I'm working through some tutorials on Python and am at a position where I am trying to decide what data type/structure to use in a certain situation.</p> <p>I'm not clear on the differences between arrays, lists, dictionaries and tuples.</p> <p>How do you decide which one is appropriate - my current understanding doesn't let me distinguish between them at all - they seem to be the same thing.</p> <p>What are the benefits/typical use cases for each one?</p>
3
2009-10-16T18:48:21Z
1,580,322
<p>Tuples first. These are list-like things that cannot be modified. Because the contents of a tuple cannot change, you can use a tuple as a key in a dictionary. That's the most useful place for them in my opinion. For instance if you have a list like <code>item = ["Ford pickup", 1993, 9995]</code> and you want to make a little in-memory database with the prices you might try something like:</p> <pre><code>ikey = tuple(item[0], item[1]) idata = item[2] db[ikey] = idata </code></pre> <p>Lists, seem to be like arrays or vectors in other programming languages and are usually used for the same types of things in Python. However, they are more flexible in that you can put different types of things into the same list. Generally, they are the most flexible data structure since you can put a whole list into a single list element of another list, but for real data crunching they may not be efficient enough.</p> <pre><code>a = [1,"fred",7.3] b = [] b.append(1) b[0] = "fred" b.append(a) # now the second element of b is the whole list a </code></pre> <p>Dictionaries are often used a lot like lists, but now you can use any immutable thing as the index to the dictionary. However, unlike lists, dictionaries don't have a natural order and can't be sorted in place. Of course you can create your own class that incorporates a sorted list and a dictionary in order to make a dict behave like an Ordered Dictionary. There are examples on the Python Cookbook site.</p> <pre><code>c = {} d = ("ford pickup",1993) c[d] = 9995 </code></pre> <p>Arrays are getting closer to the bit level for when you are doing heavy duty data crunching and you don't want the frills of lists or dictionaries. They are not often used outside of scientific applications. Leave these until you know for sure that you need them.</p> <p>Lists and Dicts are the real workhorses of Python data storage.</p>
3
2009-10-16T20:48:43Z
[ "python", "arrays", "types", "tuples" ]
How do I know what data type to use in Python?
1,579,744
<p>I'm working through some tutorials on Python and am at a position where I am trying to decide what data type/structure to use in a certain situation.</p> <p>I'm not clear on the differences between arrays, lists, dictionaries and tuples.</p> <p>How do you decide which one is appropriate - my current understanding doesn't let me distinguish between them at all - they seem to be the same thing.</p> <p>What are the benefits/typical use cases for each one?</p>
3
2009-10-16T18:48:21Z
1,580,736
<p>Personal: <strong>I m</strong>ostly work with lists and dictionaries. It seems that this satisfies most cases.</p> <p><strong>Sometimes:</strong> Tuples can be helpful--if you want to pair/match elements. Besides that, I don't really use it.</p> <p><strong>However:</strong> I write high-level scripts that don't need to drill down into the core "efficiency" where every byte and every memory/nanosecond matters. I don't believe most people need to drill this deep.</p>
0
2009-10-16T22:27:32Z
[ "python", "arrays", "types", "tuples" ]
Fastest nested loops over a single list (with elements remove or not)
1,579,771
<p>I am looking for advice about how to parse a single list, using two nested loops, in the fastest way, avoiding doing <code>len(list)^2</code> comparisons, and avoiding duplicate files in groups.</p> <p>More precisely: I have a list of 'file' objects, that each has a timestamp. I want to group the files by their timestamp and a time offset. Ex. starting from a file X, I want to create a group with all the files that have the <code>timestamp &lt; (timestamp(x) + offset)</code>.</p> <p>For this, I did:</p> <pre><code>for file_a in list: temp_group = group() temp_group.add(file_a) list.remove(file_a) for file_b in list: if (file_b.timestamp &lt; (file_a.timestamp + offset)): temp_group.add(file_b) list.remove(file_b) groups.add(temp_group) </code></pre> <p>(ok, the code is more complicated, but this is the main idea)</p> <p>This obviously doesn't work, because I am modifying the list during the loops, and strange things happen :)</p> <p>I thought I have to use copy of 'list' for the loops, but, this doesn't work either:</p> <pre><code>for file_a in list[:]: temp_group = group() temp_group.add(file_a) list.remove(file_a) for file_b in list[:]: if (file_b.timestamp &lt; (file_a.timestamp + offset)): temp_group.add(file_b) list.remove(file_b) groups.add(temp_group) </code></pre> <p>Well.. I know I can do this without removing elements from the list, but then I need to mark the ones that were already 'processed', and I need to check them each time - which is a speed penalty.</p> <p>Can anyone give me some advice about how this can be done in the fastest/best way?</p> <p>Thank you,</p> <p>Alex</p> <p><b>EDIT:</b> I have found an other solution, that doesn't exactly answers the question, but it is what I actually needed (my mistake for asking the question in that way). I am posting this here because it may help someone looking for related issues with loops over lists, in Python.</p> <p>It may not be the fastest (considering the number of 'passes' through the list), but it was quite simple to understand and implement, and it does not require the list to be sorted.</p> <p>The reason for which I avoid sorting is that it may take some more time, and because after I make the first set of groups, some of them will be 'locked', and the unlocked groups will be 'dissolved', and regrouped using a different time offset. (And when dissolving groups, the files order may be changed, and they will require sorting again).</p> <p>Anyway, the solution was to control the loops index myself. If I delete a file from the list, I skip increasing the index (ex: when I delete index "3", the previous index "4" is now "3", and I don't want to increment the loop counter, because I will skip over it). If at that iteration I don't delete any item, then the index is increased normally. Here's the code (with some extras; ignore all that 'bucket' stuff):</p> <pre><code>def regroup(self, time_offset): #create list of files to be used for regrouping regroup_files_list = [] if len(self.groups) == 0: #on first 'regroup', we start with a copy of jpeg_list, so that we do not change it further on regroup_files_list = copy.copy(self.jpeg_list) else: i = 0 while True: try: group = self.groups[i] except IndexError: break if group.is_locked == False: regroup_files_list.extend(group) self.groups.remove(group) continue else: i += 1 bucket_group = FilesGroup() bucket_group.name = c_bucket_group_name while len(regroup_files_list) &gt; 0: #we create groups until there are no files left file_a = regroup_files_list[0] regroup_files_list.remove(file_a) temp_group = FilesGroup() temp_group.start_time = file_a._iso_time temp_group.add(file_a) #manually manage the list index when iterating for file_b, because we're removing files i = 0 while True: try: file_b = regroup_files_list[i] except IndexError: break timediff = file_a._iso_time - file_b._iso_time if timediff.days &lt; 0 or timediff.seconds &lt; 0: timediff = file_b._iso_time - file_a._iso_time if timediff &lt; time_offset: temp_group.add(file_b) regroup_files_list.remove(file_b) continue # :D we reuse the old position, because all elements were shifted to the left else: i += 1 #the index is increased normally self.groups.append(temp_group) #move files to the bucket group, if the temp group is too small if c_bucket_group_enabled == True: if len(temp_group) &lt; c_bucket_group_min_count: for file in temp_group: bucket_group.add(file) temp_group.remove(file) else: self.groups.append(temp_group) if len(bucket_group) &gt; 0: self.groups.append(bucket_group) </code></pre>
1
2009-10-16T18:52:28Z
1,579,799
<h3>A simple solution that works by sorting the list then using a generator to create groups:</h3> <pre><code>def time_offsets(files, offset): files = sorted(files, key=lambda x:x.timestamp) group = [] timestamp = 0 for f in files: if f.timestamp &lt; timestamp + offset: group.append(f) else: yield group timestamp = f.timestamp group = [timestamp] else: yield group # Now you can do this... for group in time_offsets(files, 86400): print group </code></pre> <h3>And here's a complete script you can run to test:</h3> <pre><code>class File: def __init__(self, timestamp): self.timestamp = timestamp def __repr__(self): return "File: &lt;%d&gt;" % self.timestamp def gen_files(num=100): import random files = [] for i in range(num): timestamp = random.randint(0,1000000) files.append(File(timestamp)) return files def time_offsets(files, offset): files = sorted(files, key=lambda x:x.timestamp) group = [] timestamp = 0 for f in files: if f.timestamp &lt; timestamp + offset: group.append(f) else: yield group timestamp = f.timestamp group = [timestamp] else: yield group # Now you can do this to group files by day (assuming timestamp in seconds) files = gen_files() for group in time_offsets(files, 86400): print group </code></pre>
3
2009-10-16T18:59:33Z
[ "python", "performance", "list", "nested-loops" ]
Fastest nested loops over a single list (with elements remove or not)
1,579,771
<p>I am looking for advice about how to parse a single list, using two nested loops, in the fastest way, avoiding doing <code>len(list)^2</code> comparisons, and avoiding duplicate files in groups.</p> <p>More precisely: I have a list of 'file' objects, that each has a timestamp. I want to group the files by their timestamp and a time offset. Ex. starting from a file X, I want to create a group with all the files that have the <code>timestamp &lt; (timestamp(x) + offset)</code>.</p> <p>For this, I did:</p> <pre><code>for file_a in list: temp_group = group() temp_group.add(file_a) list.remove(file_a) for file_b in list: if (file_b.timestamp &lt; (file_a.timestamp + offset)): temp_group.add(file_b) list.remove(file_b) groups.add(temp_group) </code></pre> <p>(ok, the code is more complicated, but this is the main idea)</p> <p>This obviously doesn't work, because I am modifying the list during the loops, and strange things happen :)</p> <p>I thought I have to use copy of 'list' for the loops, but, this doesn't work either:</p> <pre><code>for file_a in list[:]: temp_group = group() temp_group.add(file_a) list.remove(file_a) for file_b in list[:]: if (file_b.timestamp &lt; (file_a.timestamp + offset)): temp_group.add(file_b) list.remove(file_b) groups.add(temp_group) </code></pre> <p>Well.. I know I can do this without removing elements from the list, but then I need to mark the ones that were already 'processed', and I need to check them each time - which is a speed penalty.</p> <p>Can anyone give me some advice about how this can be done in the fastest/best way?</p> <p>Thank you,</p> <p>Alex</p> <p><b>EDIT:</b> I have found an other solution, that doesn't exactly answers the question, but it is what I actually needed (my mistake for asking the question in that way). I am posting this here because it may help someone looking for related issues with loops over lists, in Python.</p> <p>It may not be the fastest (considering the number of 'passes' through the list), but it was quite simple to understand and implement, and it does not require the list to be sorted.</p> <p>The reason for which I avoid sorting is that it may take some more time, and because after I make the first set of groups, some of them will be 'locked', and the unlocked groups will be 'dissolved', and regrouped using a different time offset. (And when dissolving groups, the files order may be changed, and they will require sorting again).</p> <p>Anyway, the solution was to control the loops index myself. If I delete a file from the list, I skip increasing the index (ex: when I delete index "3", the previous index "4" is now "3", and I don't want to increment the loop counter, because I will skip over it). If at that iteration I don't delete any item, then the index is increased normally. Here's the code (with some extras; ignore all that 'bucket' stuff):</p> <pre><code>def regroup(self, time_offset): #create list of files to be used for regrouping regroup_files_list = [] if len(self.groups) == 0: #on first 'regroup', we start with a copy of jpeg_list, so that we do not change it further on regroup_files_list = copy.copy(self.jpeg_list) else: i = 0 while True: try: group = self.groups[i] except IndexError: break if group.is_locked == False: regroup_files_list.extend(group) self.groups.remove(group) continue else: i += 1 bucket_group = FilesGroup() bucket_group.name = c_bucket_group_name while len(regroup_files_list) &gt; 0: #we create groups until there are no files left file_a = regroup_files_list[0] regroup_files_list.remove(file_a) temp_group = FilesGroup() temp_group.start_time = file_a._iso_time temp_group.add(file_a) #manually manage the list index when iterating for file_b, because we're removing files i = 0 while True: try: file_b = regroup_files_list[i] except IndexError: break timediff = file_a._iso_time - file_b._iso_time if timediff.days &lt; 0 or timediff.seconds &lt; 0: timediff = file_b._iso_time - file_a._iso_time if timediff &lt; time_offset: temp_group.add(file_b) regroup_files_list.remove(file_b) continue # :D we reuse the old position, because all elements were shifted to the left else: i += 1 #the index is increased normally self.groups.append(temp_group) #move files to the bucket group, if the temp group is too small if c_bucket_group_enabled == True: if len(temp_group) &lt; c_bucket_group_min_count: for file in temp_group: bucket_group.add(file) temp_group.remove(file) else: self.groups.append(temp_group) if len(bucket_group) &gt; 0: self.groups.append(bucket_group) </code></pre>
1
2009-10-16T18:52:28Z
1,579,824
<p>The best solution I can think of is <code>O(n log n)</code>.</p> <pre><code>listA = getListOfFiles() listB = stableMergesort(listA, lambda el: el.timestamp) listC = groupAdjacentElementsByTimestampRange(listB, offset) </code></pre> <p>Note that <code>groupAdjacentElementsByTimestampRange</code> is <code>O(n)</code>.</p>
1
2009-10-16T19:04:08Z
[ "python", "performance", "list", "nested-loops" ]
Fastest nested loops over a single list (with elements remove or not)
1,579,771
<p>I am looking for advice about how to parse a single list, using two nested loops, in the fastest way, avoiding doing <code>len(list)^2</code> comparisons, and avoiding duplicate files in groups.</p> <p>More precisely: I have a list of 'file' objects, that each has a timestamp. I want to group the files by their timestamp and a time offset. Ex. starting from a file X, I want to create a group with all the files that have the <code>timestamp &lt; (timestamp(x) + offset)</code>.</p> <p>For this, I did:</p> <pre><code>for file_a in list: temp_group = group() temp_group.add(file_a) list.remove(file_a) for file_b in list: if (file_b.timestamp &lt; (file_a.timestamp + offset)): temp_group.add(file_b) list.remove(file_b) groups.add(temp_group) </code></pre> <p>(ok, the code is more complicated, but this is the main idea)</p> <p>This obviously doesn't work, because I am modifying the list during the loops, and strange things happen :)</p> <p>I thought I have to use copy of 'list' for the loops, but, this doesn't work either:</p> <pre><code>for file_a in list[:]: temp_group = group() temp_group.add(file_a) list.remove(file_a) for file_b in list[:]: if (file_b.timestamp &lt; (file_a.timestamp + offset)): temp_group.add(file_b) list.remove(file_b) groups.add(temp_group) </code></pre> <p>Well.. I know I can do this without removing elements from the list, but then I need to mark the ones that were already 'processed', and I need to check them each time - which is a speed penalty.</p> <p>Can anyone give me some advice about how this can be done in the fastest/best way?</p> <p>Thank you,</p> <p>Alex</p> <p><b>EDIT:</b> I have found an other solution, that doesn't exactly answers the question, but it is what I actually needed (my mistake for asking the question in that way). I am posting this here because it may help someone looking for related issues with loops over lists, in Python.</p> <p>It may not be the fastest (considering the number of 'passes' through the list), but it was quite simple to understand and implement, and it does not require the list to be sorted.</p> <p>The reason for which I avoid sorting is that it may take some more time, and because after I make the first set of groups, some of them will be 'locked', and the unlocked groups will be 'dissolved', and regrouped using a different time offset. (And when dissolving groups, the files order may be changed, and they will require sorting again).</p> <p>Anyway, the solution was to control the loops index myself. If I delete a file from the list, I skip increasing the index (ex: when I delete index "3", the previous index "4" is now "3", and I don't want to increment the loop counter, because I will skip over it). If at that iteration I don't delete any item, then the index is increased normally. Here's the code (with some extras; ignore all that 'bucket' stuff):</p> <pre><code>def regroup(self, time_offset): #create list of files to be used for regrouping regroup_files_list = [] if len(self.groups) == 0: #on first 'regroup', we start with a copy of jpeg_list, so that we do not change it further on regroup_files_list = copy.copy(self.jpeg_list) else: i = 0 while True: try: group = self.groups[i] except IndexError: break if group.is_locked == False: regroup_files_list.extend(group) self.groups.remove(group) continue else: i += 1 bucket_group = FilesGroup() bucket_group.name = c_bucket_group_name while len(regroup_files_list) &gt; 0: #we create groups until there are no files left file_a = regroup_files_list[0] regroup_files_list.remove(file_a) temp_group = FilesGroup() temp_group.start_time = file_a._iso_time temp_group.add(file_a) #manually manage the list index when iterating for file_b, because we're removing files i = 0 while True: try: file_b = regroup_files_list[i] except IndexError: break timediff = file_a._iso_time - file_b._iso_time if timediff.days &lt; 0 or timediff.seconds &lt; 0: timediff = file_b._iso_time - file_a._iso_time if timediff &lt; time_offset: temp_group.add(file_b) regroup_files_list.remove(file_b) continue # :D we reuse the old position, because all elements were shifted to the left else: i += 1 #the index is increased normally self.groups.append(temp_group) #move files to the bucket group, if the temp group is too small if c_bucket_group_enabled == True: if len(temp_group) &lt; c_bucket_group_min_count: for file in temp_group: bucket_group.add(file) temp_group.remove(file) else: self.groups.append(temp_group) if len(bucket_group) &gt; 0: self.groups.append(bucket_group) </code></pre>
1
2009-10-16T18:52:28Z
1,580,317
<p>I'm not exactly sure what you are trying to do - it seems to me that the order of the list will affect the groupings, but your existing code can be modified to work like this.</p> <pre><code>#This is O(n^2) while lst: file_a=lst.pop() temp_group = group() temp_group.add(file_a) while lst file_b=lst[-1] if (file_b.timestamp &lt; (file_a.timestamp + offset)): temp_group.add(lst.pop()) groups.add(temp_group) </code></pre> <p>Does the group have to start at file_a.timestamp?</p> <pre><code># This is O(n) from collections import defaultdict groups=defaultdict(list) # This is why you shouldn't use `list` as a variable name for item in lst: groups[item.timestamp/offset].append(item) </code></pre> <p>Is much simpler way to chop up into groups with similar timestamps</p>
1
2009-10-16T20:48:08Z
[ "python", "performance", "list", "nested-loops" ]
Extremely large Boolean list in Python
1,579,919
<p>I want to create an object in python that is a collection of around 200,000,000 true/false values. So that I can most effectively change or recall any given true/false value, so that I can quickly determine if any given number, like 123,456,000 is true or false or change its value.</p> <p>Is the best way to do this a list? or an array? or a class? or just a long int using bit operations? or something else?</p> <p>I'm a bit noob so you may have to spell things out for me more than if I were asking the question in one of the other languages I know better. Please give me examples of how operating on this object would look.</p> <p>Thanks</p>
5
2009-10-16T19:21:27Z
1,579,927
<p>Have you considered using a lightweight database like SQLite?</p>
3
2009-10-16T19:23:14Z
[ "python", "arrays", "list" ]
Extremely large Boolean list in Python
1,579,919
<p>I want to create an object in python that is a collection of around 200,000,000 true/false values. So that I can most effectively change or recall any given true/false value, so that I can quickly determine if any given number, like 123,456,000 is true or false or change its value.</p> <p>Is the best way to do this a list? or an array? or a class? or just a long int using bit operations? or something else?</p> <p>I'm a bit noob so you may have to spell things out for me more than if I were asking the question in one of the other languages I know better. Please give me examples of how operating on this object would look.</p> <p>Thanks</p>
5
2009-10-16T19:21:27Z
1,579,941
<p>You can try the <a href="http://pypi.python.org/pypi/bitarray"><code>bitarray</code></a> module, or write a similar thing using an <a href="http://docs.python.org/library/array.html"><code>array</code></a> of integers yourself.</p>
12
2009-10-16T19:25:29Z
[ "python", "arrays", "list" ]
Extremely large Boolean list in Python
1,579,919
<p>I want to create an object in python that is a collection of around 200,000,000 true/false values. So that I can most effectively change or recall any given true/false value, so that I can quickly determine if any given number, like 123,456,000 is true or false or change its value.</p> <p>Is the best way to do this a list? or an array? or a class? or just a long int using bit operations? or something else?</p> <p>I'm a bit noob so you may have to spell things out for me more than if I were asking the question in one of the other languages I know better. Please give me examples of how operating on this object would look.</p> <p>Thanks</p>
5
2009-10-16T19:21:27Z
1,580,175
<p>"quickly determine if any given number, like 123,456,000 is" in the "true" set or "false" set.</p> <p>This is what a <a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset" rel="nofollow">set</a> is for.</p> <p>The "true" set is a set of all the numbers.</p> <p>To make a number's boolean flag "true", add it to the true set.</p> <p>To make a number's boolean flag "false", remove it from the true set.</p> <p>Life will be much simpler.</p>
5
2009-10-16T20:12:44Z
[ "python", "arrays", "list" ]
Extremely large Boolean list in Python
1,579,919
<p>I want to create an object in python that is a collection of around 200,000,000 true/false values. So that I can most effectively change or recall any given true/false value, so that I can quickly determine if any given number, like 123,456,000 is true or false or change its value.</p> <p>Is the best way to do this a list? or an array? or a class? or just a long int using bit operations? or something else?</p> <p>I'm a bit noob so you may have to spell things out for me more than if I were asking the question in one of the other languages I know better. Please give me examples of how operating on this object would look.</p> <p>Thanks</p>
5
2009-10-16T19:21:27Z
1,580,187
<p>At first glance, the Python BitVector module sounds like it does exactly what you want. It's available at <a href="http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.5.1.html" rel="nofollow">http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.5.1.html</a> and since it is pure Python code, it will run on any platform with no compiling needed.</p> <p>You mentioned that you need some speed in getting and setting any arbitrary true-false value. For that you need to use a Python array, rather than a list, and if you go to the above URL and browse the source code for BitVector you can see that it does indeed rely on Python arrays.</p> <p>Ideally, you would encapsulate what you are doing in a class that subclasses from BitVector, i.e.</p> <pre><code>class TFValues(BitVector): pass </code></pre> <p>That way you can do things like add a list to contain associated info such as the name of a particular TF value.</p>
1
2009-10-16T20:16:35Z
[ "python", "arrays", "list" ]
Extremely large Boolean list in Python
1,579,919
<p>I want to create an object in python that is a collection of around 200,000,000 true/false values. So that I can most effectively change or recall any given true/false value, so that I can quickly determine if any given number, like 123,456,000 is true or false or change its value.</p> <p>Is the best way to do this a list? or an array? or a class? or just a long int using bit operations? or something else?</p> <p>I'm a bit noob so you may have to spell things out for me more than if I were asking the question in one of the other languages I know better. Please give me examples of how operating on this object would look.</p> <p>Thanks</p>
5
2009-10-16T19:21:27Z
1,580,799
<p>You might also like to try the <a href="http://python-bitstring.googlecode.com" rel="nofollow">bitstring</a> module, which is pure Python. Internally it's all stored as a byte array and the bit masking and shifting is done for you:</p> <pre><code>from bitstring import BitArray # Initialise with two hundred million zero bits s = BitArray(200000000) # Set a few bits to 1 s.set(1, [76, 33, 123456000]) # And test them if s.all([33, 76, 123456000]): pass </code></pre> <p>The other posters are correct though that a simple set might be a better solution to your particular problem.</p>
3
2009-10-16T22:53:28Z
[ "python", "arrays", "list" ]
Python | How to make local variable global, after script execution
1,579,996
<p>Here is the code. What I need to do is find a way to make <code>i</code> global so that upon repeated executions the value of <code>i</code> will increment by 1 instead of being reset to 0 everytime. The code in <code>main</code> is from another script that I embed in 'main' in order to have the trace function work. This is all being done from Java.</p> <pre><code>from __future__ import nested_scopes import sys import time startTime = time.time() timeLimit = 5000 def traceit(frame, event, arg): if event == "line": elapsedTime = ((time.time() - startTime)*1000) if elapsedTime &gt; timeLimit: raise Exception, "The execution time has exceeded the time limit of " + str(timeLimit) + " milliseconds. Script will now terminate" return traceit sys.settrace(traceit) def main______(): try: i+=1 except NameError: i=1 main______() </code></pre>
1
2009-10-16T19:35:48Z
1,580,165
<p>A variable not defined in a function or method, but on the module level in Python is as close as you get to a global variable in Python. You access that from another script by</p> <pre><code>from scriptA import variablename </code></pre> <p>That will execute the script, and give you access to the variable.</p>
0
2009-10-16T20:10:44Z
[ "python", "variables", "interpreter", "global", "local" ]
Python | How to make local variable global, after script execution
1,579,996
<p>Here is the code. What I need to do is find a way to make <code>i</code> global so that upon repeated executions the value of <code>i</code> will increment by 1 instead of being reset to 0 everytime. The code in <code>main</code> is from another script that I embed in 'main' in order to have the trace function work. This is all being done from Java.</p> <pre><code>from __future__ import nested_scopes import sys import time startTime = time.time() timeLimit = 5000 def traceit(frame, event, arg): if event == "line": elapsedTime = ((time.time() - startTime)*1000) if elapsedTime &gt; timeLimit: raise Exception, "The execution time has exceeded the time limit of " + str(timeLimit) + " milliseconds. Script will now terminate" return traceit sys.settrace(traceit) def main______(): try: i+=1 except NameError: i=1 main______() </code></pre>
1
2009-10-16T19:35:48Z
1,581,587
<p>The following statement declares <code>i</code> as global variable:</p> <pre><code>global i </code></pre>
0
2009-10-17T06:39:57Z
[ "python", "variables", "interpreter", "global", "local" ]
Python | How to make local variable global, after script execution
1,579,996
<p>Here is the code. What I need to do is find a way to make <code>i</code> global so that upon repeated executions the value of <code>i</code> will increment by 1 instead of being reset to 0 everytime. The code in <code>main</code> is from another script that I embed in 'main' in order to have the trace function work. This is all being done from Java.</p> <pre><code>from __future__ import nested_scopes import sys import time startTime = time.time() timeLimit = 5000 def traceit(frame, event, arg): if event == "line": elapsedTime = ((time.time() - startTime)*1000) if elapsedTime &gt; timeLimit: raise Exception, "The execution time has exceeded the time limit of " + str(timeLimit) + " milliseconds. Script will now terminate" return traceit sys.settrace(traceit) def main______(): try: i+=1 except NameError: i=1 main______() </code></pre>
1
2009-10-16T19:35:48Z
1,582,917
<p>It's unfortunate that you've edited the question so heavily that peoples' answers to it appear nonsensical.</p> <p>There are numerous ways to create a variable scoped within a function whose value remains unchanged from call to call. All of them take advantage of the fact that functions are first-class objects, which means that they can have attributes. For instance:</p> <pre><code>def f(x): if not hasattr(f, "i"): setattr(f, "i", 0) f.i += x return f.i </code></pre> <p>There's also the hack of using a list as a default value for an argument, and then never providing a value for the argument when you call the function:</p> <pre><code>def f(x, my_list=[0]): my_list[0] = my_list[0] + x return my_list[0] </code></pre> <p>...but I wouldn't recommend using that unless you understand why it works, and maybe not even then.</p>
2
2009-10-17T18:44:03Z
[ "python", "variables", "interpreter", "global", "local" ]
Python | How to make local variable global, after script execution
1,579,996
<p>Here is the code. What I need to do is find a way to make <code>i</code> global so that upon repeated executions the value of <code>i</code> will increment by 1 instead of being reset to 0 everytime. The code in <code>main</code> is from another script that I embed in 'main' in order to have the trace function work. This is all being done from Java.</p> <pre><code>from __future__ import nested_scopes import sys import time startTime = time.time() timeLimit = 5000 def traceit(frame, event, arg): if event == "line": elapsedTime = ((time.time() - startTime)*1000) if elapsedTime &gt; timeLimit: raise Exception, "The execution time has exceeded the time limit of " + str(timeLimit) + " milliseconds. Script will now terminate" return traceit sys.settrace(traceit) def main______(): try: i+=1 except NameError: i=1 main______() </code></pre>
1
2009-10-16T19:35:48Z
1,615,913
<p>Your statement "embed in 'main' in order to have the trace function work" is quite ambiguous, but it sounds like what you want is to:</p> <ul> <li>take input from a user</li> <li>execute it in some persistent context</li> <li>abort execution if it takes too long</li> </ul> <p>For this sort of thing, use "exec". An example:</p> <pre><code>import sys import time def timeout(frame,event,arg): if event == 'line': elapsed = (time.time()-start) * 1000 code = """ try: i += 1 except NameError: i = 1 print 'current i:',i """ globals = {} for ii in range(3): start = time.time() sys.settrace(timeout) exec code in globals print 'final i:',globals['i'] </code></pre>
0
2009-10-23T21:11:18Z
[ "python", "variables", "interpreter", "global", "local" ]
Python | How to make local variable global, after script execution
1,579,996
<p>Here is the code. What I need to do is find a way to make <code>i</code> global so that upon repeated executions the value of <code>i</code> will increment by 1 instead of being reset to 0 everytime. The code in <code>main</code> is from another script that I embed in 'main' in order to have the trace function work. This is all being done from Java.</p> <pre><code>from __future__ import nested_scopes import sys import time startTime = time.time() timeLimit = 5000 def traceit(frame, event, arg): if event == "line": elapsedTime = ((time.time() - startTime)*1000) if elapsedTime &gt; timeLimit: raise Exception, "The execution time has exceeded the time limit of " + str(timeLimit) + " milliseconds. Script will now terminate" return traceit sys.settrace(traceit) def main______(): try: i+=1 except NameError: i=1 main______() </code></pre>
1
2009-10-16T19:35:48Z
11,000,969
<p>You need to do two things to make your variable global.</p> <ol> <li>Define the variable at the global scope, that is outside the function.</li> <li>Use the global statement in the function so that Python knows that this function should use the larger scoped variable.</li> </ol> <p>Example:</p> <pre><code>i = 0 def inc_i(): global i i += 1 </code></pre>
2
2012-06-12T16:39:10Z
[ "python", "variables", "interpreter", "global", "local" ]
Find time until a date in Python
1,580,227
<p>What's the best way to find the time until a date. I would like to know the years, months, days and hours. </p> <p>I was hoping somebody had a nice function. I want to do something like: This comment was posted 2month and three days ago or this comment was posted 1year 5months ago.</p>
3
2009-10-16T20:28:25Z
1,580,250
<p><a href="http://docs.python.org/library/datetime.html" rel="nofollow"><code>datetime</code></a> module, <code>datetime</code> and <code>timedelta</code> objects, it will give you days and seconds.</p> <pre><code>In [5]: datetime.datetime(2009, 10, 19) - datetime.datetime.now() Out[5]: datetime.timedelta(2, 5274, 16000) In [6]: td = datetime.datetime(2009, 10, 19) - datetime.datetime.now() In [7]: td.days Out[7]: 2 In [8]: td.seconds Out[8]: 5262 </code></pre>
3
2009-10-16T20:34:17Z
[ "python" ]
Find time until a date in Python
1,580,227
<p>What's the best way to find the time until a date. I would like to know the years, months, days and hours. </p> <p>I was hoping somebody had a nice function. I want to do something like: This comment was posted 2month and three days ago or this comment was posted 1year 5months ago.</p>
3
2009-10-16T20:28:25Z
1,580,503
<p>You should use <a href="http://labix.org/python-dateutil">dateutil</a>.relativedelta.</p> <pre><code>from dateutil.relativedelta import relativedelta import datetime today = datetime.date.today() rd = relativedelta(today, datetime.date(2001,1,1)) print "comment created %(years)d years, %(months)d months, %(days)d days ago" % rd.__dict__ </code></pre>
6
2009-10-16T21:22:11Z
[ "python" ]
Find time until a date in Python
1,580,227
<p>What's the best way to find the time until a date. I would like to know the years, months, days and hours. </p> <p>I was hoping somebody had a nice function. I want to do something like: This comment was posted 2month and three days ago or this comment was posted 1year 5months ago.</p>
3
2009-10-16T20:28:25Z
1,580,531
<p>I was looking for something more like this ... which took some hard work to find. </p> <pre><code>import datetime SECOND = 1 MINUTE = 60 * SECOND HOUR = 60 * MINUTE DAY = 24 * HOUR MONTH = 30 * DAY def get_relative_time(dt): now = datetime.datetime.now() delta_time = dt - now delta = delta_time.days * DAY + delta_time.seconds minutes = delta / MINUTE hours = delta / HOUR days = delta / DAY if delta &lt; 0: return "already happened" if delta &lt; 1 * MINUTE: if delta == 1: return "one second to go" else: return str(delta) + " seconds to go" if delta &lt; 2 * MINUTE: return "a minute ago" if delta &lt; 45 * MINUTE: return str(minutes) + " minutes to go" if delta &lt; 90 * MINUTE: return "an hour ago" if delta &lt; 24 * HOUR: return str(hours) + " hours to go" if delta &lt; 48 * HOUR: return "yesterday" if delta &lt; 30 * DAY: return str(days) + " days to go" if delta &lt; 12 * MONTH: months = delta / MONTH if months &lt;= 1: return "one month to go" else: return str(months) + " months to go" else: years = days / 365.0 if years &lt;= 1: return "one year to go" else: return str(years) + " years to go" </code></pre>
1
2009-10-16T21:28:29Z
[ "python" ]
Find time until a date in Python
1,580,227
<p>What's the best way to find the time until a date. I would like to know the years, months, days and hours. </p> <p>I was hoping somebody had a nice function. I want to do something like: This comment was posted 2month and three days ago or this comment was posted 1year 5months ago.</p>
3
2009-10-16T20:28:25Z
18,368,610
<p>Let's asume you have the future datetime in a variable named eta:</p> <pre><code>(eta - datetime.datetime.now()).total_seconds() </code></pre> <p>Datetime difference results in a timedelta object, which happens to implement a method named total_seconds. That's it :)</p>
1
2013-08-21T22:15:03Z
[ "python" ]
Find time until a date in Python
1,580,227
<p>What's the best way to find the time until a date. I would like to know the years, months, days and hours. </p> <p>I was hoping somebody had a nice function. I want to do something like: This comment was posted 2month and three days ago or this comment was posted 1year 5months ago.</p>
3
2009-10-16T20:28:25Z
37,242,432
<p>may be you want something like this:</p> <pre><code>import datetime today = datetime.date.today() futdate = datetime.date(2016, 8, 10) now = datetime.datetime.now() mnight = now.replace(hour=0, minute=0, second=0, microsecond=0) seconds = (mnight - now).seconds days = (futdate - today).days hms = str(datetime.timedelta(seconds=seconds)) print ("%d days %s" % (days, hms)) </code></pre>
0
2016-05-15T18:57:39Z
[ "python" ]
Mixing Python web platforms PHP, e.g. - Mediawiki, Wordpress, etc
1,580,245
<p>Is anyone developing application integrated with Mediawiki - using Django or other Python web development platforms using mod_wsgi? </p> <p>Would be very interested to find out what has been done in this direction and maybe there is some code available for re-use. (I've started creating wiki extensions working with MW database in python whose output is injected via Apache's include virtual directive. it works ok, but a bit slow so far - maybe I can optimize it though)</p> <p>Basically I would like to have certain parts of displayed wiki pages be prepared with python.</p> <p>Has anyone reproduced common MW skins in python templates?</p> <p><strong>edit:</strong> found this nice video showing how PyCon site does just that (not with MW though) - using custom template loader</p> <p><a href="http://showmedo.com/videos/video?name=pythonNapleonePyConTech2&amp;fromSeriesID=54" rel="nofollow">http://showmedo.com/videos/video?name=pythonNapleonePyConTech2&amp;fromSeriesID=54</a></p> <p>Thanks.</p>
1
2009-10-16T20:34:00Z
1,580,261
<p>Can't you use Mediawiki HTTP based API? Loose coupling is great.</p>
1
2009-10-16T20:36:19Z
[ "php", "python", "wordpress", "mediawiki", "mod-wsgi" ]
Mixing Python web platforms PHP, e.g. - Mediawiki, Wordpress, etc
1,580,245
<p>Is anyone developing application integrated with Mediawiki - using Django or other Python web development platforms using mod_wsgi? </p> <p>Would be very interested to find out what has been done in this direction and maybe there is some code available for re-use. (I've started creating wiki extensions working with MW database in python whose output is injected via Apache's include virtual directive. it works ok, but a bit slow so far - maybe I can optimize it though)</p> <p>Basically I would like to have certain parts of displayed wiki pages be prepared with python.</p> <p>Has anyone reproduced common MW skins in python templates?</p> <p><strong>edit:</strong> found this nice video showing how PyCon site does just that (not with MW though) - using custom template loader</p> <p><a href="http://showmedo.com/videos/video?name=pythonNapleonePyConTech2&amp;fromSeriesID=54" rel="nofollow">http://showmedo.com/videos/video?name=pythonNapleonePyConTech2&amp;fromSeriesID=54</a></p> <p>Thanks.</p>
1
2009-10-16T20:34:00Z
1,580,513
<p>There are so many different ways to do this.</p> <ul> <li>You can make a mediawiki skin that uses iframes and inserts things from a Python server.</li> <li>You can write a python app that accesses mediawikis data somehow and outputs it.</li> <li>You can put a Python server in front that extracts the content from mediawiki and put's it into a page that is otherwise generated from Python.</li> <li>You can use deliverence to skin mediawiki, and use it's pyref functionality to call pythonscripts and insert that into the skin (I think, I haven't done that myself).</li> </ul> <p>Which way is best for you completely depends.</p>
2
2009-10-16T21:24:54Z
[ "php", "python", "wordpress", "mediawiki", "mod-wsgi" ]
What's the best way to search for a Python dictionary value in a list of dictionaries?
1,580,270
<p>I have the following data structure:</p> <pre><code> data = [ {'site': 'Stackoverflow', 'id': 1}, {'site': 'Superuser', 'id': 2}, {'site': 'Serverfault', 'id': 3} ] </code></pre> <p>I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain a dictionary with site = 'Superuser' and return True/False. I can do the above the usual way of looping over each item and comparing them. Is there an alternative way to achieve a search?</p>
12
2009-10-16T20:38:11Z
1,580,298
<p>Lists absolutely require loops. That's what lists are for.</p> <p>To avoid looping you have to avoid lists.</p> <p>You want dictionaries of search keys and objects.</p> <pre><code>sites = dict( (d['site'],d) for d in data ) ids = dict( (d['id'],d] for d in data ) </code></pre> <p>Now you can find the item associated with 'Superuser' with <code>sites["Superuser"]</code> using a hashed lookup instead of a loop.</p>
4
2009-10-16T20:44:42Z
[ "python" ]
What's the best way to search for a Python dictionary value in a list of dictionaries?
1,580,270
<p>I have the following data structure:</p> <pre><code> data = [ {'site': 'Stackoverflow', 'id': 1}, {'site': 'Superuser', 'id': 2}, {'site': 'Serverfault', 'id': 3} ] </code></pre> <p>I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain a dictionary with site = 'Superuser' and return True/False. I can do the above the usual way of looping over each item and comparing them. Is there an alternative way to achieve a search?</p>
12
2009-10-16T20:38:11Z
1,580,303
<pre><code>any(d['site'] == 'Superuser' for d in data) </code></pre>
23
2009-10-16T20:45:26Z
[ "python" ]
What's the best way to search for a Python dictionary value in a list of dictionaries?
1,580,270
<p>I have the following data structure:</p> <pre><code> data = [ {'site': 'Stackoverflow', 'id': 1}, {'site': 'Superuser', 'id': 2}, {'site': 'Serverfault', 'id': 3} ] </code></pre> <p>I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain a dictionary with site = 'Superuser' and return True/False. I can do the above the usual way of looping over each item and comparing them. Is there an alternative way to achieve a search?</p>
12
2009-10-16T20:38:11Z
1,580,304
<pre><code>filter( lambda x: x['site']=='Superuser', data ) </code></pre>
7
2009-10-16T20:45:26Z
[ "python" ]
What's the best way to search for a Python dictionary value in a list of dictionaries?
1,580,270
<p>I have the following data structure:</p> <pre><code> data = [ {'site': 'Stackoverflow', 'id': 1}, {'site': 'Superuser', 'id': 2}, {'site': 'Serverfault', 'id': 3} ] </code></pre> <p>I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain a dictionary with site = 'Superuser' and return True/False. I can do the above the usual way of looping over each item and comparing them. Is there an alternative way to achieve a search?</p>
12
2009-10-16T20:38:11Z
1,580,314
<p>I'm not sure of the python syntax, but it might work for you this way. While building your primary data structure, also build a parallel one that's a hash or associative array keyed on the site name; then to see if a given site exists you attempt a lookup in the hash with the site name. If it succeeds, you know there's a record in your data structure for that site and you've done it in the time of the hash lookup (likely O(1) or O(log2(n)) depending on the hash technique) instead of the O(n/2) of the list traversal.</p> <p>(updated while writing: this is pretty much what S.Lott posted)</p>
1
2009-10-16T20:48:00Z
[ "python" ]
Facebook Connect help
1,580,504
<p>According to the Facebook API documentation, most of the work is handled through javascript. </p> <p>That means that all the processing is done, and then the front end checks if the user is connected to Facebook/authorized. right?</p> <p><strong>My question is:</strong></p> <p>Suppose a user goes to my site for the first time ever. He clicks on "facebook connect". The javascript verifies him as authentic, and it "redirects" to another page on my server. From then on, how do I know that the user is actually authenticated to my website, since everything is done on frontend? </p> <p><strong>I think this is correct, but aren't there some security issues..:</strong></p> <p>-After user clicks Login, Facebook redirects to a page on my site. AND they also create a cookie with a specific "Facebook ID" that is retrieved only from this user. My backened will "read" the cookie and grab that ID...and then associate it to my userID. </p> <p>If that is correct...then it doesn't make sense. What if people steal other people's "facebook ID" and then forge the cookie? And then my backend sees the cookie and thinks it's the real user...?</p> <p><strong>Am I confused? If I am confused, please help me re-organize and tell me how it's like.</strong></p>
1
2009-10-16T21:22:53Z
1,580,650
<p>Facebook Connect uses a clever (or insane, depending on your point of view) hack to achieve cross-site communication between your site and Facebook's authentication system from within the browser.</p> <p>The way it works is as follows:</p> <ol> <li>Your site includes a very simple static HTML file, known as the cross-domain communications channel. This file is called <code>xd_receiver.htm</code> in the FB docs, but it can be named anything you like.</li> <li>Your site's login page includes a reference to the Javascript library hosted on Facebook's server.</li> <li>When a user logs in via the "Connect" button, it calls a function in Facebook's JS API which pops up a login dialog. This login box has an invisible <code>iframe</code> in which the cross-domain communications file is loaded.</li> <li>The user fills out the form and submits it, posting the form to Facebook.</li> <li>Facebook checks the login. If it's successful, it communicates this to your site. Here's where that cross-domain stuff comes in: <ol> <li>Because of cross-domain security policies, Facebook's login window can not inspect the DOM tree for documents hosted on your server. But the login window <i>can</i> update the <code>src</code> element of any <code>iframe</code> within it, and this is used to communicate with the cross-domain communications file hosted on your page.</li> <li>When the cross-domain communications file receives a communication indicating that the login was successful, it uses Javascript to set some cookies containing the user's ID and session. Since this file lives on your server, those cookies have your domain and your backend can receive them.</li> </ol></li> <li>Any further communication in Facebook's direction can be accomplished by inserting another nested <code>iframe</code> in the other <code>iframe</code> -- this second-level <code>iframe</code> lives on Facebook's server instead of yours.</li> </ol> <p>The cookies are secure (in theory) because the data is signed with the secret key that Facebook generated for you when you signed up for the developer program. The JS library uses your public key (the "API key") to validate the cookies.</p> <p>Theoretically, Facebook's Javascript library handles this all automatically once you've set everything up. In practice, I've found it doesn't always work exactly smoothly.</p> <p>For a more detailed explanation of the mechanics of cross-domain communication using <code>iframe</code>s, see <a href="http://msdn.microsoft.com/en-us/architecture/bb735305.aspx" rel="nofollow">this article</a> from MSDN.</p>
6
2009-10-16T21:54:32Z
[ "javascript", "python", "facebook" ]
Facebook Connect help
1,580,504
<p>According to the Facebook API documentation, most of the work is handled through javascript. </p> <p>That means that all the processing is done, and then the front end checks if the user is connected to Facebook/authorized. right?</p> <p><strong>My question is:</strong></p> <p>Suppose a user goes to my site for the first time ever. He clicks on "facebook connect". The javascript verifies him as authentic, and it "redirects" to another page on my server. From then on, how do I know that the user is actually authenticated to my website, since everything is done on frontend? </p> <p><strong>I think this is correct, but aren't there some security issues..:</strong></p> <p>-After user clicks Login, Facebook redirects to a page on my site. AND they also create a cookie with a specific "Facebook ID" that is retrieved only from this user. My backened will "read" the cookie and grab that ID...and then associate it to my userID. </p> <p>If that is correct...then it doesn't make sense. What if people steal other people's "facebook ID" and then forge the cookie? And then my backend sees the cookie and thinks it's the real user...?</p> <p><strong>Am I confused? If I am confused, please help me re-organize and tell me how it's like.</strong></p>
1
2009-10-16T21:22:53Z
1,631,255
<p>Please someone correct me if I'm wrong - as I am also trying to figure all this stuff out myself. My understanding with the security of the cookies is that there is also a cookie which is a special signature cookie. This cookie is created by combining the data of the other cookies, adding your application secret that only you and FB know, and the result MD5-Hashed. You can then test this hash server-side, which could not easily be duplicated by a hacker, to make sure the data can be trusted as coming from FB.</p> <p>A more charming explaination can be found <a href="http://wiki.developers.facebook.com/index.php/Verifying%5FThe%5FSignature" rel="nofollow">here</a> - scroll about halfway down the page. </p>
0
2009-10-27T14:38:49Z
[ "javascript", "python", "facebook" ]
Facebook Connect help
1,580,504
<p>According to the Facebook API documentation, most of the work is handled through javascript. </p> <p>That means that all the processing is done, and then the front end checks if the user is connected to Facebook/authorized. right?</p> <p><strong>My question is:</strong></p> <p>Suppose a user goes to my site for the first time ever. He clicks on "facebook connect". The javascript verifies him as authentic, and it "redirects" to another page on my server. From then on, how do I know that the user is actually authenticated to my website, since everything is done on frontend? </p> <p><strong>I think this is correct, but aren't there some security issues..:</strong></p> <p>-After user clicks Login, Facebook redirects to a page on my site. AND they also create a cookie with a specific "Facebook ID" that is retrieved only from this user. My backened will "read" the cookie and grab that ID...and then associate it to my userID. </p> <p>If that is correct...then it doesn't make sense. What if people steal other people's "facebook ID" and then forge the cookie? And then my backend sees the cookie and thinks it's the real user...?</p> <p><strong>Am I confused? If I am confused, please help me re-organize and tell me how it's like.</strong></p>
1
2009-10-16T21:22:53Z
1,790,321
<p>Same issues here, and I think Scott is closer to the solution.</p> <p>Also Im using "http://developers.facebook.com/docs/?u=facebook.jslib-alpha.FB.init" there open source js framework. So things are a little different.</p> <p>For me, via the opensource js framework, facebook provides and sets a session on my site with a signature. So what I am thinking is to recreate that signature on my side. - if they both match then the user is who he says he is.</p> <p>So basically if a user wanted to save something to my database, grab the session signature set up by facebook and recreate that signature with php and validate it against the one facebook gave me?</p> <pre><code>if($_SESSION['facebookSignature'] == reGeneratedSignature){ // save to database }else{ // go away I don't trust you } </code></pre> <p><strong>But how do you regenerate that signature?</strong> preferably without making more calls to Facebook? </p>
0
2009-11-24T14:10:53Z
[ "javascript", "python", "facebook" ]
Key compare using dictionary
1,580,563
<p>I have a file with the following structure:</p> <p>system.action.webMessage=An error has happened during web access. system.action.okMessage=Everything is ok. core.alert.inform=Error number 5512.</p> <p>I need a script to compare the keys in 2 files with this structure. I was working in a script to convert the file into a dictionary and use the dictionary structure to compare de keys (strings before '=') in both files and tells me with value from which key is equal.</p> <pre><code>file = open('system.keys','r') lines = [] for i in file: lines.append(i.split('=')) dic = {} for k, v in lines: dic[k] = v </code></pre> <p>But I'm receiving the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: too many values to unpack </code></pre> <p>Any one have some clue or help? :( I've try lots of things that I found in google but no solution.</p>
0
2009-10-16T21:36:09Z
1,580,589
<p>If a line has more than one '=' in it, you'll get a list with more than two items, while your for-loop (<code>for k, v in items</code>) expects that each list will only have two items.</p> <p>Try using <code>i.split('=', 1)</code>.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; "a=b=c".split('=') ['a', 'b', 'c'] &gt;&gt;&gt; "a=b=c".split('=', 1) ['a', 'b=c'] </code></pre>
0
2009-10-16T21:42:29Z
[ "python", "file", "list", "dictionary", "compare" ]
Key compare using dictionary
1,580,563
<p>I have a file with the following structure:</p> <p>system.action.webMessage=An error has happened during web access. system.action.okMessage=Everything is ok. core.alert.inform=Error number 5512.</p> <p>I need a script to compare the keys in 2 files with this structure. I was working in a script to convert the file into a dictionary and use the dictionary structure to compare de keys (strings before '=') in both files and tells me with value from which key is equal.</p> <pre><code>file = open('system.keys','r') lines = [] for i in file: lines.append(i.split('=')) dic = {} for k, v in lines: dic[k] = v </code></pre> <p>But I'm receiving the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: too many values to unpack </code></pre> <p>Any one have some clue or help? :( I've try lots of things that I found in google but no solution.</p>
0
2009-10-16T21:36:09Z
1,580,631
<pre><code>file = open('system.keys','r') lines = [] for i in file: lines.append(i.partition('=')) dic = {} for k,_,v in lines: dic[k] = v </code></pre> <p>or using split</p> <pre><code>myfile = open('system.keys','r') dic = dict(i.split("=",1) for i in myfile) </code></pre> <p>since <code>dict()</code> knows how to make a dictionary from a sequence of <code>(key,value)</code> pairs</p>
2
2009-10-16T21:51:32Z
[ "python", "file", "list", "dictionary", "compare" ]
How to concatenate multiple Python source files into a single file?
1,580,746
<p><em>(Assume that: application start-up time is absolutely critical; my application is started a lot; my application runs in an environment in which importing is slower than usual; many files need to be imported; and compilation to <code>.pyc</code> files is not available.)</em></p> <p>I would like to concatenate all the Python source files that define a collection of modules into a single new Python source file.</p> <p>I would like the result of importing the new file to be as if I imported one of the original files (which would then import some more of the original files, and so on).</p> <p>Is this possible?</p> <p>Here is a rough, manual simulation of what a tool might produce when fed the source files for modules 'bar' and 'baz'. You would run such a tool prior to deploying the code.</p> <pre><code>__file__ = 'foo.py' def _module(_name): import types mod = types.ModuleType(name) mod.__file__ = __file__ sys.modules[module_name] = mod return mod def _bar_module(): def hello(): print 'Hello World! BAR' mod = create_module('foo.bar') mod.hello = hello return mod bar = _bar_module() del _bar_module def _baz_module(): def hello(): print 'Hello World! BAZ' mod = create_module('foo.bar.baz') mod.hello = hello return mod baz = _baz_module() del _baz_module </code></pre> <p>And now you can:</p> <pre><code>from foo.bar import hello hello() </code></pre> <p>This code doesn't take account of things like import statements and dependencies. Is there any existing code that will assemble source files using this, or some other technique?</p> <p>This is very similar idea to tools being used to assemble and optimise JavaScript files before sending to the browser, where the latency of multiple HTTP requests hurts performance. In this Python case, it's the latency of importing hundreds of Python source files at startup which hurts.</p>
2
2009-10-16T22:30:50Z
1,580,782
<p>I think that due to the precompilation of Python files and some system caching, the speed up that you'll eventually get won't be measurable.</p>
1
2009-10-16T22:47:44Z
[ "python", "google-app-engine", "import", "module", "concatenation" ]
How to concatenate multiple Python source files into a single file?
1,580,746
<p><em>(Assume that: application start-up time is absolutely critical; my application is started a lot; my application runs in an environment in which importing is slower than usual; many files need to be imported; and compilation to <code>.pyc</code> files is not available.)</em></p> <p>I would like to concatenate all the Python source files that define a collection of modules into a single new Python source file.</p> <p>I would like the result of importing the new file to be as if I imported one of the original files (which would then import some more of the original files, and so on).</p> <p>Is this possible?</p> <p>Here is a rough, manual simulation of what a tool might produce when fed the source files for modules 'bar' and 'baz'. You would run such a tool prior to deploying the code.</p> <pre><code>__file__ = 'foo.py' def _module(_name): import types mod = types.ModuleType(name) mod.__file__ = __file__ sys.modules[module_name] = mod return mod def _bar_module(): def hello(): print 'Hello World! BAR' mod = create_module('foo.bar') mod.hello = hello return mod bar = _bar_module() del _bar_module def _baz_module(): def hello(): print 'Hello World! BAZ' mod = create_module('foo.bar.baz') mod.hello = hello return mod baz = _baz_module() del _baz_module </code></pre> <p>And now you can:</p> <pre><code>from foo.bar import hello hello() </code></pre> <p>This code doesn't take account of things like import statements and dependencies. Is there any existing code that will assemble source files using this, or some other technique?</p> <p>This is very similar idea to tools being used to assemble and optimise JavaScript files before sending to the browser, where the latency of multiple HTTP requests hurts performance. In this Python case, it's the latency of importing hundreds of Python source files at startup which hurts.</p>
2
2009-10-16T22:30:50Z
1,581,045
<p>If this is on google app engine as the tags indicate, make sure you are using this idiom</p> <pre><code>def main(): #do stuff if __name__ == '__main__': main() </code></pre> <p>Because GAE doesn't restart your app every request unless the .py has changed, it just runs <code>main()</code> again.</p> <p>This trick lets you write CGI style apps without the startup performance hit</p> <p><a href="http://code.google.com/appengine/docs/python/runtime.html#App%5FCaching" rel="nofollow">AppCaching</a></p> <blockquote> <p>If a handler script provides a main() routine, the runtime environment also caches the script. Otherwise, the handler script is loaded for every request.</p> </blockquote>
3
2009-10-17T00:34:22Z
[ "python", "google-app-engine", "import", "module", "concatenation" ]
How to concatenate multiple Python source files into a single file?
1,580,746
<p><em>(Assume that: application start-up time is absolutely critical; my application is started a lot; my application runs in an environment in which importing is slower than usual; many files need to be imported; and compilation to <code>.pyc</code> files is not available.)</em></p> <p>I would like to concatenate all the Python source files that define a collection of modules into a single new Python source file.</p> <p>I would like the result of importing the new file to be as if I imported one of the original files (which would then import some more of the original files, and so on).</p> <p>Is this possible?</p> <p>Here is a rough, manual simulation of what a tool might produce when fed the source files for modules 'bar' and 'baz'. You would run such a tool prior to deploying the code.</p> <pre><code>__file__ = 'foo.py' def _module(_name): import types mod = types.ModuleType(name) mod.__file__ = __file__ sys.modules[module_name] = mod return mod def _bar_module(): def hello(): print 'Hello World! BAR' mod = create_module('foo.bar') mod.hello = hello return mod bar = _bar_module() del _bar_module def _baz_module(): def hello(): print 'Hello World! BAZ' mod = create_module('foo.bar.baz') mod.hello = hello return mod baz = _baz_module() del _baz_module </code></pre> <p>And now you can:</p> <pre><code>from foo.bar import hello hello() </code></pre> <p>This code doesn't take account of things like import statements and dependencies. Is there any existing code that will assemble source files using this, or some other technique?</p> <p>This is very similar idea to tools being used to assemble and optimise JavaScript files before sending to the browser, where the latency of multiple HTTP requests hurts performance. In this Python case, it's the latency of importing hundreds of Python source files at startup which hurts.</p>
2
2009-10-16T22:30:50Z
1,581,973
<p>Doing this is unlikely to yield any performance benefits. You're still importing the same amount of Python code, just in fewer modules - and you're sacrificing all modularity for it.</p> <p>A better approach would be to modify your code and/or libraries to only import things when needed, so that a minimum of required code is loaded for each request.</p>
0
2009-10-17T11:03:40Z
[ "python", "google-app-engine", "import", "module", "concatenation" ]
How to concatenate multiple Python source files into a single file?
1,580,746
<p><em>(Assume that: application start-up time is absolutely critical; my application is started a lot; my application runs in an environment in which importing is slower than usual; many files need to be imported; and compilation to <code>.pyc</code> files is not available.)</em></p> <p>I would like to concatenate all the Python source files that define a collection of modules into a single new Python source file.</p> <p>I would like the result of importing the new file to be as if I imported one of the original files (which would then import some more of the original files, and so on).</p> <p>Is this possible?</p> <p>Here is a rough, manual simulation of what a tool might produce when fed the source files for modules 'bar' and 'baz'. You would run such a tool prior to deploying the code.</p> <pre><code>__file__ = 'foo.py' def _module(_name): import types mod = types.ModuleType(name) mod.__file__ = __file__ sys.modules[module_name] = mod return mod def _bar_module(): def hello(): print 'Hello World! BAR' mod = create_module('foo.bar') mod.hello = hello return mod bar = _bar_module() del _bar_module def _baz_module(): def hello(): print 'Hello World! BAZ' mod = create_module('foo.bar.baz') mod.hello = hello return mod baz = _baz_module() del _baz_module </code></pre> <p>And now you can:</p> <pre><code>from foo.bar import hello hello() </code></pre> <p>This code doesn't take account of things like import statements and dependencies. Is there any existing code that will assemble source files using this, or some other technique?</p> <p>This is very similar idea to tools being used to assemble and optimise JavaScript files before sending to the browser, where the latency of multiple HTTP requests hurts performance. In this Python case, it's the latency of importing hundreds of Python source files at startup which hurts.</p>
2
2009-10-16T22:30:50Z
1,584,678
<p>Without dealing with the question, whether or not this technique would boost up things at your environment, say you are right, here is what I would have done.</p> <p>I would make a list of all my modules e.g. <code>my_files = ['foo', 'bar', 'baz']</code></p> <p>I would then use os.path utilities to read all lines in all files under the source directory and writes them all into a new file, filtering all <code>import foo|bar|baz</code> lines since all code is now within a single file.</p> <p>Of curse, at last adding the <code>main()</code> from <code>__init__.py</code> (if there is such) at the tail of the file.</p>
0
2009-10-18T11:46:03Z
[ "python", "google-app-engine", "import", "module", "concatenation" ]
Apache2 + RewriteMap + Python -- when returning 'NULL', apache hangs
1,580,780
<p>[SOLVED: See solution below.]</p> <p>I'm having a problem writing a <code>RewriteMap</code> program (using Python). I have a <code>RewriteMap</code> directive pointing to a Python script which determines if the requested URL needs to be redirected elsewhere.</p> <p>When the script outputs a string terminated by a linebreak, Apache redirects accordingly. However, when the script outputs <code>NULL</code> (with no linebreak), Apache hangs and subsequent HTTP requests are effectively ignored.</p> <p>The error log shows no errors. The rewrite log only shows a <code>pass through</code> followed by a <code>redirect</code> when successful, then only <code>pass through</code> when <code>NULL</code> is returned by the script. Subsequent requests also only show <code>pass through</code>.</p> <p>Additionally, replacing <code>stdout</code> with <code>os.fdopen(sys.stdout.fileno(), 'w', 0)</code> to set buffer length to zero did not help.</p> <p>Any help would be greatly appreciated. Thank you in advance.</p> <h3>/etc/apache2/httpd.conf</h3> <pre><code>[...] RewriteLock /tmp/apache_rewrite.lock </code></pre> <h3>/etc/apache2/sites-available/default</h3> <pre><code>&lt;VirtualHost *:80&gt; [...] RewriteEngine on RewriteLogLevel 1 RewriteLog /var/www/logs/rewrite.log RewriteMap remap prg:/var/www/remap.py [...] &lt;/VirtualHost&gt; </code></pre> <h3>/var/www/webroot/.htaccess</h3> <pre><code>RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*_.*) /${remap:$1} [R=301] </code></pre> <h3>/var/www/remap.py</h3> <pre><code>#!/usr/bin/python import sys def getRedirect(str): new_url = None # if url needs to be redirected, put this value in new_url # otherwise new_url remains None return new_url while True: request = sys.stdin.readline().strip() response = getRedirect(request) if response: sys.stdout.write(response + '\n') else: sys.stdout.write('NULL') sys.stdout.flush() </code></pre>
2
2009-10-16T22:47:32Z
1,580,791
<p>You have to return a single newline, not 'NULL'. </p> <p>Apache waits for a newline to know when the URL to be rewrite to ends. If your script sends no newline, Apache waits forever.</p> <p>So just change <code>return ('NULL')</code> to <code>return ('NULL\n')</code>, this will then redirect to /. If you don't want this to happen, have the program to return the URL you want when there's no match in the map.</p> <p>If you want not to redirect when there's no match I would:</p> <pre><code>RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond (${remap:$1}) !NULL RewriteRule (.*_.*) /%1 [R=301] </code></pre> <p>Use a match in the RewriteCond (this would work with <em>NULL</em> as well, of course). But given your problem, this looks like the proper solution.</p>
5
2009-10-16T22:52:05Z
[ "python", "apache2", "rewrite", "apache" ]
Apache2 + RewriteMap + Python -- when returning 'NULL', apache hangs
1,580,780
<p>[SOLVED: See solution below.]</p> <p>I'm having a problem writing a <code>RewriteMap</code> program (using Python). I have a <code>RewriteMap</code> directive pointing to a Python script which determines if the requested URL needs to be redirected elsewhere.</p> <p>When the script outputs a string terminated by a linebreak, Apache redirects accordingly. However, when the script outputs <code>NULL</code> (with no linebreak), Apache hangs and subsequent HTTP requests are effectively ignored.</p> <p>The error log shows no errors. The rewrite log only shows a <code>pass through</code> followed by a <code>redirect</code> when successful, then only <code>pass through</code> when <code>NULL</code> is returned by the script. Subsequent requests also only show <code>pass through</code>.</p> <p>Additionally, replacing <code>stdout</code> with <code>os.fdopen(sys.stdout.fileno(), 'w', 0)</code> to set buffer length to zero did not help.</p> <p>Any help would be greatly appreciated. Thank you in advance.</p> <h3>/etc/apache2/httpd.conf</h3> <pre><code>[...] RewriteLock /tmp/apache_rewrite.lock </code></pre> <h3>/etc/apache2/sites-available/default</h3> <pre><code>&lt;VirtualHost *:80&gt; [...] RewriteEngine on RewriteLogLevel 1 RewriteLog /var/www/logs/rewrite.log RewriteMap remap prg:/var/www/remap.py [...] &lt;/VirtualHost&gt; </code></pre> <h3>/var/www/webroot/.htaccess</h3> <pre><code>RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*_.*) /${remap:$1} [R=301] </code></pre> <h3>/var/www/remap.py</h3> <pre><code>#!/usr/bin/python import sys def getRedirect(str): new_url = None # if url needs to be redirected, put this value in new_url # otherwise new_url remains None return new_url while True: request = sys.stdin.readline().strip() response = getRedirect(request) if response: sys.stdout.write(response + '\n') else: sys.stdout.write('NULL') sys.stdout.flush() </code></pre>
2
2009-10-16T22:47:32Z
1,584,049
<p>The best solution I've come up with thus far is to have the RewriteMap script return the new url or <code>'__NULL__\n'</code> if no redirect is desired and store this value in a ENV variable. Then, check the ENV variable for <code>!__NULL__</code> and redirect. See <code>.htaccess</code> file below.</p> <p>Also, if anyone is planning on doing something similar to this, inside of the Python script I wrapped a fair amount of it in try/except blocks to prevent the script from dying (in my case, due to failed file/database reads) and subsequent queries being ignored.</p> <h3>/var/www/webroot/.htaccess</h3> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+)$ - [E=REMAP_RESULT:${remap:$1},NS] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{ENV:REMAP_RESULT} !^__NULL__$ RewriteRule ^(.+)$ /%{ENV:REMAP_RESULT} [R=301,L] </code></pre> <h3>/var/www/remap.py</h3> <pre><code>#!/usr/bin/python import sys def getRedirect(str): try: # to prevent the script from dying on any errors new_url = str # if url needs to be redirected, put this value in new_url # otherwise new_url remains None if new_url == str: new_url = '__NULL__' return new_url except: return '__NULL__' while True: request = sys.stdin.readline().strip() response = getRedirect(request) sys.stdout.write(response + '\n') sys.stdout.flush() </code></pre> <p>Vinko, you definitely helped me figure this one out. If I had more experience with <code>stackoverflow</code>, you would have received <code>^</code> from me. Thank you.</p> <p>I hope this post helps someone dealing with a similar problem in the future.</p> <p>Cheers, Andrew</p>
2
2009-10-18T04:57:33Z
[ "python", "apache2", "rewrite", "apache" ]
How to avoid excessive parameter passing?
1,580,792
<p>I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I extend the ability for the user to customise the behaviour or the program I find that I end up requiring this user-defined parameter in a method in a.py that is not directly called by main.py, but is instead called by another method in a.py:</p> <p>main.py:</p> <pre><code> import a p = some_command_line_argument_value a.meth1(p) </code></pre> <p>a.py:</p> <pre><code>meth1(p): # some code res = meth2(p) # some more code w/ res meth2(p): # do something with p </code></pre> <p>This excessive parameter passing seems wasteful and wrong, but has hard as I try I cannot think of a design pattern that solves this problem. While I had some formal CS education (minor in CS during my B.Sc.), I've only really come to appreciate good coding practices since I started using python. Please help me become a better programmer!</p>
2
2009-10-16T22:52:16Z
1,580,824
<p>If "a" is a real object and not just a set of independent helper methods, you can create an "p" member variable in "a" and set it when you instantiate an "a" object. Then your main class will not need to pass "p" into meth1 and meth2 once "a" has been instantiated.</p>
2
2009-10-16T23:02:27Z
[ "python", "design-patterns" ]
How to avoid excessive parameter passing?
1,580,792
<p>I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I extend the ability for the user to customise the behaviour or the program I find that I end up requiring this user-defined parameter in a method in a.py that is not directly called by main.py, but is instead called by another method in a.py:</p> <p>main.py:</p> <pre><code> import a p = some_command_line_argument_value a.meth1(p) </code></pre> <p>a.py:</p> <pre><code>meth1(p): # some code res = meth2(p) # some more code w/ res meth2(p): # do something with p </code></pre> <p>This excessive parameter passing seems wasteful and wrong, but has hard as I try I cannot think of a design pattern that solves this problem. While I had some formal CS education (minor in CS during my B.Sc.), I've only really come to appreciate good coding practices since I started using python. Please help me become a better programmer!</p>
2
2009-10-16T22:52:16Z
1,580,843
<p>[Caution: my answer isn't specific to python.]</p> <p>I remember that <em>Code Complete</em> called this kind of parameter a "tramp parameter". Googling for "tramp parameter" doesn't return many results, however.</p> <p>Some alternatives to tramp parameters might include:</p> <ul> <li>Put the data in a global variable</li> <li>Put the data in a static variable of a class (similar to global data)</li> <li>Put the data in an instance variable of a class</li> <li>Pseudo-global variable: hidden behind a singleton, or some dependency injection mechanism</li> </ul> <p>Personally, I don't mind a tramp parameter as long as there's no more than one; i.e. your example is OK for me, but I wouldn't like ...</p> <pre><code>import a p1 = some_command_line_argument_value p2 = another_command_line_argument_value p3 = a_further_command_line_argument_value a.meth1(p1, p2, p3) </code></pre> <p>... instead I'd prefer ...</p> <pre><code>import a p = several_command_line_argument_values a.meth1(p) </code></pre> <p>... because if <code>meth2</code> decides that it wants more data than before, I'd prefer if it could extract this extra data from the original parameter which it's already being passed, so that I don't need to edit <code>meth1</code>.</p>
2
2009-10-16T23:10:15Z
[ "python", "design-patterns" ]
How to avoid excessive parameter passing?
1,580,792
<p>I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I extend the ability for the user to customise the behaviour or the program I find that I end up requiring this user-defined parameter in a method in a.py that is not directly called by main.py, but is instead called by another method in a.py:</p> <p>main.py:</p> <pre><code> import a p = some_command_line_argument_value a.meth1(p) </code></pre> <p>a.py:</p> <pre><code>meth1(p): # some code res = meth2(p) # some more code w/ res meth2(p): # do something with p </code></pre> <p>This excessive parameter passing seems wasteful and wrong, but has hard as I try I cannot think of a design pattern that solves this problem. While I had some formal CS education (minor in CS during my B.Sc.), I've only really come to appreciate good coding practices since I started using python. Please help me become a better programmer!</p>
2
2009-10-16T22:52:16Z
1,580,848
<p>Create objects of types relevant to your program, and store the command line options relevant to each in them. Example:</p> <pre><code>import WidgetFrobnosticator f = WidgetFrobnosticator() f.allow_oncave_widgets = option_allow_concave_widgets f.respect_weasel_pins = option_respect_weasel_pins # Now the methods of WidgetFrobnosticator have access to your command-line parameters, # in a way that's not dependent on the input format. import PlatypusFactory p = PlatypusFactory() p.allow_parthenogenesis = option_allow_parthenogenesis p.max_population = option_max_population # The platypus factory knows about its own options, but not those of the WidgetFrobnosticator # or vice versa. This makes each class easier to read and implement. </code></pre>
7
2009-10-16T23:11:16Z
[ "python", "design-patterns" ]
How to avoid excessive parameter passing?
1,580,792
<p>I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I extend the ability for the user to customise the behaviour or the program I find that I end up requiring this user-defined parameter in a method in a.py that is not directly called by main.py, but is instead called by another method in a.py:</p> <p>main.py:</p> <pre><code> import a p = some_command_line_argument_value a.meth1(p) </code></pre> <p>a.py:</p> <pre><code>meth1(p): # some code res = meth2(p) # some more code w/ res meth2(p): # do something with p </code></pre> <p>This excessive parameter passing seems wasteful and wrong, but has hard as I try I cannot think of a design pattern that solves this problem. While I had some formal CS education (minor in CS during my B.Sc.), I've only really come to appreciate good coding practices since I started using python. Please help me become a better programmer!</p>
2
2009-10-16T22:52:16Z
1,580,850
<p>With objects, parameter lists should normally be very small, since most appropriate information is a property of the object itself. The standard way to handle this is to configure the object properties and then call the appropriate methods of that object. In this case set <code>p</code> as an attribute of <code>a</code>. Your <code>meth2</code> should also complain if <code>p</code> is not set.</p>
1
2009-10-16T23:12:20Z
[ "python", "design-patterns" ]
How to avoid excessive parameter passing?
1,580,792
<p>I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I extend the ability for the user to customise the behaviour or the program I find that I end up requiring this user-defined parameter in a method in a.py that is not directly called by main.py, but is instead called by another method in a.py:</p> <p>main.py:</p> <pre><code> import a p = some_command_line_argument_value a.meth1(p) </code></pre> <p>a.py:</p> <pre><code>meth1(p): # some code res = meth2(p) # some more code w/ res meth2(p): # do something with p </code></pre> <p>This excessive parameter passing seems wasteful and wrong, but has hard as I try I cannot think of a design pattern that solves this problem. While I had some formal CS education (minor in CS during my B.Sc.), I've only really come to appreciate good coding practices since I started using python. Please help me become a better programmer!</p>
2
2009-10-16T22:52:16Z
1,580,851
<p>Maybe you should organize your code more into classes and objects? As I was writing this, Jimmy showed a class-instance based answer, so here is a pure class-based answer. This would be most useful if you only ever wanted a single behavior; if there is any chance at all you might want different defaults some of the time, you should use ordinary object-oriented programming in Python, i.e. pass around class instances with the property p set in the instance, not the class.</p> <pre><code>class Aclass(object): p = None @classmethod def init_p(cls, value): p = value @classmethod def meth1(cls): # some code res = cls.meth2() # some more code w/ res @classmethod def meth2(cls): # do something with p pass from a import Aclass as ac ac.init_p(some_command_line_argument_value) ac.meth1() ac.meth2() </code></pre>
3
2009-10-16T23:12:48Z
[ "python", "design-patterns" ]
How to avoid excessive parameter passing?
1,580,792
<p>I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I extend the ability for the user to customise the behaviour or the program I find that I end up requiring this user-defined parameter in a method in a.py that is not directly called by main.py, but is instead called by another method in a.py:</p> <p>main.py:</p> <pre><code> import a p = some_command_line_argument_value a.meth1(p) </code></pre> <p>a.py:</p> <pre><code>meth1(p): # some code res = meth2(p) # some more code w/ res meth2(p): # do something with p </code></pre> <p>This excessive parameter passing seems wasteful and wrong, but has hard as I try I cannot think of a design pattern that solves this problem. While I had some formal CS education (minor in CS during my B.Sc.), I've only really come to appreciate good coding practices since I started using python. Please help me become a better programmer!</p>
2
2009-10-16T22:52:16Z
1,580,989
<p>Your example is reminiscent of the code smell <a href="http://sourcemaking.com/refactoring/message-chains" rel="nofollow">Message Chains</a>. You may find the corresponding refactoring, <a href="http://sourcemaking.com/refactoring/hide-delegate" rel="nofollow">Hide Delegate</a>, informative.</p>
1
2009-10-17T00:11:22Z
[ "python", "design-patterns" ]
Python logging for non-trivial uses?
1,580,828
<p>I'm attempting to use the python logging module to do complex things. I'll leave the motivation for this design out because it would greatly lengthen the post, but I need to have a root logger that spams a regular log file for our code and libraries that use logging -- and a collection of other loggers that go to <em>different</em> log files.</p> <p>The overall setup should look like this. I will do everything to stdout in this example to simplify the code.</p> <pre><code> import logging, sys root = logging.getLogger('') top = logging.getLogger('top') bottom = logging.getLogger('top.bottom') class KillFilter(object): def filter(self, msg): return 0 root_handler = logging.StreamHandler(sys.stdout) top_handler = logging.StreamHandler(sys.stdout) bottom_handler = logging.StreamHandler(sys.stdout) root_handler.setFormatter(logging.Formatter('ROOT')) top_handler.setFormatter(logging.Formatter('TOP HANDLER')) bottom_handler.setFormatter(logging.Formatter("BOTTOM HANDLER")) msg_killer = KillFilter() root.addHandler(root_handler) top.addHandler(top_handler) bottom.addHandler(bottom_handler) top.addFilter(msg_killer) root.error('hi') top.error('hi') bottom.error('hi') </code></pre> <p>This outputs</p> <p><pre><code> ROOT BOTTOM HANDLER ROOT </pre></code></p> <p>The second root handler call should not because according to logging documentation the <code>msg_killer</code> will stop the message from going up to the root logger. Obviously the documentation could use improvement.</p> <p>Edit: removed my "in the moment" harsh words for python logging.</p>
1
2009-10-16T23:04:28Z
1,580,929
<p>First off, I get a different output on my machine (running Python 2.6):</p> <pre><code>ROOT BOTTOM HANDLER TOP HANDLER ROOT </code></pre> <p>Filtering is only applied on the logger that the message is issued to, and if it passes the filters, it's then propagated to all the handlers of the parent loggers (and not the loggers themselves) - I don't know the rationale for this decision. If you want to stop propagation at say the "top" Logger instance, set:</p> <pre><code>top.propagation = False </code></pre>
7
2009-10-16T23:44:50Z
[ "python", "logging" ]
Python logging for non-trivial uses?
1,580,828
<p>I'm attempting to use the python logging module to do complex things. I'll leave the motivation for this design out because it would greatly lengthen the post, but I need to have a root logger that spams a regular log file for our code and libraries that use logging -- and a collection of other loggers that go to <em>different</em> log files.</p> <p>The overall setup should look like this. I will do everything to stdout in this example to simplify the code.</p> <pre><code> import logging, sys root = logging.getLogger('') top = logging.getLogger('top') bottom = logging.getLogger('top.bottom') class KillFilter(object): def filter(self, msg): return 0 root_handler = logging.StreamHandler(sys.stdout) top_handler = logging.StreamHandler(sys.stdout) bottom_handler = logging.StreamHandler(sys.stdout) root_handler.setFormatter(logging.Formatter('ROOT')) top_handler.setFormatter(logging.Formatter('TOP HANDLER')) bottom_handler.setFormatter(logging.Formatter("BOTTOM HANDLER")) msg_killer = KillFilter() root.addHandler(root_handler) top.addHandler(top_handler) bottom.addHandler(bottom_handler) top.addFilter(msg_killer) root.error('hi') top.error('hi') bottom.error('hi') </code></pre> <p>This outputs</p> <p><pre><code> ROOT BOTTOM HANDLER ROOT </pre></code></p> <p>The second root handler call should not because according to logging documentation the <code>msg_killer</code> will stop the message from going up to the root logger. Obviously the documentation could use improvement.</p> <p>Edit: removed my "in the moment" harsh words for python logging.</p>
1
2009-10-16T23:04:28Z
3,411,943
<p>Source is messed with different case identifiers, more useful version:</p> <pre><code>import logging, sys root = logging.getLogger('') level1 = logging.getLogger('level1') level2 = logging.getLogger('level1.level2') class KillFilter(object): def filter(self, msg): return 0 root_handler = logging.StreamHandler(sys.stdout) top_handler = logging.StreamHandler(sys.stdout) bottom_handler = logging.StreamHandler(sys.stdout) root_handler.setFormatter(logging.Formatter('ROOT HANDLER - %(msg)s')) top_handler.setFormatter(logging.Formatter('level1 HANDLER - %(msg)s')) bottom_handler.setFormatter(logging.Formatter('level2 HANDLER - %(msg)s')) msg_killer = KillFilter() root.addHandler(root_handler) level1.addHandler(top_handler) level2.addHandler(bottom_handler) level1.addFilter(msg_killer) level1.propagate = False root.error('root_message') level1.error('level1_message') level2.error('level2_message') </code></pre>
1
2010-08-05T05:19:06Z
[ "python", "logging" ]
Python TCP stack implementation
1,581,087
<p>Is there a python library which implements a standalone TCP stack?</p> <p>I can't use the usual python socket library because I'm receiving a stream of packets over a socket (they are being tunneled to me over this socket). When I receive a TCP SYN packet addressed to a particular port, I'd like to accept the connection (send a syn-ack) and then get the data sent by the other end (ack'ing appropriately).</p> <p>I was hoping there was some sort of TCP stack already written which I could utilize. Any ideas? I've used lwip in the past for a C project -- something along those lines in python would be perfect.</p>
7
2009-10-17T00:50:53Z
1,581,097
<p>I know this isn't directly Python related but if you are looking to do heavy network processing, you should consider Erlang instead of Python. Just a suggestion really... you can always take a shot a doing this with Twisted... if you feel adventurous (and have lots of time on your side) ;-)</p>
1
2009-10-17T00:53:09Z
[ "python", "tcp", "network-programming", "network-protocols", "raw-sockets" ]