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>...
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...
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>...
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, th...
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, th...
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, th...
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, th...
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...
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]...
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&g...
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]...
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;hel...
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]...
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]...
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;/tes...
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>...
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 acces...
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>...
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 ...
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 t...
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 help...
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 t...
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)).OfTyp...
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 t...
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><co...
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 t...
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 t...
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...
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 t...
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_da...
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 t...
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, ...
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;...
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 tex...
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;...
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 typ...
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 conn...
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 ...
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 ...
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 ...
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 should...
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-packag...
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): ...
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 t...
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): ...
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 respon...
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): ...
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() ...
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 th...
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 (whi...
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 th...
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...
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 ...
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 getdirentr...
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> ...
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...
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> ...
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 ...
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 tr...
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 tr...
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 impor...
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 tr...
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(t...
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] ...
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), ...
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: d...
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 ...
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: d...
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 =...
-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 =...
-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 sa...
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 =...
-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 =...
-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 workin...
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 ...
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 ...
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: ...
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 ...
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 ...
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...
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 ...
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 ne...
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 tim...
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...
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 tim...
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...
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 tim...
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 fil...
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...
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...
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...
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 fl...
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...
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 ...
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...
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 ...
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....
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....
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....
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, wh...
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....
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". A...
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....
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 d...
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, 16...
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 d...
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....
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 = st...
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...
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...
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 me...
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...
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 assoc...
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...
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...
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...
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 t...
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 t...
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 cr...
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 t...
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 tha...
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 t...
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...
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 fil...
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']...
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 fil...
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> kno...
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 al...
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 al...
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>Th...
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 al...
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 requir...
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 al...
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 ...
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...
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 wan...
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...
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, i...
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 th...
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 th...
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 var...
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 th...
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 o...
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 th...
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</c...
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 th...
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 th...
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 th...
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 ...
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 t...
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 ...
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.Strea...
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 conn...
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" ]