title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python:: Turn string into operator
1,740,726
<p>How can I turn a string such as "+" into the operator plus? Thanks!</p>
12
2009-11-16T08:00:19Z
1,740,761
<pre><code>import operator def get_operator_fn(op): return { '+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.div, '%' : operator.mod, '^' : operator.xor, }[op] def eval_binary_expr(op1, operator, op2): op1,op2 = int(op1), int(o...
11
2009-11-16T08:09:34Z
[ "python" ]
Python:: Turn string into operator
1,740,726
<p>How can I turn a string such as "+" into the operator plus? Thanks!</p>
12
2009-11-16T08:00:19Z
1,740,819
<p>In my opinion, the answer proposed by Amnon is the right one.</p> <p>However, you may also be interested by this article about a mathematical parser: <a href="http://effbot.org/zone/simple-top-down-parsing.htm" rel="nofollow">http://effbot.org/zone/simple-top-down-parsing.htm</a></p>
1
2009-11-16T08:27:35Z
[ "python" ]
Python:: Turn string into operator
1,740,726
<p>How can I turn a string such as "+" into the operator plus? Thanks!</p>
12
2009-11-16T08:00:19Z
38,095,600
<p>There is a magic method corresponding to every operator</p> <pre><code>OPERATORS = {'+': 'add', '-': 'sub', '*': 'mul', '/': 'div'} def apply_operator(a, op, b): method = '__%s__' % OPERATORS[op] return getattr(b, method)(a) apply_operator(1, '+', 2) </code></pre>
0
2016-06-29T09:29:48Z
[ "python" ]
XML attributes get sorted
1,740,731
<p>When I create a document using the minidom, attributes get sorted alphabetically in the element. Take this example from <a href="http://developer.taboca.com/cases/en/creating%5Fa%5Fnew%5Fxml%5Fdocument%5Fwith%5Fpython/" rel="nofollow">here</a>:</p> <pre><code>from xml.dom import minidom # New document xml = minido...
4
2009-11-16T08:00:40Z
1,740,805
<p>According to the <a href="http://docs.python.org/library/xml.dom.html#namednodemap-objects" rel="nofollow">documentation</a>, the order of attributes is arbitrary but consistent for the life of the DOM. This is common across DOM implementations. Sorry.</p>
4
2009-11-16T08:23:12Z
[ "python", "xml", "minidom" ]
sqlalchemy REST serialization
1,740,817
<p>Reading the doc of sqlalchemy, i saw the serialization part.<br> I'm wondering about a possibility to use an xml serializer for matching sa models with Rest webservices like Jax-RS<br> There is a django extension which deal with that : <a href="http://bitbucket.org/david/django-roa/" rel="nofollow">django_roa</a><br...
2
2009-11-16T08:26:18Z
1,741,760
<p><code>sqlalchemy.ext.serializer</code> exists to support pickling (with <code>pickle</code> module) of queries, expressions and other <em>internal</em> SQLAlchemy objects, it doesn't deal with model objects. In no way it will help you to serialize model objects to XML. Probably something like <a href="http://pypi.py...
1
2009-11-16T12:01:06Z
[ "python", "rest", "xml-serialization", "sqlalchemy" ]
sqlalchemy REST serialization
1,740,817
<p>Reading the doc of sqlalchemy, i saw the serialization part.<br> I'm wondering about a possibility to use an xml serializer for matching sa models with Rest webservices like Jax-RS<br> There is a django extension which deal with that : <a href="http://bitbucket.org/david/django-roa/" rel="nofollow">django_roa</a><br...
2
2009-11-16T08:26:18Z
3,781,961
<p>Its a long way till full RFC2616 compliance, but for a prototype, I do something like this:</p> <pre><code>from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relation, backref, sessionm...
2
2010-09-23T19:43:37Z
[ "python", "rest", "xml-serialization", "sqlalchemy" ]
Lightweight python wiki engine with pluggable auth system
1,740,957
<p>I need to add wiki to my Tornado webapp. i'm new to python so i would like it not too intimidating to be learned and integrated and can use my existing authentication system, hence the lightweight. it would be better if can use mongodb backend.</p> <p>I already take a look at moin-moin and it seems too complex(?). ...
5
2009-11-16T09:08:38Z
1,741,232
<p>Have a look at <a href="http://hatta-wiki.org/" rel="nofollow">Hatta</a>. Overwrite <code>WikiRequest.get_author()</code> method to plug your authentication system. But it uses mercurial repository to store the data.</p>
4
2009-11-16T10:10:40Z
[ "python", "wiki-engine" ]
Lightweight python wiki engine with pluggable auth system
1,740,957
<p>I need to add wiki to my Tornado webapp. i'm new to python so i would like it not too intimidating to be learned and integrated and can use my existing authentication system, hence the lightweight. it would be better if can use mongodb backend.</p> <p>I already take a look at moin-moin and it seems too complex(?). ...
5
2009-11-16T09:08:38Z
1,742,781
<p><a href="http://orangoo.com/skeletonz/" rel="nofollow">Skeletonz</a> is a very nice lightweight Python cms that might be worth a look...</p>
0
2009-11-16T15:11:31Z
[ "python", "wiki-engine" ]
translate python method to ruby
1,740,960
<p>What would be the correct translation of the following Python method to Ruby?</p> <pre><code>def uniqueCombinations(self, items, n): """ items: list of elements n: number in a group """ if n == 0: yield [] else: for i in range(len(items)-n+1): for cc in uniqueCom...
0
2009-11-16T09:08:56Z
1,740,979
<pre><code>yield [items[i]] + cc </code></pre> <p>You are attempting to concatenate an array ([items[i]]) and a Fixnum (cc). You could instead turn both into an array or use the &lt;&lt; method to push cc onto [items[i]].</p> <pre><code>yield [items[i]] &lt;&lt; cc </code></pre>
2
2009-11-16T09:14:47Z
[ "python", "ruby" ]
translate python method to ruby
1,740,960
<p>What would be the correct translation of the following Python method to Ruby?</p> <pre><code>def uniqueCombinations(self, items, n): """ items: list of elements n: number in a group """ if n == 0: yield [] else: for i in range(len(items)-n+1): for cc in uniqueCom...
0
2009-11-16T09:08:56Z
1,741,014
<p>First, it'd be better to do this as a method of the <code>Array</code> class.</p> <p>Second, you can fix your error by changing <code>[items[i]] + cc</code> to <code>[items[i]] + [cc]</code>.</p> <p>Third, here's a different implementation I had lying around, see what you think. It creates an array of permutations...
0
2009-11-16T09:21:43Z
[ "python", "ruby" ]
translate python method to ruby
1,740,960
<p>What would be the correct translation of the following Python method to Ruby?</p> <pre><code>def uniqueCombinations(self, items, n): """ items: list of elements n: number in a group """ if n == 0: yield [] else: for i in range(len(items)-n+1): for cc in uniqueCom...
0
2009-11-16T09:08:56Z
1,741,226
<p>From Ruby 1.8.7 onwards, class Array provides a method to return combinations:</p> <p>irb> ['01', '02', '03'].combination(2).to_a => [["01", "02"], ["01", "03"], ["02", "03"]]</p>
2
2009-11-16T10:08:21Z
[ "python", "ruby" ]
Web.py template error: 'sum' does not exist
1,741,022
<p>I use the built in 'sum' function in a web.py templator template and I get the following error:</p> <pre><code>global name 'sum' is not defined </code></pre> <p>Source code is below:</p> <pre><code>$if profs: $for prof in profs: $sum([1, 2, 3]) </code></pre> <p>I can use 'sum' just fine at a Python REPL...
3
2009-11-16T09:23:03Z
1,741,048
<p>Not all python code is available in template notation, try something like this:</p> <pre><code>$if profs: $for prof in profs: $code: mysum = sum([1, 2, 3]) $mysum </code></pre>
0
2009-11-16T09:29:52Z
[ "python", "web.py" ]
Web.py template error: 'sum' does not exist
1,741,022
<p>I use the built in 'sum' function in a web.py templator template and I get the following error:</p> <pre><code>global name 'sum' is not defined </code></pre> <p>Source code is below:</p> <pre><code>$if profs: $for prof in profs: $sum([1, 2, 3]) </code></pre> <p>I can use 'sum' just fine at a Python REPL...
3
2009-11-16T09:23:03Z
3,868,598
<p>Add the functions in a dict and pass as the globals argument to render:</p> <pre><code>render = web.template.render('templates/', globals={'sum': sum}) </code></pre> <p>Then in your template you can just use it:</p> <pre><code>$def with (numbers) &lt;h1&gt;Numbers add to $sum(numbers)&lt;/h1&gt; </code></pre>
4
2010-10-05T23:47:56Z
[ "python", "web.py" ]
How to make PowerBuilder UI testing application?
1,741,023
<p>I'm not familiar with PowerBuilder but I have a task to create Automatic UI Test Application for PB. We've decided to do it in Python with pywinauto and iaccesible libraries. The problem is that some UI elements like newly added lists record can not be accesed from it (even inspect32 can't get it). Any ideas how to...
5
2009-11-16T09:23:41Z
1,741,142
<p>I'm experimenting with code for a tool for automating PowerBuilder-based GUIs as well. From what I can see, your best bet would be to use the PowerBuilder Native Interface (PBNI), and call PowerScript code from within your NVO.</p> <p>If you like, feel free to send me an email (see my profile for my email address),...
2
2009-11-16T09:50:18Z
[ "python", "testing", "powerbuilder" ]
How to make PowerBuilder UI testing application?
1,741,023
<p>I'm not familiar with PowerBuilder but I have a task to create Automatic UI Test Application for PB. We've decided to do it in Python with pywinauto and iaccesible libraries. The problem is that some UI elements like newly added lists record can not be accesed from it (even inspect32 can't get it). Any ideas how to...
5
2009-11-16T09:23:41Z
1,741,303
<p>I didn't use PowerBuilder for a while but I guess that the problem that you are trying to solve is similar to the one I am trying to address for people making projects with SCADA systems like Wonderware Intouch.</p> <p>The problem with such an application is that there is no API to get or set the value of a control...
1
2009-11-16T10:27:41Z
[ "python", "testing", "powerbuilder" ]
How to make PowerBuilder UI testing application?
1,741,023
<p>I'm not familiar with PowerBuilder but I have a task to create Automatic UI Test Application for PB. We've decided to do it in Python with pywinauto and iaccesible libraries. The problem is that some UI elements like newly added lists record can not be accesed from it (even inspect32 can't get it). Any ideas how to...
5
2009-11-16T09:23:41Z
1,743,045
<p>If you are testing DataWindows (the class is pbdwxxx, e.g. pbdw110) you will have to use a combination of clicking at specific coordinates and sending Tab keys to get to the control you want. Of course you can also send up and down arrow keys to move among rows. The easiest thing to do is to start with a normal cont...
1
2009-11-16T15:50:16Z
[ "python", "testing", "powerbuilder" ]
How to make PowerBuilder UI testing application?
1,741,023
<p>I'm not familiar with PowerBuilder but I have a task to create Automatic UI Test Application for PB. We've decided to do it in Python with pywinauto and iaccesible libraries. The problem is that some UI elements like newly added lists record can not be accesed from it (even inspect32 can't get it). Any ideas how to...
5
2009-11-16T09:23:41Z
2,328,021
<p>I've seen in AutomatedQa support that they a recipe recommending using msaa and setting some properties on the controls. I do not know if it works.</p>
1
2010-02-24T17:25:37Z
[ "python", "testing", "powerbuilder" ]
How to ignore "Enter username for Private Proxy Access" prompt?
1,741,360
<p>I'm using urllib.urlopen with some http proxies and sometimes (probably when they require authorization) I get the following prompt printed into the console:</p> <pre><code>Enter username for Private Proxy Access (country) at xxx.xxx.xxx.xxx:xxxx </code></pre> <p>How can I raise an exception on such thing happenin...
1
2009-11-16T10:39:46Z
1,741,399
<p><code>urllib.urlencode</code> doesn't <strong>ever</strong> print that message. That method never hits the network in first place. Your problem is somewhere else.</p> <p>I guess you're running some other daemon in background that prints the message.</p> <p>Please provide exact reproducible code and message. Exampl...
1
2009-11-16T10:45:59Z
[ "python", "proxy", "urllib" ]
How to ignore "Enter username for Private Proxy Access" prompt?
1,741,360
<p>I'm using urllib.urlopen with some http proxies and sometimes (probably when they require authorization) I get the following prompt printed into the console:</p> <pre><code>Enter username for Private Proxy Access (country) at xxx.xxx.xxx.xxx:xxxx </code></pre> <p>How can I raise an exception on such thing happenin...
1
2009-11-16T10:39:46Z
1,743,022
<p>You need to overwrite <code>FancyURLopener.prompt_user_passwd</code> method:</p> <pre><code>class AuthorizationRequired(Exception): pass class MyURLOpener(urllib.FancyURLopener): def prompt_user_passwd(self, host, realm): raise AuthorizationRequired() opener = MyURLOpener(proxies={'http': 'htt...
2
2009-11-16T15:47:03Z
[ "python", "proxy", "urllib" ]
How to ignore "Enter username for Private Proxy Access" prompt?
1,741,360
<p>I'm using urllib.urlopen with some http proxies and sometimes (probably when they require authorization) I get the following prompt printed into the console:</p> <pre><code>Enter username for Private Proxy Access (country) at xxx.xxx.xxx.xxx:xxxx </code></pre> <p>How can I raise an exception on such thing happenin...
1
2009-11-16T10:39:46Z
10,311,272
<p>I adapted Denis' code a little to this:</p> <pre><code>import urllib urllib.FancyURLopener.prompt_user_passwd = lambda *a, **k: (None, None) </code></pre> <p>It will disable password prompting altogether</p>
1
2012-04-25T07:33:17Z
[ "python", "proxy", "urllib" ]
mongodb, pymongo querying
1,741,379
<p>I've been browsing through the documentation, but I can't seem to figure out a way to perform a find on my mongodb collection using only a key. For example, let's suppose this is what's inside my collection</p> <pre><code>{ 'res1': 10 } { 'res2: 20 } </code></pre> <p>How can I query the collection using only the k...
1
2009-11-16T10:42:41Z
1,741,414
<p>Not sure exaclty what you want, so... This is if you want all documents that have key res1 set:</p> <p><code>db.collection.find({'res1': { $exists : true }})</code></p> <p>And this is if you want all the documents that have key res1 set to 10:</p> <p><code>db.collection.find({'res1': 10})</code></p>
2
2009-11-16T10:50:25Z
[ "python", "mongodb" ]
mongodb, pymongo querying
1,741,379
<p>I've been browsing through the documentation, but I can't seem to figure out a way to perform a find on my mongodb collection using only a key. For example, let's suppose this is what's inside my collection</p> <pre><code>{ 'res1': 10 } { 'res2: 20 } </code></pre> <p>How can I query the collection using only the k...
1
2009-11-16T10:42:41Z
1,741,418
<p>Ah, I guess I'm structuring my data all wrong, I should have something like this:</p> <pre><code>{ 'name': 'res1', 'value': 10 } </code></pre> <p>Right?</p>
2
2009-11-16T10:50:37Z
[ "python", "mongodb" ]
mongodb, pymongo querying
1,741,379
<p>I've been browsing through the documentation, but I can't seem to figure out a way to perform a find on my mongodb collection using only a key. For example, let's suppose this is what's inside my collection</p> <pre><code>{ 'res1': 10 } { 'res2: 20 } </code></pre> <p>How can I query the collection using only the k...
1
2009-11-16T10:42:41Z
1,751,554
<pre><code>&gt; db.collection.find({'res1': 10}) # Returns a cursor. </code></pre> <p>In your case, find_one method will do the needful.</p> <pre><code>&gt; db.collection.find_one({'res1': 10}) # Returns a document whose value is 10 </code></pre>
1
2009-11-17T20:30:18Z
[ "python", "mongodb" ]
Google Wave Python Tutorial - Nothing happens
1,741,773
<p>For the <a href="http://code.google.com/apis/wave/extensions/robots/python-tutorial.html" rel="nofollow">Google Wave Python Robot Tutorial</a>, my capabilities.xml is visible and I can add it to a Wave, but the robot isn't actually responding to the events. I checked the logs, but I've fixed it so I'm not getting an...
3
2009-11-16T12:03:14Z
1,741,973
<p>There's known issue with Wave API: <a href="http://code.google.com/p/google-wave-resources/issues/detail?id=158" rel="nofollow">Issue 158</a> Fix is ready and is expected to be deployed in "coming days".</p>
3
2009-11-16T12:42:23Z
[ "python", "google-app-engine", "google-wave" ]
How to use different formatters with the same logging handler in python
1,741,972
<p>Is it possible to log to a single destination (i.e. using one <code>FileHandler</code>) with multiple loggers (i.e. <code>logging.getLogger("base.foo")</code> and <code>logging.getLogger("base.bar")</code>), and use different formatters for each of the loggers.</p> <p>To my understanding it's only possible to assig...
12
2009-11-16T12:42:04Z
1,742,512
<p>It's easy to dispatch to different formatters based on <code>record.name</code>. Below is prove-of-concept sample code:</p> <pre><code>import logging class DispatchingFormatter: def __init__(self, formatters, default_formatter): self._formatters = formatters self._default_formatter = default_...
11
2009-11-16T14:30:57Z
[ "python", "logging" ]
How to use different formatters with the same logging handler in python
1,741,972
<p>Is it possible to log to a single destination (i.e. using one <code>FileHandler</code>) with multiple loggers (i.e. <code>logging.getLogger("base.foo")</code> and <code>logging.getLogger("base.bar")</code>), and use different formatters for each of the loggers.</p> <p>To my understanding it's only possible to assig...
12
2009-11-16T12:42:04Z
34,626,685
<p>Little fix to excellent Denis's solution.</p> <p><a href="https://docs.python.org/3.5/library/logging.html#logger-objects" rel="nofollow">Logging name system</a> based on hierarchical structure:</p> <blockquote> <p>The <code>name</code> is potentially a period-separated hierarchical value, like <code>foo.bar.b...
0
2016-01-06T06:07:24Z
[ "python", "logging" ]
Can SQLAlchemy update the table structure?
1,742,157
<p>I am working on my first pylons + SQLAlchemy app (I'm new to both).</p> <p>As I change my mind on the table structure, I wish there was a similar function to metadata.create_all(), that checks if there are new columns definitions and create them in the database.</p> <p>Does such a function exist ?</p>
6
2009-11-16T13:18:03Z
1,742,314
<p>I'm not (yet) a SQLAlchemy user, but I've heard good things about <a href="http://code.google.com/p/sqlalchemy-migrate/">sqlalchemy-migrate</a>. The general term of the problem you have is "schema migration", I'm sure a <a href="http://www.google.ch/search?q=schema+migration+sqlalchemy">google search</a> containing ...
5
2009-11-16T13:52:33Z
[ "python", "mysql", "sqlalchemy", "pylons" ]
How do I get the selected text in desktop application using python-dbus?
1,742,264
<p>For example, I open a pdf file or a web page in gnome, use mouse double click some text, so a word is selected, how can I get this word in a background running daemon written with python-dbus?</p> <p>Some simple but working piece of script is appreciated greatly.</p> <p>Thanks!</p>
2
2009-11-16T13:41:22Z
1,742,584
<p><a href="https://code.launchpad.net/do" rel="nofollow">Gnome Do</a> has a few plug-ins that use the selected text. I'm not sure how it is implemented (and if it uses DBus), but the code should reveal all. :)</p>
0
2009-11-16T14:42:03Z
[ "python", "text", "gtk", "selection", "dbus" ]
How do I get the selected text in desktop application using python-dbus?
1,742,264
<p>For example, I open a pdf file or a web page in gnome, use mouse double click some text, so a word is selected, how can I get this word in a background running daemon written with python-dbus?</p> <p>Some simple but working piece of script is appreciated greatly.</p> <p>Thanks!</p>
2
2009-11-16T13:41:22Z
1,742,632
<p>You don't need D-Bus, simply listen to changes for the middle-click (Selection) clipboard with for example Gtk:</p> <pre><code>import gtk def _clipboard_changed(clipboard, event): text = clipboard.wait_for_text() clip = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY) clip.connect("owner-change", _clipboard_chang...
7
2009-11-16T14:50:51Z
[ "python", "text", "gtk", "selection", "dbus" ]
Python 3 Library for Realtime Midi Communication
1,742,382
<p>Can anyone suggest a good Python 3 Library for sending / receiving reatime MIDI?</p>
4
2009-11-16T14:06:43Z
2,089,977
<p>Why Python 3? It generally doesn't have many libraries yet. Generally you want to look into high-level C-libraries with Python wrappers. I doubt many of these work under Python 3 at the moment. </p>
1
2010-01-18T23:26:47Z
[ "python", "python-3.x", "midi" ]
Calling Method from Different Python File
1,742,430
<p>As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition.</p> <p>So let's say I have this Package called <code>Example1</code> with a <code>views.py</code> that contains this method:</p> <pre><co...
5
2009-11-16T14:15:43Z
1,742,466
<p>Try:</p> <pre><code>from Example2.views import adder as myadder myadder(x,y) </code></pre> <p>If you are unsure, you can always start a python shell and then use the <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow">dir</a> command to look inside the contents of packages to see what can be...
6
2009-11-16T14:22:06Z
[ "python", "django", "methods" ]
Calling Method from Different Python File
1,742,430
<p>As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition.</p> <p>So let's say I have this Package called <code>Example1</code> with a <code>views.py</code> that contains this method:</p> <pre><co...
5
2009-11-16T14:15:43Z
1,742,467
<p>Normally you import "modules"</p> <p>I would suggest:</p> <pre><code>from Example2 import views as views2 x = views2.adder(1, 2) </code></pre> <p>I hope, I got this right, since I did not use packages till now ;-)</p>
3
2009-11-16T14:22:18Z
[ "python", "django", "methods" ]
Calling Method from Different Python File
1,742,430
<p>As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition.</p> <p>So let's say I have this Package called <code>Example1</code> with a <code>views.py</code> that contains this method:</p> <pre><co...
5
2009-11-16T14:15:43Z
1,742,476
<p>Python has module level and class level methods. In this concept a "module" is a very special class that you get by using <code>import</code> instead of <code>Name()</code>. Try</p> <pre><code>from Example1.views import adder as otherAdder </code></pre> <p>to get access to the module level method. Now you can call...
7
2009-11-16T14:23:56Z
[ "python", "django", "methods" ]
How to use python win32com to save as excel file
1,742,471
<p>I have a small python code to open an Excel file. Now I want to "Save As" with a different name but same format. How do I do that.. Any help will be great. FK </p>
4
2009-11-16T14:23:00Z
1,742,556
<p>Here is a <a href="http://www.xsi-blog.com/archives/11">tutorial on using the win32com API with Exce</a>l and here is the COM method you will likely have to call, <a href="http://msdn.microsoft.com/en-us/library/bb214129.aspx">Workbook.SaveAs</a>. And here is an example of actually <a href="http://aspn.activestate.c...
9
2009-11-16T14:37:32Z
[ "python", "win32com" ]
sorting function in python
1,742,656
<p>I'm trying to sort a list of objects according to my criteria.</p> <p>Here is my sorting function:</p> <pre><code>def sort_pots(self, pot1, pot2): coeff1 = ((pot1.movable + pot1.convertible) / pot1.total) coeff2 = ((pot2.movable + pot2.convertible) / pot2.total) if coeff1 &gt; coeff2: return 1...
1
2009-11-16T14:54:45Z
1,742,672
<p>Does the following work?</p> <pre><code>def coef(pot): return (pot.movable + pot.convertible) / float(pot.total) l.sort(key=lambda x: (coef(x), x.total), reverse=True) </code></pre> <p>It should even be faster (key is better than cmp).</p>
9
2009-11-16T14:58:49Z
[ "python", "sorting" ]
sorting function in python
1,742,656
<p>I'm trying to sort a list of objects according to my criteria.</p> <p>Here is my sorting function:</p> <pre><code>def sort_pots(self, pot1, pot2): coeff1 = ((pot1.movable + pot1.convertible) / pot1.total) coeff2 = ((pot2.movable + pot2.convertible) / pot2.total) if coeff1 &gt; coeff2: return 1...
1
2009-11-16T14:54:45Z
1,742,777
<p>I think tonfa's answer is the most readable but if you want to do it with the code you have you should try:</p> <pre><code>def sort_pots(self, pot1, pot2): coeff1 = ((pot1.movable + pot1.convertible) / pot1.total) coeff2 = ((pot2.movable + pot2.convertible) / pot2.total) if coeff1 &gt; coeff2: ...
1
2009-11-16T15:10:44Z
[ "python", "sorting" ]
sorting function in python
1,742,656
<p>I'm trying to sort a list of objects according to my criteria.</p> <p>Here is my sorting function:</p> <pre><code>def sort_pots(self, pot1, pot2): coeff1 = ((pot1.movable + pot1.convertible) / pot1.total) coeff2 = ((pot2.movable + pot2.convertible) / pot2.total) if coeff1 &gt; coeff2: return 1...
1
2009-11-16T14:54:45Z
1,742,912
<p>Just as a final note, you could override the <code>__cmp__</code> method as follows:</p> <pre><code>class Potential(object): # new style classes FTW! ... def __cmp__(self, other): coeff1 = (self.movable + self.convertible) / self.total coeff2 = (other.movable + other.convertible) / other.tot...
2
2009-11-16T15:30:31Z
[ "python", "sorting" ]
compute crc of file in python
1,742,866
<p>I want to calculate the <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC</a> of file and get output like: <code>E45A12AC</code>. Here's my code:</p> <pre><code>#!/usr/bin/env python import os, sys import zlib def crc(fileName): fd = open(fileName,"rb") content = fd.readlines() fd.clo...
12
2009-11-16T15:23:47Z
1,742,958
<p>You can use base64 for getting out like [ERD45FTR]. And zlib.crc32 provides update options.<pre><code>import os, sys import zlib import base64</p> <p>def crc(fileName): fd = open(fileName,"rb") content = fd.readlines() fd.close() prev = None for eachLine in content: if not prev: prev = zlib.crc32(...
2
2009-11-16T15:38:39Z
[ "python", "hash", "crc" ]
compute crc of file in python
1,742,866
<p>I want to calculate the <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC</a> of file and get output like: <code>E45A12AC</code>. Here's my code:</p> <pre><code>#!/usr/bin/env python import os, sys import zlib def crc(fileName): fd = open(fileName,"rb") content = fd.readlines() fd.clo...
12
2009-11-16T15:23:47Z
1,742,988
<p>To show any integer's lowest 32 bits as 8 hexadecimal digits, without sign, you can "mask" the value by bit-and'ing it with a mask made of 32 bits all at value 1, then apply formatting. I.e.:</p> <pre><code>&gt;&gt;&gt; x = -1767935985 &gt;&gt;&gt; format(x &amp; 0xFFFFFFFF, '08x') '969f700f' </code></pre> <p>It'...
5
2009-11-16T15:43:08Z
[ "python", "hash", "crc" ]
compute crc of file in python
1,742,866
<p>I want to calculate the <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC</a> of file and get output like: <code>E45A12AC</code>. Here's my code:</p> <pre><code>#!/usr/bin/env python import os, sys import zlib def crc(fileName): fd = open(fileName,"rb") content = fd.readlines() fd.clo...
12
2009-11-16T15:23:47Z
1,744,163
<p>solution:</p> <pre><code>import os, sys import zlib def crc(fileName, excludeLine="", includeLine=""): try: fd = open(fileName,"rb") except IOError: print "Unable to open the file in readmode:", filename return eachLine = fd.readline() prev = None while eachLine: if excludeL...
0
2009-11-16T19:04:34Z
[ "python", "hash", "crc" ]
compute crc of file in python
1,742,866
<p>I want to calculate the <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC</a> of file and get output like: <code>E45A12AC</code>. Here's my code:</p> <pre><code>#!/usr/bin/env python import os, sys import zlib def crc(fileName): fd = open(fileName,"rb") content = fd.readlines() fd.clo...
12
2009-11-16T15:23:47Z
2,387,880
<p>A little more compact and optimized code</p> <pre><code>def crc(fileName): prev = 0 for eachLine in open(fileName,"rb"): prev = zlib.crc32(eachLine, prev) return "%X"%(prev &amp; 0xFFFFFFFF) </code></pre> <p>PS2: Old PS is deprecated - therefore deleted -, because of the suggestion in the comme...
19
2010-03-05T15:35:38Z
[ "python", "hash", "crc" ]
compute crc of file in python
1,742,866
<p>I want to calculate the <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC</a> of file and get output like: <code>E45A12AC</code>. Here's my code:</p> <pre><code>#!/usr/bin/env python import os, sys import zlib def crc(fileName): fd = open(fileName,"rb") content = fd.readlines() fd.clo...
12
2009-11-16T15:23:47Z
5,061,842
<p><em>hashlib</em>-compatible interface for CRC-32 support:</p> <pre>import zlib class crc32(object): name = 'crc32' digest_size = 4 block_size = 1 def __init__(self, arg=''): self.__digest = 0 self.update(arg) def copy(self): copy = super(self.__class__, self).__new__(s...
5
2011-02-21T02:59:22Z
[ "python", "hash", "crc" ]
compute crc of file in python
1,742,866
<p>I want to calculate the <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC</a> of file and get output like: <code>E45A12AC</code>. Here's my code:</p> <pre><code>#!/usr/bin/env python import os, sys import zlib def crc(fileName): fd = open(fileName,"rb") content = fd.readlines() fd.clo...
12
2009-11-16T15:23:47Z
9,733,707
<p>Merge the above 2 codes as below:</p> <pre><code>try: fd = open(decompressedFile,"rb") except IOError: logging.error("Unable to open the file in readmode:" + decompressedFile) return 4 eachLine = fd.readline() prev = 0 while eachLine: prev = zlib.crc32(eachLine, prev) eachLine = fd.readline() fd...
2
2012-03-16T07:54:27Z
[ "python", "hash", "crc" ]
Convert float to string with cutting zero decimals afer point in Python
1,742,937
<p>I am having difficulty converting a float to string in the following manner:</p> <pre><code>20.02 --&gt; 20.02 20.016 --&gt; 20.02 20.0 --&gt; 20 </code></pre> <p>It seems that<code>%g</code> format is the best for that, but I am getting strange results:</p> <pre><code>In [30]: "%.2g" % 20.03 Out[30]: '20' In...
8
2009-11-16T15:35:45Z
1,742,996
<p>use built-in function <a href="http://docs.python.org/library/functions.html#round" rel="nofollow">round</a></p>
1
2009-11-16T15:44:19Z
[ "python", "string", "floating-point" ]
Convert float to string with cutting zero decimals afer point in Python
1,742,937
<p>I am having difficulty converting a float to string in the following manner:</p> <pre><code>20.02 --&gt; 20.02 20.016 --&gt; 20.02 20.0 --&gt; 20 </code></pre> <p>It seems that<code>%g</code> format is the best for that, but I am getting strange results:</p> <pre><code>In [30]: "%.2g" % 20.03 Out[30]: '20' In...
8
2009-11-16T15:35:45Z
1,743,021
<p>Try something a little less than 20 digits. If you use 20 digits, it will give you the 20 digit representation of the floating point value, which might look a bit odd.</p>
1
2009-11-16T15:46:56Z
[ "python", "string", "floating-point" ]
Convert float to string with cutting zero decimals afer point in Python
1,742,937
<p>I am having difficulty converting a float to string in the following manner:</p> <pre><code>20.02 --&gt; 20.02 20.016 --&gt; 20.02 20.0 --&gt; 20 </code></pre> <p>It seems that<code>%g</code> format is the best for that, but I am getting strange results:</p> <pre><code>In [30]: "%.2g" % 20.03 Out[30]: '20' In...
8
2009-11-16T15:35:45Z
1,743,076
<p>I'm not sure what exactly you are finding complicated here -- you're getting exactly the results specified e.g. <a href="http://docs.python.org/library/string.html#formatspec" rel="nofollow">here</a>. E.g.:</p> <pre><code>In [32]: "%.2g" % 20.3 Out[32]: '20' In [33]: "%.2g" % 1.2 Out[33]: '1.2' </code></pre> <p>...
2
2009-11-16T15:53:51Z
[ "python", "string", "floating-point" ]
Convert float to string with cutting zero decimals afer point in Python
1,742,937
<p>I am having difficulty converting a float to string in the following manner:</p> <pre><code>20.02 --&gt; 20.02 20.016 --&gt; 20.02 20.0 --&gt; 20 </code></pre> <p>It seems that<code>%g</code> format is the best for that, but I am getting strange results:</p> <pre><code>In [30]: "%.2g" % 20.03 Out[30]: '20' In...
8
2009-11-16T15:35:45Z
1,743,086
<p>Use round together with <code>%g</code> -- you want at most 2 digits shown, so round to two digits, then use <code>%g</code> to print it as short as possible:</p> <pre><code>&gt;&gt;&gt; "%g" % round(20.016, 2) '20.02' &gt;&gt;&gt; "%g" % round(20, 2) '20' </code></pre>
5
2009-11-16T15:55:14Z
[ "python", "string", "floating-point" ]
Convert float to string with cutting zero decimals afer point in Python
1,742,937
<p>I am having difficulty converting a float to string in the following manner:</p> <pre><code>20.02 --&gt; 20.02 20.016 --&gt; 20.02 20.0 --&gt; 20 </code></pre> <p>It seems that<code>%g</code> format is the best for that, but I am getting strange results:</p> <pre><code>In [30]: "%.2g" % 20.03 Out[30]: '20' In...
8
2009-11-16T15:35:45Z
1,743,088
<p>Using <code>%f</code> format specifier:</p> <pre><code>('%.2f' % (value,)).rstrip('0').rstrip('.') </code></pre> <p>Using <code>round()</code> function:</p> <pre><code>str(round(value)).rstrip('0').rstrip('.') </code></pre>
10
2009-11-16T15:55:39Z
[ "python", "string", "floating-point" ]
How to sort model by values in a dictionary?
1,743,288
<p>In Django, I have a model, and I will have a dictionary having the id's of objects in this model as keys, and a weight as values. I would like to use these weights in an order_by:</p> <pre><code>MyModel.objects.filter(title__icontains=query).order_by( 'value_from_the_dictionary' ) </code></pre> <p>How to make this...
0
2009-11-16T16:32:40Z
1,743,332
<p>Sorting in <code>order_by</code> is done by the database, so if those elements aren't in the database you can't order by them. You will have to get the queryset and then do the ordering in Python.</p> <pre><code>qs = MyModel.objects.filter(title__icontains=query) qs.sort(key=lambda x: mydict[x]) </code></pre>
5
2009-11-16T16:39:52Z
[ "python", "django", "sorting", "sql-order-by" ]
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU?
1,743,293
<p>I use Python 2.5.4. My computer: CPU AMD <a href="http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3">Phenom X3</a> 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit. </p> <p>I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?. </p> ...
7
2009-11-16T16:33:15Z
1,743,302
<p>You bottleneck is probably somewhere else, like the hard-drive (paging), or memory access.</p>
0
2009-11-16T16:35:12Z
[ "python", "performance", "process", "multiprocessing", "cpu-usage" ]
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU?
1,743,293
<p>I use Python 2.5.4. My computer: CPU AMD <a href="http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3">Phenom X3</a> 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit. </p> <p>I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?. </p> ...
7
2009-11-16T16:33:15Z
1,743,312
<p>Try the <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> module, as Python, while it has real, native threads, will restrict their concurrent use while the GIL is held. Another alternative, and something you should look at if you need <em>real</em> speed, is writing a C extension mo...
21
2009-11-16T16:36:11Z
[ "python", "performance", "process", "multiprocessing", "cpu-usage" ]
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU?
1,743,293
<p>I use Python 2.5.4. My computer: CPU AMD <a href="http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3">Phenom X3</a> 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit. </p> <p>I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?. </p> ...
7
2009-11-16T16:33:15Z
1,743,335
<p>From CPU usage it looks like you're still running on a single core. Try running a trivial calculation with 3 or more threads with same threading code and see if it utilizes all cores. If it doesn't, something might be wrong with your threading code.</p>
1
2009-11-16T16:40:27Z
[ "python", "performance", "process", "multiprocessing", "cpu-usage" ]
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU?
1,743,293
<p>I use Python 2.5.4. My computer: CPU AMD <a href="http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3">Phenom X3</a> 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit. </p> <p>I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?. </p> ...
7
2009-11-16T16:33:15Z
1,743,350
<p>It appears that you have a 3-core CPU. If you want to use more than one CPU core in native Python code, you have to spawn multiple processes. (Two or more Python threads cannot run concurrently on different CPUs)</p> <p>As <em>R. Pate</em> said, Python's <code>multiprocessing</code> module is one way. However, I wo...
25
2009-11-16T16:42:55Z
[ "python", "performance", "process", "multiprocessing", "cpu-usage" ]
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU?
1,743,293
<p>I use Python 2.5.4. My computer: CPU AMD <a href="http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3">Phenom X3</a> 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit. </p> <p>I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?. </p> ...
7
2009-11-16T16:33:15Z
1,743,358
<p><strong>You should perform some Operating System and Python monitoring to determine where the bottle neck is.</strong></p> <p>Here is some info for windows 7:</p> <p><strong>Performance Monitor</strong>: You can use Windows Performance Monitor to examine how programs you run affect your computer’s performance, b...
0
2009-11-16T16:43:44Z
[ "python", "performance", "process", "multiprocessing", "cpu-usage" ]
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU?
1,743,293
<p>I use Python 2.5.4. My computer: CPU AMD <a href="http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3">Phenom X3</a> 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit. </p> <p>I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?. </p> ...
7
2009-11-16T16:33:15Z
1,743,362
<p><a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock">Global Interpreter Lock</a></p> <blockquote> <p>The reasons of employing such a lock include:</p> <pre><code>* increased speed of single-threaded programs (no necessity to acquire or release locks on all data structures separately) * easy integ...
10
2009-11-16T16:44:30Z
[ "python", "performance", "process", "multiprocessing", "cpu-usage" ]
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU?
1,743,293
<p>I use Python 2.5.4. My computer: CPU AMD <a href="http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3">Phenom X3</a> 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit. </p> <p>I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?. </p> ...
7
2009-11-16T16:33:15Z
1,743,402
<p>What about <a href="http://www.stackless.com/" rel="nofollow">Stackless Python</a>?</p>
1
2009-11-16T16:51:10Z
[ "python", "performance", "process", "multiprocessing", "cpu-usage" ]
Differences between Go and Cython
1,743,526
<p>Today a great friend of mine asked me what are the main differences between the newest Go language and <a href="http://www.cython.org/" rel="nofollow">Cython</a>, which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython?</p>
4
2009-11-16T17:12:34Z
1,743,546
<p>GO introduces goroutines and channels. See language <a href="http://golang.org/doc/go%5Flang%5Ffaq.html#goroutines" rel="nofollow">FAQ</a></p>
1
2009-11-16T17:15:24Z
[ "python", "go", "cython" ]
Differences between Go and Cython
1,743,526
<p>Today a great friend of mine asked me what are the main differences between the newest Go language and <a href="http://www.cython.org/" rel="nofollow">Cython</a>, which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython?</p>
4
2009-11-16T17:12:34Z
1,744,135
<p>Differences? Pretty much everything!</p> <ul> <li>Concurrency and channels.</li> <li>Interfaces.</li> <li>Static typechecking.</li> <li>...</li> </ul>
3
2009-11-16T18:57:22Z
[ "python", "go", "cython" ]
Differences between Go and Cython
1,743,526
<p>Today a great friend of mine asked me what are the main differences between the newest Go language and <a href="http://www.cython.org/" rel="nofollow">Cython</a>, which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython?</p>
4
2009-11-16T17:12:34Z
1,748,038
<p>My main reason for trying out go is the supposed ease of introducing concurrency into programs. I think that will be the 'next big thing', as processor speeds will tail off, and increasingly multiple cores are available. If you want to make use of multicore processors, you need to write your program so that it can...
1
2009-11-17T10:50:17Z
[ "python", "go", "cython" ]
Differences between Go and Cython
1,743,526
<p>Today a great friend of mine asked me what are the main differences between the newest Go language and <a href="http://www.cython.org/" rel="nofollow">Cython</a>, which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython?</p>
4
2009-11-16T17:12:34Z
1,749,058
<p>Cython isn't really a language in the conventional sense. It is a preprocessor for building Python extensions that takes Python-like syntax (actually they strive for full Python compatibility) and produces C code (using the Python C API). Doing this they are able to include some special case optimisations, but the r...
8
2009-11-17T13:55:04Z
[ "python", "go", "cython" ]
Differences between Go and Cython
1,743,526
<p>Today a great friend of mine asked me what are the main differences between the newest Go language and <a href="http://www.cython.org/" rel="nofollow">Cython</a>, which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython?</p>
4
2009-11-16T17:12:34Z
3,779,421
<p>gevent is a concurrent library that uses Cython at its core. It seems to be pretty fast: <a href="http://nichol.as/asynchronous-servers-in-python" rel="nofollow">http://nichol.as/asynchronous-servers-in-python</a></p>
4
2010-09-23T14:27:18Z
[ "python", "go", "cython" ]
Differences between Go and Cython
1,743,526
<p>Today a great friend of mine asked me what are the main differences between the newest Go language and <a href="http://www.cython.org/" rel="nofollow">Cython</a>, which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython?</p>
4
2009-11-16T17:12:34Z
4,437,778
<p>What about support. You are relying on a single compiler, provided by Google. What if Go folds or goes commercial?</p> <p>With Cython you could always go back to Python (or port the C code) if the Cython project folded.</p> <p><em>UPDATE: I must say that I am now upset with Cython.</em> <strong><em>The lack of thr...
1
2010-12-14T09:43:06Z
[ "python", "go", "cython" ]
Conflicting Python Packages How can it be Resolved?
1,743,596
<p>So we went to implement something today, and discovered that there already is several applications relying on the old implementation of our inhouse python library. Called <code>cis_py</code>. Now all applications for our implementation currently sit in a folder called, bin. This is where <code>cis_py</code> currentl...
0
2009-11-16T17:20:20Z
1,743,646
<p>Try <code>import sys; sys.path.insert(0, "cis")</code> as the very start of your main Python file.</p>
4
2009-11-16T17:29:20Z
[ "python", "packages" ]
Conflicting Python Packages How can it be Resolved?
1,743,596
<p>So we went to implement something today, and discovered that there already is several applications relying on the old implementation of our inhouse python library. Called <code>cis_py</code>. Now all applications for our implementation currently sit in a folder called, bin. This is where <code>cis_py</code> currentl...
0
2009-11-16T17:20:20Z
1,743,675
<p>Step one is to start telling people about this issue. Talk to your co-workers and boss and inform them of the problem you discovered, since it is <em>possible</em> that the go-live will have to be called off or postponed while a solution is worked on. Changes will have to be made somewhere, and it would be good (a...
0
2009-11-16T17:36:02Z
[ "python", "packages" ]
Conflicting Python Packages How can it be Resolved?
1,743,596
<p>So we went to implement something today, and discovered that there already is several applications relying on the old implementation of our inhouse python library. Called <code>cis_py</code>. Now all applications for our implementation currently sit in a folder called, bin. This is where <code>cis_py</code> currentl...
0
2009-11-16T17:20:20Z
1,743,728
<p>Add a version to the name: cis_py2. You may have to make changes in the class, but nothing that can't be done with a quick script (don't run this without testing it first):</p> <pre><code>sed 's/cis_py/cis_py2/g' `find -name '.py$'` </code></pre> <p>This assumes that cis_py is only the module name and nothing else...
0
2009-11-16T17:44:18Z
[ "python", "packages" ]
Conflicting Python Packages How can it be Resolved?
1,743,596
<p>So we went to implement something today, and discovered that there already is several applications relying on the old implementation of our inhouse python library. Called <code>cis_py</code>. Now all applications for our implementation currently sit in a folder called, bin. This is where <code>cis_py</code> currentl...
0
2009-11-16T17:20:20Z
1,744,648
<p>It looks like Alex Martelli's solution solved the emergency for you. Here's another solution, one I think better for the long term.</p> <p>In source files, replace the line</p> <pre><code>import cis_py </code></pre> <p>with the line</p> <pre><code>import cis.cis_py as cis_py </code></pre> <p>That way, when lat...
1
2009-11-16T20:28:23Z
[ "python", "packages" ]
Django Admin: OneToOne Relation as an Inline?
1,744,203
<p>I am putting together the admin for a satchmo application. Satchmo uses OneToOne relations to extend the base <code>Product</code> model, and I'd like to edit it all on one page.</p> <p>It is possible to have a OneToOne relation as an Inline? If not, what is the best way to add a few fields to a given page of my ad...
38
2009-11-16T19:10:26Z
1,744,445
<p>It's perfectly possible to use an inline for a OneToOne relationship. However, the actual field defining the relationship has to be on the inline model, not the parent one - in just the same way as for a ForeignKey. Switch it over and it will work.</p> <p><strong>Edit after comment</strong>: you say the parent mode...
53
2009-11-16T19:49:49Z
[ "python", "django", "django-admin", "inline", "one-to-one" ]
Django Admin: OneToOne Relation as an Inline?
1,744,203
<p>I am putting together the admin for a satchmo application. Satchmo uses OneToOne relations to extend the base <code>Product</code> model, and I'd like to edit it all on one page.</p> <p>It is possible to have a OneToOne relation as an Inline? If not, what is the best way to add a few fields to a given page of my ad...
38
2009-11-16T19:10:26Z
2,440,684
<p>Referring to the last question, what would be the best solution for multiple sub-types. E.g class Product with sub-type class Book and sub-type class CD. The way shown here you would have to edit a product the general items plus the sub-type items for book AND the sub-type items for CD. So even if you only want to a...
2
2010-03-14T00:24:43Z
[ "python", "django", "django-admin", "inline", "one-to-one" ]
Django Admin: OneToOne Relation as an Inline?
1,744,203
<p>I am putting together the admin for a satchmo application. Satchmo uses OneToOne relations to extend the base <code>Product</code> model, and I'd like to edit it all on one page.</p> <p>It is possible to have a OneToOne relation as an Inline? If not, what is the best way to add a few fields to a given page of my ad...
38
2009-11-16T19:10:26Z
12,640,250
<p>Maybe use inheritance instead OneToOne relationship</p> <pre><code>class Product(models.Model): name = models.CharField(max_length=100) ... class MyProduct(Product): ..... </code></pre> <p>Or use proxy classes</p> <pre><code>class ProductProxy(Product) class Meta: proxy = True </code></pr...
4
2012-09-28T12:42:57Z
[ "python", "django", "django-admin", "inline", "one-to-one" ]
Django Admin: OneToOne Relation as an Inline?
1,744,203
<p>I am putting together the admin for a satchmo application. Satchmo uses OneToOne relations to extend the base <code>Product</code> model, and I'd like to edit it all on one page.</p> <p>It is possible to have a OneToOne relation as an Inline? If not, what is the best way to add a few fields to a given page of my ad...
38
2009-11-16T19:10:26Z
13,877,317
<p>You can also try setting 'parent_link=True' on your OneToOneField?</p> <p><a href="https://docs.djangoproject.com/en/dev/topics/db/models/#specifying-the-parent-link-field" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/db/models/#specifying-the-parent-link-field</a></p>
1
2012-12-14T10:57:55Z
[ "python", "django", "django-admin", "inline", "one-to-one" ]
Windows with Plesk Panel installs ActiveState Python 2.5.0 - any thoughts?
1,744,243
<p>I expect to run Pylons on a Windows Server 2003 and IIS 6 on a Virtual Private Server (VPS). Most work with the VPS is done through the Plesk 8.6 panel. The Plesk panel has a lot of maintenance advantages for us. However, this Plesk configuration installs ActiveState Python 2.5.0. The Parallels Plesk documents for 8...
1
2009-11-16T19:17:05Z
1,801,127
<p>The default Python install location is something like c:\python26. I think it's likely you could install the latest python there, without it conflicting with the ActiveState Python. (You may have to deal with path issues or conflicts over which copy 'owns' python source files in Explorer, though.)</p>
0
2009-11-26T01:42:46Z
[ "python", "pylons", "virtualenv", "plesk", "activestate" ]
Is `import module` better coding style than `from module import function`?
1,744,258
<p>Let <code>from module import function</code> be called the FMIF coding style.</p> <p>Let <code>import module</code> be called the IM coding style.</p> <p>Let <code>from package import module</code> be called the FPIM coding style.</p> <p>Why is IM+FPIM considered a better coding style than FMIF? (See <a href="htt...
53
2009-11-16T19:18:49Z
1,744,336
<p>The classic text on this, as so often, is from Fredrik Lundh, the effbot. His advice: <a href="http://effbot.org/zone/import-confusion.htm">always use import</a> - except when you shouldn't.</p> <p>In other words, be sensible. Personally I find that anything that's several modules deep tends to get imported via <co...
15
2009-11-16T19:32:11Z
[ "python", "python-import" ]
Is `import module` better coding style than `from module import function`?
1,744,258
<p>Let <code>from module import function</code> be called the FMIF coding style.</p> <p>Let <code>import module</code> be called the IM coding style.</p> <p>Let <code>from package import module</code> be called the FPIM coding style.</p> <p>Why is IM+FPIM considered a better coding style than FMIF? (See <a href="htt...
53
2009-11-16T19:18:49Z
1,744,439
<p>The negatives you list for IM/FPIM can often be ameliorated by appropriate use of an <code>as</code> clause. <code>from some.package import mymodulewithalongname as mymod</code> can usefully shorten your code and enhance its readability, and if you rename <code>mymodulewithalongname</code> to <code>somethingcomplet...
34
2009-11-16T19:49:15Z
[ "python", "python-import" ]
Is `import module` better coding style than `from module import function`?
1,744,258
<p>Let <code>from module import function</code> be called the FMIF coding style.</p> <p>Let <code>import module</code> be called the IM coding style.</p> <p>Let <code>from package import module</code> be called the FPIM coding style.</p> <p>Why is IM+FPIM considered a better coding style than FMIF? (See <a href="htt...
53
2009-11-16T19:18:49Z
1,744,584
<p>Like Alex Martelli, I am fond of using <code>as</code> when importing a function.</p> <p>One thing I have done is to use some prefix on all the functions that were imported from the same module:</p> <pre><code>from random import seed as r_seed from random import random as r_random </code></pre> <p><code>r_seed</c...
5
2009-11-16T20:16:09Z
[ "python", "python-import" ]
Is `import module` better coding style than `from module import function`?
1,744,258
<p>Let <code>from module import function</code> be called the FMIF coding style.</p> <p>Let <code>import module</code> be called the IM coding style.</p> <p>Let <code>from package import module</code> be called the FPIM coding style.</p> <p>Why is IM+FPIM considered a better coding style than FMIF? (See <a href="htt...
53
2009-11-16T19:18:49Z
19,827,467
<p>Great answers here (I upvoted them all), and here are my thoughts on this matter:</p> <p>First, addressing each of your bullets:</p> <p><strong>(Allegedly) Pros of FMIF:</strong></p> <ul> <li><em>Shortness of code: shorter function names help stick to the 80 columns-per-line.</em></li> </ul> <p>Perhaps, but modu...
4
2013-11-07T03:26:18Z
[ "python", "python-import" ]
Is `import module` better coding style than `from module import function`?
1,744,258
<p>Let <code>from module import function</code> be called the FMIF coding style.</p> <p>Let <code>import module</code> be called the IM coding style.</p> <p>Let <code>from package import module</code> be called the FPIM coding style.</p> <p>Why is IM+FPIM considered a better coding style than FMIF? (See <a href="htt...
53
2009-11-16T19:18:49Z
19,885,414
<p>I agree with MestreLion the most here (and so an upvote). </p> <p>My perspective: I review code frequently that I am unfamiliar with, and not knowing what module a function is coming from just looking at the function is quite frustrating. </p> <p>Code is written once and read many times, and so readability and mai...
1
2013-11-10T01:56:54Z
[ "python", "python-import" ]
Does Django cache templates automatically?
1,744,339
<p>I'm new to Django and trying to implement a voting system between two images. However, it looks like the page is being cached or something because when I refresh it, some values are wrong. I have no cache setup in my Settings.</p> <p>Here is the View:</p> <pre><code>def rate(request, type): photos = Photo.ob...
3
2009-11-16T19:32:46Z
1,744,450
<p><code>order_by('?')</code> means that the list is ordered in <em>random</em> order, so <code>{{ photos.0 }}</code> will be different each time you load the page. </p> <p>Also:</p> <pre><code>&lt;a href="/rate/vote/{{photos.1.id}}/{{photos.0.id}}" class="vote"&gt;Vote&lt;/a&gt; ^^^ ...
1
2009-11-16T19:51:16Z
[ "python", "django", "caching", "django-templates" ]
Does Django cache templates automatically?
1,744,339
<p>I'm new to Django and trying to implement a voting system between two images. However, it looks like the page is being cached or something because when I refresh it, some values are wrong. I have no cache setup in my Settings.</p> <p>Here is the View:</p> <pre><code>def rate(request, type): photos = Photo.ob...
3
2009-11-16T19:32:46Z
1,744,582
<p>Django doesn't cache these sorts of things by default. Make sure that your browser/isp/etc. isn't caching it.</p> <p>It looks like your database query isn't returning what you're expecting. Check that directly via your debugger or with print statement debugging if you have to.</p> <p>That said, you really need to ...
1
2009-11-16T20:15:28Z
[ "python", "django", "caching", "django-templates" ]
Does Django cache templates automatically?
1,744,339
<p>I'm new to Django and trying to implement a voting system between two images. However, it looks like the page is being cached or something because when I refresh it, some values are wrong. I have no cache setup in my Settings.</p> <p>Here is the View:</p> <pre><code>def rate(request, type): photos = Photo.ob...
3
2009-11-16T19:32:46Z
1,744,686
<p>Taking a look at this in some of my code, I have this in my template:</p> <pre><code>{{ mytable.0.pk }} {{ mytable.1.pk }} {{ mytable.0.pk }} {{ mytable.3.pk }} </code></pre> <p>And I get this output:</p> <pre><code>91596 54774 156800 23593 </code></pre> <p>Odd, until you consider that django executes database q...
7
2009-11-16T20:35:45Z
[ "python", "django", "caching", "django-templates" ]
Embedding a control in a QTableView?
1,744,348
<p>I'm working a small qt app (using PyQt4) and I've come up with an idea but I'm unsure as to how to implement it. I have a QTableView that represents some data and I'd like to add another column to the QTableView that contains a checkbox control that could be wired up to some piece of the model. For example, somethin...
2
2009-11-16T19:34:53Z
1,744,428
<p>In Qt/C++ you can create a delegate for custom items in a column. I would assume you can do something very similar in PyQt. See the following examples:</p> <p><a href="http://doc.trolltech.com/4.5/itemviews-stardelegate.html" rel="nofollow">Star Delegate Example</a><br> <a href="http://doc.trolltech.com/4.5/itemvie...
1
2009-11-16T19:47:47Z
[ "python", "qt", "pyqt4", "tableview" ]
Embedding a control in a QTableView?
1,744,348
<p>I'm working a small qt app (using PyQt4) and I've come up with an idea but I'm unsure as to how to implement it. I have a QTableView that represents some data and I'd like to add another column to the QTableView that contains a checkbox control that could be wired up to some piece of the model. For example, somethin...
2
2009-11-16T19:34:53Z
1,744,957
<p>You could also have a look at the QStandardItemModel, which gives you an interface to interact with items through a "checkable" state !</p> <p>You could also inherit from QAbstractItemModel and use the role Qt::CheckStateRole...</p>
3
2009-11-16T21:25:52Z
[ "python", "qt", "pyqt4", "tableview" ]
Embedding a control in a QTableView?
1,744,348
<p>I'm working a small qt app (using PyQt4) and I've come up with an idea but I'm unsure as to how to implement it. I have a QTableView that represents some data and I'd like to add another column to the QTableView that contains a checkbox control that could be wired up to some piece of the model. For example, somethin...
2
2009-11-16T19:34:53Z
1,746,130
<p>Implementing your own table model is more work than using <code>QStandardItemModel</code> (as @Andy recommends), but it does give you a fine control over what you want to do, so I'll try to give you a summary of what to do. I assume you know all about <a href="http://doc.trolltech.com" rel="nofollow">Qt's documenta...
6
2009-11-17T01:57:24Z
[ "python", "qt", "pyqt4", "tableview" ]
Automating old DOS application using Python
1,744,796
<p>Is there a way to automate an old DOS application (16-bit, probably needs an emulator such as DOSBox) from Python (on Windows)? I would like to send keys and strings to the application, detect updates to the DOS "screen" and get the application output.</p> <p>It would be even better if the DOS application could run...
2
2009-11-16T20:54:42Z
1,745,037
<p>Sorry, can't reply yet so you're getting an 'answer' instead. </p> <p>This question is probably closely related to this <a href="http://stackoverflow.com/questions/1124884/interact-with-a-windows-console-application-via-python">Stack Overflow question.</a></p>
1
2009-11-16T21:41:39Z
[ "python", "automation", "dos", "sendkeys", "dosbox" ]
Automating old DOS application using Python
1,744,796
<p>Is there a way to automate an old DOS application (16-bit, probably needs an emulator such as DOSBox) from Python (on Windows)? I would like to send keys and strings to the application, detect updates to the DOS "screen" and get the application output.</p> <p>It would be even better if the DOS application could run...
2
2009-11-16T20:54:42Z
1,748,584
<p>I'm not familiar with DosBOX or whether it has an external API. However, for Sun VirtualBox there is a python API, so if it is OK to run DOS on a VM, you could easily use the VirtualBox Python API to control &amp; automate the application you run on the DOS.</p> <p>You can download the VirtualBox SDK <a href="http:...
1
2009-11-17T12:36:00Z
[ "python", "automation", "dos", "sendkeys", "dosbox" ]
Read from File, or STDIN
1,744,989
<p>I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage</p> <pre><code>tool -d character -f integer [filena...
31
2009-11-16T21:32:22Z
1,745,008
<p>The <a href="http://docs.python.org/library/fileinput.html">fileinput</a> module may do what you want - assuming the non-option arguments are in <code>args</code> then:</p> <pre><code>import fileinput for line in fileinput.input(args): print line </code></pre> <p>If <code>args</code> is empty then <code>filein...
43
2009-11-16T21:35:51Z
[ "python", "file", "command-line", "arguments", "stdin" ]
Read from File, or STDIN
1,744,989
<p>I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage</p> <pre><code>tool -d character -f integer [filena...
31
2009-11-16T21:32:22Z
1,745,035
<p>In the simplest terms:</p> <pre><code>import sys # parse command line if file_name_given: inf = open(file_name_given) else: inf = sys.stdin </code></pre> <p>At this point you would use <code>inf</code> to read from the file. Depending on whether a filename was given, this would read from the given file or ...
30
2009-11-16T21:40:54Z
[ "python", "file", "command-line", "arguments", "stdin" ]
Read from File, or STDIN
1,744,989
<p>I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage</p> <pre><code>tool -d character -f integer [filena...
31
2009-11-16T21:32:22Z
1,745,101
<p>Something like:</p> <pre><code>if input_from_file: f = open(file_name, "rt") else: f = sys.stdin inL = f.readline() while inL: print inL.rstrip() inL = f.readline() </code></pre>
0
2009-11-16T21:54:11Z
[ "python", "file", "command-line", "arguments", "stdin" ]
Read from File, or STDIN
1,744,989
<p>I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage</p> <pre><code>tool -d character -f integer [filena...
31
2009-11-16T21:32:22Z
19,802,578
<p>To make use of python's <code>with</code> statement, one can use the following code:</p> <pre><code>import sys with open(sys.argv[1], 'r') if len(sys.argv) &gt; 1 else sys.stdin as f: # read data using f # ...... </code></pre>
8
2013-11-06T01:49:06Z
[ "python", "file", "command-line", "arguments", "stdin" ]
Read from File, or STDIN
1,744,989
<p>I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage</p> <pre><code>tool -d character -f integer [filena...
31
2009-11-16T21:32:22Z
28,141,462
<p>I prefer to use "-" as an indicator that you should read from stdin, it's more explicit:</p> <pre><code>import sys with open(sys.argv[1], 'r') if sys.argv[1] is not "-" else sys.stdin as f: pass # do something here </code></pre>
2
2015-01-25T21:00:51Z
[ "python", "file", "command-line", "arguments", "stdin" ]
Read from File, or STDIN
1,744,989
<p>I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage</p> <pre><code>tool -d character -f integer [filena...
31
2009-11-16T21:32:22Z
29,824,059
<p>I like the general idiom of using a context manager, but the (too) trivial solution ends up closing <code>sys.stdin</code> when you are out of the <code>with</code> statement, which I want to avoid.</p> <p>Borrowing from <a href="http://stackoverflow.com/a/17603000/874188">this answer</a>, here is a workaround:</p>...
4
2015-04-23T12:53:48Z
[ "python", "file", "command-line", "arguments", "stdin" ]
Convert date Python
1,745,042
<p>I have <code>MMDDYY</code> dates, i.e. today is <code>111609</code></p> <p>How do I convert this to <code>11/16/2009</code>, in Python?</p>
3
2009-11-16T21:42:22Z
1,745,076
<p>I suggest the following:</p> <pre><code>import datetime date = datetime.datetime.strptime("111609", "%m%d%y") print date.strftime("%m/%d/%Y") </code></pre> <p>This will convert <code>010199</code> to <code>01/01/1999</code> and <code>010109</code> to <code>01/01/2009</code>.</p>
15
2009-11-16T21:49:07Z
[ "python", "date" ]
Convert date Python
1,745,042
<p>I have <code>MMDDYY</code> dates, i.e. today is <code>111609</code></p> <p>How do I convert this to <code>11/16/2009</code>, in Python?</p>
3
2009-11-16T21:42:22Z
1,745,082
<pre><code>date = '111609' new_date = date[0:2] + '/' + date[2:4] + '/' + date[4:6] </code></pre>
0
2009-11-16T21:50:11Z
[ "python", "date" ]
Convert date Python
1,745,042
<p>I have <code>MMDDYY</code> dates, i.e. today is <code>111609</code></p> <p>How do I convert this to <code>11/16/2009</code>, in Python?</p>
3
2009-11-16T21:42:22Z
1,745,118
<pre><code>&gt;&gt;&gt; s = '111609' &gt;&gt;&gt; d = datetime.date(int('20' + s[4:6]), int(s[0:2]), int(s[2:4])) &gt;&gt;&gt; # or, alternatively (and better!), as initially shown here, by Tim &gt;&gt;&gt; # d = datetime.datetime.strptime(s, "%m%d%y") &gt;&gt;&gt; d.strftime('%m/%d/%Y') '11/16/2009' </code></pre> <p>...
0
2009-11-16T21:57:19Z
[ "python", "date" ]
Solving thread cleanup on paramiko
1,745,232
<p>I have an automated process using paramiko and have this error:</p> <pre><code>Exception in thread Thread-1 (most likely raised during interpreter shutdown) .... .... &lt;type 'exceptions.AttributeError'&gt;: 'NoneType' object has no attribute 'error' </code></pre> <p>I understand that is a problem in the clea...
10
2009-11-16T22:21:36Z
1,745,344
<p><code>__del__</code> is not a deconstructor. It's called when you delete a object's last name, which doesn't nessesarily happen when you exit the interpreter. </p> <p>Anything that manages a context, such as connections, is a <a href="http://docs.python.org/library/stdtypes.html#typecontextmanager"><code>context ma...
7
2009-11-16T22:45:44Z
[ "python", "ssh", "paramiko" ]
Solving thread cleanup on paramiko
1,745,232
<p>I have an automated process using paramiko and have this error:</p> <pre><code>Exception in thread Thread-1 (most likely raised during interpreter shutdown) .... .... &lt;type 'exceptions.AttributeError'&gt;: 'NoneType' object has no attribute 'error' </code></pre> <p>I understand that is a problem in the clea...
10
2009-11-16T22:21:36Z
1,750,151
<p>Close your connections in the normal program control flow, not in <code>__del__</code>, as @THC4k said, it's not a deconstructor, and in general, you <em>shouldn't</em> need to use <code>__del__</code> (of course there are exceptions).</p> <p>If you're creating your own threads, you need to .setDaemon(True) if you ...
1
2009-11-17T16:41:35Z
[ "python", "ssh", "paramiko" ]
Solving thread cleanup on paramiko
1,745,232
<p>I have an automated process using paramiko and have this error:</p> <pre><code>Exception in thread Thread-1 (most likely raised during interpreter shutdown) .... .... &lt;type 'exceptions.AttributeError'&gt;: 'NoneType' object has no attribute 'error' </code></pre> <p>I understand that is a problem in the clea...
10
2009-11-16T22:21:36Z
6,844,288
<p>I now, is not the case. But a find this discussion, searching a problem whit my wxpython app.</p> <p>Solve it to add a close event to the main frame. So all the thread's will be close.</p> <pre><code>class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): super(MyFrame, self).__init__(*args, **kw...
1
2011-07-27T12:28:56Z
[ "python", "ssh", "paramiko" ]
Structured programming and Python generators?
1,745,333
<p><strong>Update:</strong> What I really wanted all along were <a href="http://pypi.python.org/pypi/greenlet" rel="nofollow">greenlets</a>.</p> <hr> <p><strong>Note:</strong> This question mutated a bit as people answered and forced me to "raise the stakes", as my trivial examples had trivial simplifications; rather...
6
2009-11-16T22:43:30Z
1,745,370
<pre><code>import itertools def quadraticRange(n): for i in xrange(n) yield i*i def sillyGenerator(): return itertools.chain( quadraticRange(10), quadraticRange(12), quadraticRange(8), ) def sillyGenerator2(): return itertools.chain.from_iterable( quadraticRange(n) for n in [10, 12, 8]) <...
3
2009-11-16T22:50:25Z
[ "python", "generator" ]
Structured programming and Python generators?
1,745,333
<p><strong>Update:</strong> What I really wanted all along were <a href="http://pypi.python.org/pypi/greenlet" rel="nofollow">greenlets</a>.</p> <hr> <p><strong>Note:</strong> This question mutated a bit as people answered and forced me to "raise the stakes", as my trivial examples had trivial simplifications; rather...
6
2009-11-16T22:43:30Z
1,745,371
<p>You want to <a href="http://docs.python.org/library/itertools.html#itertools.chain" rel="nofollow">chain several iterators</a> together:</p> <pre><code>from itertools import chain def sillyGenerator(a,b,c): return chain(quadraticRange(a),quadraticRange(b),quadraticRange(c)) </code></pre>
6
2009-11-16T22:50:30Z
[ "python", "generator" ]
Structured programming and Python generators?
1,745,333
<p><strong>Update:</strong> What I really wanted all along were <a href="http://pypi.python.org/pypi/greenlet" rel="nofollow">greenlets</a>.</p> <hr> <p><strong>Note:</strong> This question mutated a bit as people answered and forced me to "raise the stakes", as my trivial examples had trivial simplifications; rather...
6
2009-11-16T22:43:30Z
1,745,429
<p>For an arbitrary number of calls to <code>quadraticRange</code>:</p> <pre><code>from itertools import chain def sillyGenerator(*args): return chain(*map(quadraticRange, args)) </code></pre> <p>This code uses <a href="http://docs.python.org/3.1/library/functions.html#map" rel="nofollow"><code>map</code></a> an...
2
2009-11-16T23:02:13Z
[ "python", "generator" ]
Structured programming and Python generators?
1,745,333
<p><strong>Update:</strong> What I really wanted all along were <a href="http://pypi.python.org/pypi/greenlet" rel="nofollow">greenlets</a>.</p> <hr> <p><strong>Note:</strong> This question mutated a bit as people answered and forced me to "raise the stakes", as my trivial examples had trivial simplifications; rather...
6
2009-11-16T22:43:30Z
1,745,463
<p>There is a Python Enhancement Proposal for providing a <a href="http://www.python.org/dev/peps/pep-0380/" rel="nofollow"><code>yield from</code> statement</a> for "delegating generation". Your example would be written as:</p> <pre><code>def sillyGenerator(): sq = lambda i: i * i yield from map(sq, xrange(10)) ...
3
2009-11-16T23:09:37Z
[ "python", "generator" ]