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
Data Structure for storing a sorting field to efficiently allow modifications
1,640,664
<p>I'm using Django and PostgreSQL, but I'm not absolutely tied to the Django ORM if there's a better way to do this with raw SQL or database specific operations.</p> <p>I've got a model that needs sequential ordering. Lookup operations will generally retrieve the entire list in order. The most common operation on thi...
7
2009-10-28T22:54:48Z
1,661,702
<p>A temp table and a transaction should maintain atomicity and the unique constraint on sort order. Restating the problem, you want to go from:</p> <pre><code>A 10 to B 10 B 25 C 25 C 26 E 26 E 34 A 34 </code></pre> <p>Where there can be any number of items in between each row. So, first...
4
2009-11-02T14:44:40Z
[ "python", "database", "django", "sorting", "data-structures" ]
Get json data via url and use in python (simplejson)
1,640,715
<p>I imagine this must have a simple answer, but I am struggling: I want to take a url (which outputs json) and get the data in a usable dictionary in python. I am stuck on the last step.</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; import simplejson &gt;&gt;&gt; req = urllib2.Request("http://vimeo.com/api...
38
2009-10-28T23:09:46Z
1,640,736
<p>Try </p> <pre><code>f = opener.open(req) simplejson.load(f) </code></pre> <p>without running f.read() first. When you run f.read(), the filehandle's contents are slurped so there is nothing left when your call <code>simplejson.load(f)</code></p>
43
2009-10-28T23:13:24Z
[ "python", "json", "urllib2", "simplejson" ]
Get json data via url and use in python (simplejson)
1,640,715
<p>I imagine this must have a simple answer, but I am struggling: I want to take a url (which outputs json) and get the data in a usable dictionary in python. I am stuck on the last step.</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; import simplejson &gt;&gt;&gt; req = urllib2.Request("http://vimeo.com/api...
38
2009-10-28T23:09:46Z
1,640,752
<p>The first line reads the entire file. The second line then tries to read more from the file, but there's nothing left:</p> <pre><code>&gt;&gt;&gt; f.read() # this works blah blah blah &gt;&gt;&gt; simplejson.load(f) </code></pre> <p>Either just omit the f.read() line, or save the value from read, and ...
10
2009-10-28T23:17:30Z
[ "python", "json", "urllib2", "simplejson" ]
Get json data via url and use in python (simplejson)
1,640,715
<p>I imagine this must have a simple answer, but I am struggling: I want to take a url (which outputs json) and get the data in a usable dictionary in python. I am stuck on the last step.</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; import simplejson &gt;&gt;&gt; req = urllib2.Request("http://vimeo.com/api...
38
2009-10-28T23:09:46Z
8,867,296
<p>There's an even easier way - you dont need simplejson at all. Python can parse json into a dict/array using the eval statement as long as you set true/false/null to the right values.</p> <pre><code># fetch the url url = "https://api.twitter.com/1/users/lookup.json?user_id=6253282,18949452" json = urllib2.urlopen(ur...
-7
2012-01-15T03:15:44Z
[ "python", "json", "urllib2", "simplejson" ]
post_save in django to update instance immediately
1,640,744
<p>I'm trying to immediately update a record after it's saved. This example may seem pointless but imagine we need to use an API after the data is saved to get some extra info and update the record:</p> <pre><code>def my_handler(sender, instance=False, **kwargs): t = Test.objects.filter(id=instance.id) t.blah ...
9
2009-10-28T23:15:36Z
1,640,767
<p>Doesn't the post_save handler take the instance? Why are you filtering using it? Why not just do:</p> <pre><code>def my_handler(sender, instance=False, created, **kwargs): if created: instance.blah = 'hello' instance.save() </code></pre> <p>Your existing code doesn't work because it loops, and <code>Te...
6
2009-10-28T23:21:45Z
[ "python", "django", "django-models" ]
post_save in django to update instance immediately
1,640,744
<p>I'm trying to immediately update a record after it's saved. This example may seem pointless but imagine we need to use an API after the data is saved to get some extra info and update the record:</p> <pre><code>def my_handler(sender, instance=False, **kwargs): t = Test.objects.filter(id=instance.id) t.blah ...
9
2009-10-28T23:15:36Z
1,641,021
<p>When you find yourself using a post_save signal to update an object of the sender class, chances are you should be overriding the save method instead. In your case, the model definition would look like:</p> <pre><code>class Test(models.Model): title = models.CharField('title', max_length=200) blah = models....
17
2009-10-29T00:41:56Z
[ "python", "django", "django-models" ]
PyQt: Trouble with asterisk on modification in QPlainTextEdit
1,640,878
<p>I'm having a problem with a QPlainTextEdit. I want the "contents have been modified" asterisk to appear in the title bar whenever the contents have been modified.</p> <p>In the example below, type a few letters. The asterisk appears as it should. Hit Ctrl+S, the asterisk disappears as it should. But then if you...
0
2009-10-28T23:55:25Z
1,641,011
<p>Never mind, figured it out. The problem was that in the save method I should've been calling self.document().setModified(False) instead of window.setWindowModified(False)</p>
1
2009-10-29T00:37:45Z
[ "python", "qt", "qt4", "pyqt", "pyqt4" ]
Does Python have “private” variables in classes?
1,641,219
<p>I'm coming from the Java world and reading Bruce Eckels' <em>Python 3 Patterns, Recipes and Idioms</em>. </p> <p>While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. </p> <p>So for example:</p> ...
273
2009-10-29T01:54:18Z
1,641,232
<p>Python has limited support for private identifiers, through a feature that automatically prepends the class name to any identifiers starting with two underscores. This is transparent to the programmer, for the most part, but the net effect is that any variables named this way can be used as private variables.</p> ...
6
2009-10-29T01:59:36Z
[ "python", "class", "private" ]
Does Python have “private” variables in classes?
1,641,219
<p>I'm coming from the Java world and reading Bruce Eckels' <em>Python 3 Patterns, Recipes and Idioms</em>. </p> <p>While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. </p> <p>So for example:</p> ...
273
2009-10-29T01:54:18Z
1,641,236
<p>It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you <em>really</em> want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages...
577
2009-10-29T02:01:29Z
[ "python", "class", "private" ]
Does Python have “private” variables in classes?
1,641,219
<p>I'm coming from the Java world and reading Bruce Eckels' <em>Python 3 Patterns, Recipes and Idioms</em>. </p> <p>While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. </p> <p>So for example:</p> ...
273
2009-10-29T01:54:18Z
1,641,305
<p>"In java, we have been taught about public/private/protected variables"</p> <p>"Why is that not required in python?"</p> <p>For the same reason it's not <em>required</em> in Java.</p> <p>You're free to use -- or not use <code>private</code> and <code>protected</code>.</p> <p>As a Python and Java programmer, I've...
40
2009-10-29T02:28:33Z
[ "python", "class", "private" ]
Does Python have “private” variables in classes?
1,641,219
<p>I'm coming from the Java world and reading Bruce Eckels' <em>Python 3 Patterns, Recipes and Idioms</em>. </p> <p>While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. </p> <p>So for example:</p> ...
273
2009-10-29T01:54:18Z
6,722,196
<p>private and protected concepts are very important. But python - just a tool for prototyping and rapid development with restricted resources available for development, that is why some of protection levels are not so strict followed in python. You can use "__" in class member, it works properly, but looks not good en...
3
2011-07-17T06:00:14Z
[ "python", "class", "private" ]
Does Python have “private” variables in classes?
1,641,219
<p>I'm coming from the Java world and reading Bruce Eckels' <em>Python 3 Patterns, Recipes and Idioms</em>. </p> <p>While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. </p> <p>So for example:</p> ...
273
2009-10-29T01:54:18Z
16,265,586
<p>The only time I ever use private variables is when I need to do other things when writing to or reading from the variable and as such I need to force the use of a setter and/or getter.</p> <p>Again this goes to culture, as already stated. I've been working on projects where reading and writing other classes variabl...
2
2013-04-28T17:22:44Z
[ "python", "class", "private" ]
Does Python have “private” variables in classes?
1,641,219
<p>I'm coming from the Java world and reading Bruce Eckels' <em>Python 3 Patterns, Recipes and Idioms</em>. </p> <p>While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. </p> <p>So for example:</p> ...
273
2009-10-29T01:54:18Z
25,614,597
<p>There is a variation of private variables in the underscore convention.</p> <pre><code>In [5]: class test(object): ...: def __private_method(self): ...: return "Boo" ...: def public_method(self): ...: return self.__private_method() ...: In [6]: x = test() In [7]: x.publ...
4
2014-09-02T01:19:15Z
[ "python", "class", "private" ]
Does Python have “private” variables in classes?
1,641,219
<p>I'm coming from the Java world and reading Bruce Eckels' <em>Python 3 Patterns, Recipes and Idioms</em>. </p> <p>While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. </p> <p>So for example:</p> ...
273
2009-10-29T01:54:18Z
26,965,993
<p>As correctly mentioned by many of the comments above, let's not forget the main goal of Access Modifiers: To help users of code understand what is supposed to change and what is supposed not to. When you see a private field you don't mess around with it. So it's mostly syntactic sugar which is easily achieved in Pyt...
11
2014-11-17T05:17:25Z
[ "python", "class", "private" ]
Does Python have “private” variables in classes?
1,641,219
<p>I'm coming from the Java world and reading Bruce Eckels' <em>Python 3 Patterns, Recipes and Idioms</em>. </p> <p>While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. </p> <p>So for example:</p> ...
273
2009-10-29T01:54:18Z
32,802,486
<p>private variables in python is more or less a hack, which means the interpreter intentionally rename the variable</p> <pre><code>class A: def __int__(self): self.__var1 = 123 def printVar1(self): print self.__var1 </code></pre> <p>and now if you try to access <strong>__var1</strong> outside...
20
2015-09-26T22:06:06Z
[ "python", "class", "private" ]
Python - Working around memory leaks
1,641,231
<p>I have a Python program that runs a series of experiments, with no data intended to be stored from one test to another. My code contains a memory leak which I am completely unable to find (I've look at the <a href="http://stackoverflow.com/questions/1435415/python-memory-leaks/1641009">other threads</a> on memory le...
24
2009-10-29T01:58:58Z
1,641,253
<p>I would simply refactor the experiments into individual functions (if not like that already) then accept an experiment number from the command line which calls the single experiment function.</p> <p>The just bodgy up a shell script as follows:</p> <pre><code>#!/bin/bash for expnum in 1 2 3 4 5 6 7 8 9 10 11 ; do ...
2
2009-10-29T02:06:39Z
[ "python", "memory-leaks" ]
Python - Working around memory leaks
1,641,231
<p>I have a Python program that runs a series of experiments, with no data intended to be stored from one test to another. My code contains a memory leak which I am completely unable to find (I've look at the <a href="http://stackoverflow.com/questions/1435415/python-memory-leaks/1641009">other threads</a> on memory le...
24
2009-10-29T01:58:58Z
1,641,265
<p>Threads would not help. If you must give up on finding the leak, then the only solution to contain its effect is running a new <em>process</em> once in a while (e.g., when a test has left overall memory consumption too high for your liking -- you can determine VM size easily by reading <code>/proc/self/status</code...
4
2009-10-29T02:11:17Z
[ "python", "memory-leaks" ]
Python - Working around memory leaks
1,641,231
<p>I have a Python program that runs a series of experiments, with no data intended to be stored from one test to another. My code contains a memory leak which I am completely unable to find (I've look at the <a href="http://stackoverflow.com/questions/1435415/python-memory-leaks/1641009">other threads</a> on memory le...
24
2009-10-29T01:58:58Z
1,641,280
<p>You can use something like this to help track down memory leaks</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; from gc import get_objects &gt;&gt;&gt; before = defaultdict(int) &gt;&gt;&gt; after = defaultdict(int) &gt;&gt;&gt; for i in get_objects(): ... before[type(i)] += 1 ... ...
41
2009-10-29T02:19:30Z
[ "python", "memory-leaks" ]
Python - Working around memory leaks
1,641,231
<p>I have a Python program that runs a series of experiments, with no data intended to be stored from one test to another. My code contains a memory leak which I am completely unable to find (I've look at the <a href="http://stackoverflow.com/questions/1435415/python-memory-leaks/1641009">other threads</a> on memory le...
24
2009-10-29T01:58:58Z
9,353,316
<p>I had the same problem with a third party C library which was leaking. The most clean work-around that I could think of was to fork and wait. The advantage of it is that you don't even have to create a separate process after each run. You can define the size of your batch.</p> <p>Here's a general solution (if yo...
2
2012-02-19T21:14:24Z
[ "python", "memory-leaks" ]
Why can't Python find my path? (django)
1,641,393
<pre><code>import sys sys.path.append('/home/myuser/svn-repos/myproject') from myproject.settings import * </code></pre> <p>But, it says module not found when I run the script? By the way, settings.py has been set up and manage.py syncdb works.</p>
0
2009-10-29T03:02:39Z
1,641,406
<p>You want <code>sys.path.append('/home/myuser/svn-repos')</code> instead. Then when you <code>import myproject</code>, it looks in <code>svn-repos</code> for the <code>myproject</code> folder, and looks in that for <code>settings</code>.</p> <p>Alternatively, leave it as is and just <code>import settings</code>. Thi...
3
2009-10-29T03:06:53Z
[ "python", "django" ]
Why can't Python find my path? (django)
1,641,393
<pre><code>import sys sys.path.append('/home/myuser/svn-repos/myproject') from myproject.settings import * </code></pre> <p>But, it says module not found when I run the script? By the way, settings.py has been set up and manage.py syncdb works.</p>
0
2009-10-29T03:02:39Z
1,641,410
<p>Try:</p> <pre><code>import sys sys.path.append('/home/myuser/svn-repos/myproject') from settings import * </code></pre> <p>Note that </p> <pre><code>from settings import * </code></pre> <p>makes it difficult to track down where imported variables come from. It is not a good practive if you can avoid it.</p>
1
2009-10-29T03:07:36Z
[ "python", "django" ]
How to permanently append a path to Python for Linux?
1,641,418
<p>I know there are multiple solutions online, but some are for windows, some are environmental variable, etc..</p> <p>What is the best way?</p>
4
2009-10-29T03:11:42Z
1,641,426
<p>Find your site-packages directory and create a new file called <code>myproj.pth</code></p> <p>Inside that file, put each directory you want to add, one per line like so:</p> <pre> /home/myuser/svn-repos/myproject /home/myuser/svn-repos/SomeOtherProject </pre> <p>Python loads <code>*.pth</code> every time it runs,...
11
2009-10-29T03:16:03Z
[ "python" ]
How to permanently append a path to Python for Linux?
1,641,418
<p>I know there are multiple solutions online, but some are for windows, some are environmental variable, etc..</p> <p>What is the best way?</p>
4
2009-10-29T03:11:42Z
1,641,468
<p>I personally just define <code>PYTHONPATH</code> in <code>~/.bashrc</code>, as for what's the "best" approach? I think that's hard to answer (or rather, there's no correct answer). It <em>depends</em>.</p>
1
2009-10-29T03:33:14Z
[ "python" ]
Why am I getting this error in Django?
1,641,444
<p>I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong.</p> <pre><code> Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.fl...
20
2009-10-29T03:23:08Z
1,641,451
<blockquote> <p>I don't believe I am supposed to manually create an "export DJANGO..." environment variable...</p> </blockquote> <p>Manually or otherwise, you <em>are</em> supposed to ensure that variable is in the environment before you import a Django models file -- not sure what the causes are for your disbel...
16
2009-10-29T03:26:35Z
[ "python", "django" ]
Why am I getting this error in Django?
1,641,444
<p>I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong.</p> <pre><code> Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.fl...
20
2009-10-29T03:23:08Z
1,641,457
<p>You need to properly import your settings file. If you don't import the django environment variables first, your import will fail as you've noticed. You need to code something like:</p> <pre> import os # Set the DJANGO_SETTINGS_MODULE environment variable. os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings...
38
2009-10-29T03:29:11Z
[ "python", "django" ]
Why am I getting this error in Django?
1,641,444
<p>I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong.</p> <pre><code> Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.fl...
20
2009-10-29T03:23:08Z
1,641,607
<p>One alternative to messing about with the environment is to just write your script as a <a href="http://docs.djangoproject.com/en/dev/howto/custom-management-commands/">Django custom management command</a>, which takes care of setting up the environment for you (along with other things like option parsing, etc).</p>...
6
2009-10-29T04:25:50Z
[ "python", "django" ]
Why am I getting this error in Django?
1,641,444
<p>I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong.</p> <pre><code> Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.fl...
20
2009-10-29T03:23:08Z
5,461,393
<p>from command line ran "python manage.py shell" should include the right settings for you and give you the python prompt.</p>
15
2011-03-28T15:35:37Z
[ "python", "django" ]
Why am I getting this error in Django?
1,641,444
<p>I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong.</p> <pre><code> Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.fl...
20
2009-10-29T03:23:08Z
19,586,482
<p>From command line, please execute this command. This may help you:</p> <pre><code>export DJANGO_SETTINGS_MODULE=yourproject.settings </code></pre> <p>For eg:</p> <p>(virtualenv)test@test-tester:~/projects/myproject$ export DJANGO_SETTINGS_MODULE=projname.settings</p>
0
2013-10-25T09:48:49Z
[ "python", "django" ]
Why am I getting this error in Django?
1,641,444
<p>I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong.</p> <pre><code> Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.fl...
20
2009-10-29T03:23:08Z
22,352,495
<p>I had this similar error, and I realized that I forgot to create the file "<strong>init</strong>.py" in to the app folder:</p> <pre><code>myapp: manage.py myapp: __init__.py settings.py .... </code></pre>
0
2014-03-12T13:05:11Z
[ "python", "django" ]
General programming question. When to use OOP?
1,641,470
<p>My program needs to do 2 things. </p> <ol> <li><p>Extract stuff from a webpage.</p></li> <li><p>Do stuff with a webpage.</p></li> </ol> <p>However, there are many webpages, such as Twitter and Facebook.</p> <p>should I do this?</p> <pre><code>def facebookExtract(): code here def twitterExtract(): code he...
2
2009-10-29T03:33:54Z
1,641,481
<p>Put as much of the common stuff together in a single function. Once you've factored as much out as possible, build a mechanism for branching to the appropriate function for each website.</p> <p>One possible way to do this is with python's <code>if/else</code> clauses, but if you have many such functions, you may wa...
1
2009-10-29T03:37:07Z
[ "python", "oop", "function" ]
General programming question. When to use OOP?
1,641,470
<p>My program needs to do 2 things. </p> <ol> <li><p>Extract stuff from a webpage.</p></li> <li><p>Do stuff with a webpage.</p></li> </ol> <p>However, there are many webpages, such as Twitter and Facebook.</p> <p>should I do this?</p> <pre><code>def facebookExtract(): code here def twitterExtract(): code he...
2
2009-10-29T03:33:54Z
1,641,482
<p>You use OOP when it makes sense, when it makes developing the solution quicker and when it makes the end result easier to read, understand and maintain.</p> <p>In this case it <em>might</em> make sense to create a generic Extractor interface/class and then have subclasses for Twitter, MySpace, Facebook, etc but thi...
1
2009-10-29T03:37:09Z
[ "python", "oop", "function" ]
General programming question. When to use OOP?
1,641,470
<p>My program needs to do 2 things. </p> <ol> <li><p>Extract stuff from a webpage.</p></li> <li><p>Do stuff with a webpage.</p></li> </ol> <p>However, there are many webpages, such as Twitter and Facebook.</p> <p>should I do this?</p> <pre><code>def facebookExtract(): code here def twitterExtract(): code he...
2
2009-10-29T03:33:54Z
1,641,489
<p>It's up to you. I personally try to stay away from Java-style classes when programming in python. Instead, I use dicts and/or simple objects.</p> <p>For instance, after defining these functions (the ones you defined in the question), I'd create a simple dict, maybe like this:</p> <pre><code>{ 'facebook' : { 'proce...
3
2009-10-29T03:39:45Z
[ "python", "oop", "function" ]
General programming question. When to use OOP?
1,641,470
<p>My program needs to do 2 things. </p> <ol> <li><p>Extract stuff from a webpage.</p></li> <li><p>Do stuff with a webpage.</p></li> </ol> <p>However, there are many webpages, such as Twitter and Facebook.</p> <p>should I do this?</p> <pre><code>def facebookExtract(): code here def twitterExtract(): code he...
2
2009-10-29T03:33:54Z
1,641,627
<p>My favorite rule of thumb: if you're in doubt (unspoken assumption: "and you're a reasonable person rather than a fanatic";-), make and use some classes. I've often found myself refactoring code originally written as simple functions into classes -- for example, any time the simple functions' best way to communicat...
7
2009-10-29T04:33:46Z
[ "python", "oop", "function" ]
General programming question. When to use OOP?
1,641,470
<p>My program needs to do 2 things. </p> <ol> <li><p>Extract stuff from a webpage.</p></li> <li><p>Do stuff with a webpage.</p></li> </ol> <p>However, there are many webpages, such as Twitter and Facebook.</p> <p>should I do this?</p> <pre><code>def facebookExtract(): code here def twitterExtract(): code he...
2
2009-10-29T03:33:54Z
1,641,752
<p>I regularly define classes for solving problems for a few reasons, I'll model an example of my thinking below. I have no compunctions about mixing OO models and procedural styles, that's often more a reflection of your work society than personal religion. It often works to have a procedural facade for a class hierar...
1
2009-10-29T05:17:06Z
[ "python", "oop", "function" ]
General programming question. When to use OOP?
1,641,470
<p>My program needs to do 2 things. </p> <ol> <li><p>Extract stuff from a webpage.</p></li> <li><p>Do stuff with a webpage.</p></li> </ol> <p>However, there are many webpages, such as Twitter and Facebook.</p> <p>should I do this?</p> <pre><code>def facebookExtract(): code here def twitterExtract(): code he...
2
2009-10-29T03:33:54Z
1,642,752
<p>"My program needs to do 2 things."</p> <p>When you start out like that, the objects cannot be seen. You're perspective isn't right.</p> <p>Change your thinking.</p> <p><strong>"My program works with stuff"</strong></p> <p>That's OO thinking. What "stuff" does your program work with? Define the stuff. Those a...
9
2009-10-29T10:25:33Z
[ "python", "oop", "function" ]
Checking arguments in numerical Python code
1,641,591
<p>I find myself writing the same argument checking code all the time for number-crunching:</p> <pre><code>def myfun(a, b): if a &lt; 0: raise ValueError('a cannot be &lt; 0 (was a=%s)' % a) # more if.. raise exception stuff here ... return a + b </code></pre> <p>Is there a better way? I was told ...
3
2009-10-29T04:17:06Z
1,641,601
<p>You don't want to use assert because your code can be run (and is by default on some systems) in such a way that assert lines are not checked and do not raise errors (<code>-O</code> command line flag).</p> <p>If you're using a lot of variables that are all supposed to have those same properties, why not subclass w...
0
2009-10-29T04:21:10Z
[ "python", "exception", "arguments", "assert" ]
Checking arguments in numerical Python code
1,641,591
<p>I find myself writing the same argument checking code all the time for number-crunching:</p> <pre><code>def myfun(a, b): if a &lt; 0: raise ValueError('a cannot be &lt; 0 (was a=%s)' % a) # more if.. raise exception stuff here ... return a + b </code></pre> <p>Is there a better way? I was told ...
3
2009-10-29T04:17:06Z
1,641,606
<p><code>assert</code> gets optimized away if you run with <code>python -O</code> (modest optimizations, but sometimes nice to have). One preferable alternative if you have patterns that often repeat may be to use decorators -- great way to factor out repetition. E.g., say you have a zillion functions that must be ca...
4
2009-10-29T04:24:58Z
[ "python", "exception", "arguments", "assert" ]
Checking arguments in numerical Python code
1,641,591
<p>I find myself writing the same argument checking code all the time for number-crunching:</p> <pre><code>def myfun(a, b): if a &lt; 0: raise ValueError('a cannot be &lt; 0 (was a=%s)' % a) # more if.. raise exception stuff here ... return a + b </code></pre> <p>Is there a better way? I was told ...
3
2009-10-29T04:17:06Z
1,641,656
<p>I'm not sure if this will answer your question, but it strikes me that checking a lot of arguments at the start of a function isn't very <em>pythonic</em>.</p> <p>What I mean by this is that it is the assumption of most pythonistas that we are all consenting adults, and we trust each other not to do something stupi...
-1
2009-10-29T04:44:48Z
[ "python", "exception", "arguments", "assert" ]
I'm a python beginner, dictionary is new
1,641,612
<p>Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if there is an entry (b, c) in d2, then the entry (a, c) should be added to the new dictionary. How to think of the solution?</p>
-2
2009-10-29T04:26:34Z
1,641,662
<pre><code>def transitive_dict_join(d1, d2): result = dict() for a, b in d1.iteritems(): if b in d2: result[a] = d2[b] return result </code></pre> <p>You can express this more concisely, of course, but I think that, for a beginner, spelling things out is clearer and more instructive.</p>
6
2009-10-29T04:48:05Z
[ "python" ]
I'm a python beginner, dictionary is new
1,641,612
<p>Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if there is an entry (b, c) in d2, then the entry (a, c) should be added to the new dictionary. How to think of the solution?</p>
-2
2009-10-29T04:26:34Z
1,641,693
<p>I agree with Alex, on <strong>the need of spelling things out as a novice</strong>, and to move to more concise/abstract/dangerous constructs later on.</p> <p>For the record I'm placing here a list comprehension version as Paul's doesn't seem to work.</p> <pre><code>&gt;&gt;&gt; d1 = {'a':'alpha', 'b':'bravo', 'c'...
4
2009-10-29T04:59:26Z
[ "python" ]
I'm a python beginner, dictionary is new
1,641,612
<p>Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if there is an entry (b, c) in d2, then the entry (a, c) should be added to the new dictionary. How to think of the solution?</p>
-2
2009-10-29T04:26:34Z
1,641,991
<pre><code>#!/usr/local/bin/python3.1 b = { 'aaa' : 'aaa@gmail.com', 'bbb' : 'bbb@gmail.com', 'ccc' : 'ccc@gmail.com' } a = {'a':'aaa', 'b':'bbb', 'c':'ccc'} c = {} for x in a.keys(): if a[x] in b: c[x] = b[a[x]] print(c) </code></pre> <p>OutPut: {'a': 'aaa@gmail.com', 'c': 'ccc@gma...
0
2009-10-29T06:46:11Z
[ "python" ]
extract grammar features from sentence on Google App Engine
1,641,635
<p>For my GAE app I need to do some natural language processing to extract the subject and object from an input sentence. </p> <p>Apparently <a href="http://stackoverflow.com/questions/1286301/using-the-python-nltk-2-0b5-on-the-google-app-engine">NLTK can't be installed</a> (easily) on GAE so I am looking for another ...
0
2009-10-29T04:36:45Z
1,641,691
<p>With regards to the NLTK problem specifically, my solution would probably be to fix the weird imports that NLTK is doing, and use that as originally planned. When you're done, submit a patch of course.</p> <p>That said, if this ultimately involves touching the data store, the answer is that it probably can't be do...
1
2009-10-29T04:59:03Z
[ "python", "google-app-engine", "antlr3", "nlp" ]
extract grammar features from sentence on Google App Engine
1,641,635
<p>For my GAE app I need to do some natural language processing to extract the subject and object from an input sentence. </p> <p>Apparently <a href="http://stackoverflow.com/questions/1286301/using-the-python-nltk-2-0b5-on-the-google-app-engine">NLTK can't be installed</a> (easily) on GAE so I am looking for another ...
0
2009-10-29T04:36:45Z
1,641,820
<p>You can easily build and NTLK RPC server on some machine and access it.</p> <p>Another option is to find another web based service that already does that (such as opencalais).</p>
1
2009-10-29T05:53:09Z
[ "python", "google-app-engine", "antlr3", "nlp" ]
Manual garbage collection in Python
1,641,717
<p>Is there any way to manually remove an object which the garbage collection refuses to get rid of even when I call <code>gc.collect()</code>? Working in Python 3.0</p>
15
2009-10-29T05:06:02Z
1,641,734
<p>It depends on what your Python is running on. <a href="http://effbot.org/pyfaq/how-does-python-manage-memory.htm" rel="nofollow">Here's good article</a> that explains the details</p> <p>Quoting:</p> <p>In current releases of CPython, each new assignment to x inside the loop will release the previously allocated re...
1
2009-10-29T05:10:29Z
[ "python", "garbage-collection" ]
Manual garbage collection in Python
1,641,717
<p>Is there any way to manually remove an object which the garbage collection refuses to get rid of even when I call <code>gc.collect()</code>? Working in Python 3.0</p>
15
2009-10-29T05:06:02Z
1,641,735
<p>If the GC is refusing to destroy it, it's because you have a reference to it somewhere. Get rid of the reference and it will (eventually) go. For example:</p> <pre><code>myRef = None </code></pre> <p>Keep in mind that GC may not <em>necessarily</em> destroy your object unless it needs to.</p> <p>If your object is...
4
2009-10-29T05:10:51Z
[ "python", "garbage-collection" ]
Manual garbage collection in Python
1,641,717
<p>Is there any way to manually remove an object which the garbage collection refuses to get rid of even when I call <code>gc.collect()</code>? Working in Python 3.0</p>
15
2009-10-29T05:06:02Z
1,641,744
<p><code>del</code> Or <code>None</code> are your <em>only</em> friends</p> <pre><code>&gt;&gt;&gt; a = "Hello" &gt;&gt;&gt; a = None Or &gt;&gt;&gt; del a </code></pre>
3
2009-10-29T05:12:46Z
[ "python", "garbage-collection" ]
Manual garbage collection in Python
1,641,717
<p>Is there any way to manually remove an object which the garbage collection refuses to get rid of even when I call <code>gc.collect()</code>? Working in Python 3.0</p>
15
2009-10-29T05:06:02Z
1,641,762
<p>Per <a href="http://docs.python.org/library/gc.html?highlight=gc#gc.get_referrers">the docs</a>, <code>gc.get_referrers(thatobject)</code> will tell you <em>why</em> the object is still alive (do it right after a <code>gc.collect()</code> to make sure the undesired "liveness" is gonna be persistent). After that, it...
24
2009-10-29T05:25:14Z
[ "python", "garbage-collection" ]
Is it OK to extend both old and new style classes?
1,641,958
<p>When I extended some tool generated classes, I didn't realize that they are old style classes until I tried to use super(). The super() doesn't work with old style classes, so I got this error:</p> <pre><code>TypeError: super() argument 1 must be type, not classobj </code></pre> <p>E.g., try this snippet:</p> <pr...
5
2009-10-29T06:38:10Z
1,642,118
<p>New-style classes have been recommended practice in Python since they were introduced in Python 2.2. In Python 3.x, only new-style classes are available. Therefore, I recommend you switch your classes to new-style.</p> <p>I am not aware of any real problems you might have from this. For the most part, new-style ...
4
2009-10-29T07:31:21Z
[ "python" ]
Is it OK to extend both old and new style classes?
1,641,958
<p>When I extended some tool generated classes, I didn't realize that they are old style classes until I tried to use super(). The super() doesn't work with old style classes, so I got this error:</p> <pre><code>TypeError: super() argument 1 must be type, not classobj </code></pre> <p>E.g., try this snippet:</p> <pr...
5
2009-10-29T06:38:10Z
1,643,003
<p>I see no problem mixing classic and new-style classes unless some methods rely on classic semantic or your classic base uses metaclass (metaclass of offspring will be always a new-style class).</p> <p>On the other hand I see no reason to use classic classes anymore, so changing <code>class A:</code> to <code>class ...
0
2009-10-29T11:14:31Z
[ "python" ]
Is it OK to extend both old and new style classes?
1,641,958
<p>When I extended some tool generated classes, I didn't realize that they are old style classes until I tried to use super(). The super() doesn't work with old style classes, so I got this error:</p> <pre><code>TypeError: super() argument 1 must be type, not classobj </code></pre> <p>E.g., try this snippet:</p> <pr...
5
2009-10-29T06:38:10Z
1,646,827
<p>If you cannot change the generator to generate new-style classes, you could post-process the file to make them new-style:</p> <pre><code>import re pat = re.compile("^(.*class\s+\w+)(:.*)$") out_file = open("edited_file.py", "w") for line in open("generated_file.py"): m = pat.match(line) if m: line =...
1
2009-10-29T21:56:28Z
[ "python" ]
Regular expression to match alphanumeric string
1,642,018
<p>If string "x" contains any letter or number, print that string. How to do that using regular expressions? The code below is wrong</p> <pre><code>if re.search('^[A-Z]?[a-z]?[0-9]?', i): print i </code></pre>
0
2009-10-29T06:53:55Z
1,642,026
<p>You want</p> <pre><code>if re.search('[A-Za-z0-9]+', i): print i </code></pre>
2
2009-10-29T06:57:21Z
[ "python", "regex" ]
Regular expression to match alphanumeric string
1,642,018
<p>If string "x" contains any letter or number, print that string. How to do that using regular expressions? The code below is wrong</p> <pre><code>if re.search('^[A-Z]?[a-z]?[0-9]?', i): print i </code></pre>
0
2009-10-29T06:53:55Z
1,642,032
<p><code>[A-Z]?[a-z]?[0-9]?</code> matches an optional upper case letter, followed by an optional lower case letter, followed by an optional digit. So, it also matches an empty string. What you're looking for is this: <code>[a-zA-Z0-9]</code> which will match a single digit, lower- or upper case letter. </p> <p>And if...
1
2009-10-29T06:59:44Z
[ "python", "regex" ]
Regular expression to match alphanumeric string
1,642,018
<p>If string "x" contains any letter or number, print that string. How to do that using regular expressions? The code below is wrong</p> <pre><code>if re.search('^[A-Z]?[a-z]?[0-9]?', i): print i </code></pre>
0
2009-10-29T06:53:55Z
1,642,053
<p><a href="http://docs.python.org/library/re.html" rel="nofollow">re — Regular expression operations</a></p> <p>This question is actually rather tricky. Unfortunately \w includes _ and [a-z] solutions assume a 26-letter alphabet. With the below solution <em>please read the pydoc where it talks about LOCALE and UNIC...
4
2009-10-29T07:07:23Z
[ "python", "regex" ]
Regular expression to match alphanumeric string
1,642,018
<p>If string "x" contains any letter or number, print that string. How to do that using regular expressions? The code below is wrong</p> <pre><code>if re.search('^[A-Z]?[a-z]?[0-9]?', i): print i </code></pre>
0
2009-10-29T06:53:55Z
1,642,267
<p>don't need regex. </p> <pre><code>&gt;&gt;&gt; a="abc123" &gt;&gt;&gt; if True in map(str.isdigit,list(a)): ... print a ... abc123 &gt;&gt;&gt; if True in map(str.isalpha,list(a)): ... print a ... abc123 &gt;&gt;&gt; a="##@%$#%#^!" &gt;&gt;&gt; if True in map(str.isdigit,list(a)): ... print a ... &gt;&gt;&gt; if...
0
2009-10-29T08:22:14Z
[ "python", "regex" ]
Regular expression to match alphanumeric string
1,642,018
<p>If string "x" contains any letter or number, print that string. How to do that using regular expressions? The code below is wrong</p> <pre><code>if re.search('^[A-Z]?[a-z]?[0-9]?', i): print i </code></pre>
0
2009-10-29T06:53:55Z
1,642,293
<p>I suggest that you check out RegexBuddy. It can explain regexes well. <img src="http://dl.getdropbox.com/u/42655/eternity/regexbuddy1.png" alt="RegexBuddy" /></p> <p><img src="http://dl.getdropbox.com/u/42655/eternity/regexbuddy2.png" alt="RegexBuddy" /></p> <p><img src="http://dl.getdropbox.com/u/42655/eternity/...
2
2009-10-29T08:30:40Z
[ "python", "regex" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
1,642,385
<p>I'd use <a href="http://www.gnu.org/software/octave/" rel="nofollow">Octave</a> for this but I agree, the syntax of Octave isn't what I'd call thrilling (and the docs always confuse me more than they help, too).</p>
1
2009-10-29T08:55:44Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
1,642,396
<p>For inexact solutions, read up on <a href="http://en.wikipedia.org/wiki/Linear%5Fprogramming">linear programming</a> and <a href="http://en.wikipedia.org/wiki/Sequential%5Fquadratic%5Fprogramming">sequential quadratic optimization</a>, then search for Python libraries that performs such optimizations for you.</p> <...
5
2009-10-29T08:57:46Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
1,642,398
<p>You discount the best answer as unacceptable.</p> <p>Your question is "I want a free Computer Algebra System that I can use in Python."</p> <p>The answer is "SAGE does that."</p> <p>Have you looked at maxima/macsyma? SAGE provides bindings for it, and that's one of the more powerful free ones.</p> <p><a href="ht...
22
2009-10-29T08:58:09Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
1,642,405
<p>I don't think there is a unified way of dealing with both linear and quadratic (or generally nonlinear) equations simultaneously. With linear systems, python has bindings to linear algebra and matrix packages. Nonlinear problems tend to be solved on a case by case basis.</p>
0
2009-10-29T08:59:22Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
1,642,422
<p>Have you looked at <a href="http://www.scipy.org/" rel="nofollow">SciPy</a>?</p> <p>It has an example in the tutorials on solving linear algebra:</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html#solving-linear-system" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/tutorial/l...
3
2009-10-29T09:03:38Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
1,642,479
<p><a href="http://sympy.org/">sympy</a> is exactly what you're looking for.</p>
40
2009-10-29T09:19:37Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
1,642,533
<p>I have just started using <a href="http://www.gnu.org/software/gsl/" rel="nofollow">GNU Scientific Library</a>, which however is C library. Looks like there are Python <a href="http://pygsl.sourceforge.net/README.html" rel="nofollow">bindings</a> too. So, it might be worth looking at.</p>
2
2009-10-29T09:31:54Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
1,656,755
<p>On second thoughts, I went through sage in detail and clearly it <em>is</em> the best math free software available.</p> <p>Just some of the different python math related libraries, it integrates is absolutely awesome.</p> <p>Mathematics packages contained in Sage:</p> <pre><code>Algebra GAP, Maxima, Singular Alg...
-1
2009-11-01T09:46:00Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
1,657,019
<p>It depends on your needs:</p> <p>If you want an interactive graphical interface, then sage is probably the best solution.</p> <p>If you want to avoid using a graphical interface, but you still want to do computer algebra, then sympy or maxima may cover your needs. (sympy looks very promising, but it still have a ...
0
2009-11-01T12:14:15Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
3,507,336
<p>Here is how to solve your original question using Python (via Sage). This basically clarifies the remark Paul McMillan makes above. </p> <pre><code>sage: a,b,c = var('a,b,c') sage: solve([a+b+c==1000, a^2+b^2==c^2], a,b,c) [[a == 1000*(r1 + sqrt(r1^2 + 2000*r1 - 1000000))/(r1 + sqrt(r1^2 + 2000*r1 - 1000000) + 100...
10
2010-08-17T22:02:57Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
6,607,579
<p>Take a look at this:</p> <p><a href="http://openopt.org/FuncDesignerDoc#Solving_systems_of_nonlinear_equations" rel="nofollow">http://openopt.org/FuncDesignerDoc#Solving_systems_of_nonlinear_equations</a></p> <p>It is extremely easy to use and quite powerful</p>
0
2011-07-07T08:06:46Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
8,190,961
<p>Well, I just googled into this page by accident. I see many suggestions regarding this and that software tool, but does any tool actually provide an answer? The actual answer is:</p> <p>[a,b,c] = [200,375,425]</p> <p>How did I get this? By writing a quick program in the Maxima programming language to find it vi...
0
2011-11-19T00:47:05Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
9,150,391
<p>A free web-service for solving large-scale systems of nonlinear equations (1 million+) is APMonitor.com. There is a browser interface and an API to Python / MATLAB. The API to Python is a single script (apm.py) that is available for download from the apmonitor.com homepage. Once the script is loaded into a Python...
3
2012-02-05T15:21:55Z
[ "python", "math", "numpy", "scipy", "equation" ]
Simplest way to solve mathematical equations in Python
1,642,357
<p>I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.</p> <p>It is simple to use <a href="http://www.wolframalpha.com/" rel="nofollow">wolframalpha.com</a>, the web equivalent of Mathematica, to solve them. But that doesn...
16
2009-10-29T08:48:29Z
9,740,209
<p>For reference: <a href="http://www.wolframalpha.com/input/?i=a%2Bb%2Bc%3D1000%2C+a%5E2+%2B+b%5E2+%3D+c%5E2" rel="nofollow">Wolfram Alpha's solution</a>:</p> <pre><code>a-1000!=0, b = (1000 (a-500))/(a-1000), c = (-a^2+1000 a-500000)/(a-1000) </code></pre> <p>In python, using <a href="http://docs.sympy.org/dev/...
3
2012-03-16T15:36:14Z
[ "python", "math", "numpy", "scipy", "equation" ]
How to defer a Django DB operation from within Twisted?
1,642,392
<p>I have a normal Django site running. In addition, there is another twisted process, which listens for Jabber presence notifications and updates the Django DB using Django's ORM.</p> <p>So far it works as I just call the corresponding Django models (after having set up the settings environment correctly). This, howe...
6
2009-10-29T08:57:02Z
1,643,750
<p>"I have a normal Django site running."</p> <p>Presumably under Apache using mod_wsgi or similar.</p> <p>If you're using mod_wsgi embedded in Apache, note that Apache is multi-threaded and your Python threads are mashed into Apache's threading. Analysis of what's blocking could get icky.</p> <p>If you're using mo...
1
2009-10-29T13:30:23Z
[ "python", "django", "twisted", "deferred-execution" ]
How to defer a Django DB operation from within Twisted?
1,642,392
<p>I have a normal Django site running. In addition, there is another twisted process, which listens for Jabber presence notifications and updates the Django DB using Django's ORM.</p> <p>So far it works as I just call the corresponding Django models (after having set up the settings environment correctly). This, howe...
6
2009-10-29T08:57:02Z
1,677,455
<p>I have been successful using the method you described as your current method. You'll find by reading the docs that the twisted DB api uses threads under the hood because most SQL libraries have a blocking API.</p> <p>I have a twisted server that saves data from power monitors in the field, and it does it by startin...
1
2009-11-04T23:42:42Z
[ "python", "django", "twisted", "deferred-execution" ]
How to defer a Django DB operation from within Twisted?
1,642,392
<p>I have a normal Django site running. In addition, there is another twisted process, which listens for Jabber presence notifications and updates the Django DB using Django's ORM.</p> <p>So far it works as I just call the corresponding Django models (after having set up the settings environment correctly). This, howe...
6
2009-10-29T08:57:02Z
1,683,697
<p>I have a running Twisted app where I use Django ORM. I'm not deferring it. I know it's wrong, but hadd no problems yet.</p>
0
2009-11-05T21:20:12Z
[ "python", "django", "twisted", "deferred-execution" ]
Why do so many apps/frameworks keep their configuration files in an un-executed format?
1,642,413
<p>Many frameworks keep their configuration files in a language different from the rest of the program. Eg, Appengine keeps the configuration in yaml format. to compare, DJango settings.py is a python module. There are many disadvantages I can see with this.</p> <p>If its in same language as rest of the program, I can...
2
2009-10-29T09:01:19Z
1,642,424
<p>Some framework designers feel that the configuration files are inappropriate places for heavy logic. Just as the MVC framework prevents you from putting logic where it does not belong, the configuration file prevents you from putting programming where it does not belong.</p> <p>It's a matter of taste and philosophy...
12
2009-10-29T09:03:45Z
[ "python", "configuration", "settings", "yaml" ]
Why do so many apps/frameworks keep their configuration files in an un-executed format?
1,642,413
<p>Many frameworks keep their configuration files in a language different from the rest of the program. Eg, Appengine keeps the configuration in yaml format. to compare, DJango settings.py is a python module. There are many disadvantages I can see with this.</p> <p>If its in same language as rest of the program, I can...
2
2009-10-29T09:01:19Z
1,642,433
<p>Python may not always be the only language that appengine runs on. So the same yaml configuration file could drive an appengine app written in, for example, java or perl</p>
5
2009-10-29T09:06:07Z
[ "python", "configuration", "settings", "yaml" ]
Why do so many apps/frameworks keep their configuration files in an un-executed format?
1,642,413
<p>Many frameworks keep their configuration files in a language different from the rest of the program. Eg, Appengine keeps the configuration in yaml format. to compare, DJango settings.py is a python module. There are many disadvantages I can see with this.</p> <p>If its in same language as rest of the program, I can...
2
2009-10-29T09:01:19Z
1,642,477
<p>It probably just didn't occur to them that they could do it. Many programmers are from the old days where scripting languages were slow and not really more simple than the programming languages (just look at things like Unix shells). When nifty dynamic languages came along, they just stuck to "text only config files...
-1
2009-10-29T09:19:29Z
[ "python", "configuration", "settings", "yaml" ]
Why do so many apps/frameworks keep their configuration files in an un-executed format?
1,642,413
<p>Many frameworks keep their configuration files in a language different from the rest of the program. Eg, Appengine keeps the configuration in yaml format. to compare, DJango settings.py is a python module. There are many disadvantages I can see with this.</p> <p>If its in same language as rest of the program, I can...
2
2009-10-29T09:01:19Z
1,642,591
<p>Sometimes you need to use an automatic/GUI tool to parse and/or generate and/or modify a configuration file. This is not easy if your conffile is a python script.</p>
5
2009-10-29T09:47:22Z
[ "python", "configuration", "settings", "yaml" ]
Why do so many apps/frameworks keep their configuration files in an un-executed format?
1,642,413
<p>Many frameworks keep their configuration files in a language different from the rest of the program. Eg, Appengine keeps the configuration in yaml format. to compare, DJango settings.py is a python module. There are many disadvantages I can see with this.</p> <p>If its in same language as rest of the program, I can...
2
2009-10-29T09:01:19Z
1,642,621
<p>There is a very good reason: if your program is distributed in an unsafe environment, like the user computer, executing a text file which is so easy to modify is the door open to many viruses. This is less the case with a django application where the application is hosted on the server - a safe environment. But with...
2
2009-10-29T09:55:23Z
[ "python", "configuration", "settings", "yaml" ]
Datastore datetimeproperty iterable?
1,642,441
<p>I have model</p> <pre><code>class info(db.Model): user = db.UserProperty() last_update_date = db.DateTimeProperty() </code></pre> <p>I need to retrieve <code>last_update_date</code> for specific user. It is working good, i can retrieve this value, i can even pass it to another variable</p> <pre><code>if r...
0
2009-10-29T09:08:16Z
1,653,121
<p>An example from <a href="http://code.google.com/apis/contacts/docs/1.0/developers%5Fguide%5Fpython.html" rel="nofollow">the contacts API documentation</a>:</p> <pre><code>updated_min = raw_input('Enter updated min (example: 2007-03-16T00:00:00): ') query = gdata.contacts.service.ContactsQuery() query.updated_min = ...
1
2009-10-31T01:37:54Z
[ "python", "google-app-engine", "datetime", "gae-datastore" ]
How to delete columns in numpy.array
1,642,730
<p>I would like to delete selected columns in a numpy.array . This is what I do:</p> <pre><code>n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z [ True False Fa...
24
2009-10-29T10:21:34Z
1,643,022
<p>This creates another array without those columns:</p> <pre><code> b = a.compress(logical_not(z), axis=1) </code></pre>
5
2009-10-29T11:19:34Z
[ "python", "numpy", "scipy" ]
How to delete columns in numpy.array
1,642,730
<p>I would like to delete selected columns in a numpy.array . This is what I do:</p> <pre><code>n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z [ True False Fa...
24
2009-10-29T10:21:34Z
1,643,457
<p>Another way is to use masked arrays:</p> <pre><code>import numpy as np a = np.array([[ np.nan, 2., 3., np.nan], [ 1., 2., 3., 9]]) print(a) # [[ NaN 2. 3. NaN] # [ 1. 2. 3. 9.]] </code></pre> <p>The np.ma.masked_invalid method returns a masked array with nans and infs masked out:</p> <pre><c...
10
2009-10-29T12:44:05Z
[ "python", "numpy", "scipy" ]
How to delete columns in numpy.array
1,642,730
<p>I would like to delete selected columns in a numpy.array . This is what I do:</p> <pre><code>n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z [ True False Fa...
24
2009-10-29T10:21:34Z
5,034,558
<p>Given its name, I think the standard way should be <code>delete</code>:</p> <pre><code>A = scipy.delete(A, 1, 0) # delete second row of A B = scipy.delete(B, 2, 0) # delete third row of B C = scipy.delete(C, 1, 1) # delete second column of C </code></pre>
26
2011-02-17T20:57:37Z
[ "python", "numpy", "scipy" ]
How to delete columns in numpy.array
1,642,730
<p>I would like to delete selected columns in a numpy.array . This is what I do:</p> <pre><code>n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z [ True False Fa...
24
2009-10-29T10:21:34Z
6,586,683
<p>Example from <a href="http://wiki.scipy.org/Numpy_Example_List#head-a2ab8bc7283d245977d250a5d8761f9369d0a60e" rel="nofollow">the numpy documentation</a>:</p> <pre><code>&gt;&gt;&gt; a = array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) &gt;...
4
2011-07-05T17:42:42Z
[ "python", "numpy", "scipy" ]
How to delete columns in numpy.array
1,642,730
<p>I would like to delete selected columns in a numpy.array . This is what I do:</p> <pre><code>n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z [ True False Fa...
24
2009-10-29T10:21:34Z
7,786,760
<p>In your situation, you can extract the desired data with:</p> <pre><code>a[:, -z] </code></pre> <p>"-z" is the logical negation of the boolean array "z". This is the same as:</p> <pre><code>a[:, logical_not(z)] </code></pre>
1
2011-10-16T19:36:52Z
[ "python", "numpy", "scipy" ]
How to delete columns in numpy.array
1,642,730
<p>I would like to delete selected columns in a numpy.array . This is what I do:</p> <pre><code>n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z [ True False Fa...
24
2009-10-29T10:21:34Z
19,886,741
<p>From <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html">Numpy Documentation</a></p> <p>np.delete(arr, obj, axis=None) Return a new array with sub-arrays along an axis deleted.</p> <pre><code>&gt;&gt;&gt; arr array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]...
5
2013-11-10T05:55:31Z
[ "python", "numpy", "scipy" ]
How to delete columns in numpy.array
1,642,730
<p>I would like to delete selected columns in a numpy.array . This is what I do:</p> <pre><code>n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z [ True False Fa...
24
2009-10-29T10:21:34Z
29,222,613
<pre><code>&gt;&gt;&gt; A = array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) &gt;&gt;&gt; A = A.transpose() &gt;&gt;&gt; A = A[1:].transpose() </code></pre>
1
2015-03-23T23:55:44Z
[ "python", "numpy", "scipy" ]
Django Custom Managers for User model
1,642,779
<p>How would I go about extending the default User model with custom managers?</p> <p>My app has many user types that will be defined using the built-in Groups model. So a User might be a client, a staff member, and so on. It would be ideal to be able to do something like:</p> <pre><code>User.clients.filter(name='Tes...
7
2009-10-29T10:31:05Z
1,642,856
<p>You can user Profile for this</p> <blockquote> <p>AUTH_PROFILE_MODULE = 'accounts.UserProfile'</p> <p>When a user profile model has been defined and specified in this manner, each User object will have a method -- get_profile() -- which returns the instance of the user profile model associated wi...
-1
2009-10-29T10:43:14Z
[ "python", "django" ]
Django Custom Managers for User model
1,642,779
<p>How would I go about extending the default User model with custom managers?</p> <p>My app has many user types that will be defined using the built-in Groups model. So a User might be a client, a staff member, and so on. It would be ideal to be able to do something like:</p> <pre><code>User.clients.filter(name='Tes...
7
2009-10-29T10:31:05Z
1,644,255
<p>Yes, you can add a custom manager directly to the User class. This is monkeypatching, and it does make your code less maintainable (someone trying to figure out your code may have no idea where the User class acquired that custom manager, or where they could look to find it). In this case it's relatively harmless, a...
14
2009-10-29T14:46:44Z
[ "python", "django" ]
I want to create this environment variable for everyone, but it does not load during startup? (linux)
1,642,926
<p>I put this at the top, using "sudo vi /etc/profile":</p> <pre><code>PYTHONPATH=/home/myuser:/home/myotheruser </code></pre> <p>When I use putty and log in under my username, the python path does not work! I type "set", and it is there. But, importing things from that directory still does not work.</p> <p>When I m...
0
2009-10-29T10:57:51Z
1,642,943
<p>You need to <em>export</em> the PYTHONPATH even in /etc/profile.</p> <p>Make sure you have these lines both in /etc/profile.</p> <pre><code>PYTHONPATH=... export PYTHONPATH </code></pre> <p>After that login again.</p>
4
2009-10-29T11:01:43Z
[ "python", "linux", "unix", "environment-variables" ]
Introspecting a DLL with python
1,642,938
<p>I'm currently trying to do some introspection on a DLL with python. I want to create automatically a graphical test interface based on a DLL.</p> <p>I can load my DLL in python quite easily and I call some functions. The main problem is if I call "dir" on the object without calling any method, I've got in result</p...
1
2009-10-29T11:00:41Z
1,643,330
<p>As far as I know, there is no easy way to do this. You have to use some external tool (e.g. <code>link /dump /exports</code>) or use a PE/DLL parser (e.g. <a href="http://code.google.com/p/pefile/" rel="nofollow">pefile</a>).</p>
2
2009-10-29T12:20:43Z
[ "python", "ctypes" ]
Folder and file organization for Python development
1,642,975
<p>What is the best way to organize code that belongs to the same project in a Python development environment? What are the do and donts of Python project organization? Do you separate each class in a file? </p> <pre><code>Project A Classes "subsystem1" class1 class2 subsyste...
14
2009-10-29T11:08:00Z
1,643,354
<p>Some suggestions are at <a href="http://jcalderone.livejournal.com/39794.html">http://jcalderone.livejournal.com/39794.html</a> and <a href="http://infinitemonkeycorps.net/docs/pph/">http://infinitemonkeycorps.net/docs/pph/</a></p>
9
2009-10-29T12:25:18Z
[ "python", "organization", "code-organization" ]
Folder and file organization for Python development
1,642,975
<p>What is the best way to organize code that belongs to the same project in a Python development environment? What are the do and donts of Python project organization? Do you separate each class in a file? </p> <pre><code>Project A Classes "subsystem1" class1 class2 subsyste...
14
2009-10-29T11:08:00Z
1,643,389
<p>There are not that many issues that are going to be applicable only to Python. This website: <a href="http://www.scmpatterns.com/book/pattern-summary.html" rel="nofollow" title="Software Configuration Management Patterns">Software Configuration Management Patterns</a> and the associate book describes some Source Cod...
0
2009-10-29T12:31:20Z
[ "python", "organization", "code-organization" ]
Why do I get this error when I try to print something in Putty?
1,643,023
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 38: ordinal not in range(128) </code></pre> <p>I am downloading a website and then printing its contents...simple. Do I have to encode it somehow?</p>
2
2009-10-29T11:19:41Z
1,643,044
<p>Make sure you have Putty configured to accept UTF-8 encoded data.</p>
0
2009-10-29T11:23:33Z
[ "python", "unicode", "encoding", "ascii" ]
Why do I get this error when I try to print something in Putty?
1,643,023
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 38: ordinal not in range(128) </code></pre> <p>I am downloading a website and then printing its contents...simple. Do I have to encode it somehow?</p>
2
2009-10-29T11:19:41Z
1,643,049
<p>Try utf-8 for start. Website you download might have different charset than ANSI and those extra characters can not be printed on console.</p> <p>So in place where you do <code>print text</code> do <code>print text.encode('utf-8')</code> instead.</p>
2
2009-10-29T11:24:39Z
[ "python", "unicode", "encoding", "ascii" ]
Why do I get this error when I try to print something in Putty?
1,643,023
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 38: ordinal not in range(128) </code></pre> <p>I am downloading a website and then printing its contents...simple. Do I have to encode it somehow?</p>
2
2009-10-29T11:19:41Z
1,643,707
<p><code>print</code>ing stuff to standard output can be problematic, because Python often doesn't know what character encoding the system is using. In the face of this Python 2 assumes the most conservative choice, US ASCII. So when you try to print a string that contains characters that aren't in ASCII, like the U+20...
0
2009-10-29T13:23:32Z
[ "python", "unicode", "encoding", "ascii" ]
Django 1.1 forms, models and hiding fields
1,643,171
<p>Consider the following Django models:</p> <pre><code>class Host(models.Model): # This is the hostname only name = models.CharField(max_length=255) class Url(models.Model): # The complete url url = models.CharField(max_length=255, db_index=True, unique=True) # A foreign key identifying the host ...
3
2009-10-29T11:48:40Z
1,643,180
<p>You can use exclude and then in the forms "clean" method set whatever you want.</p> <p>So in your form:</p> <pre><code>class myform(models.ModelForm): class Meta: model=Urls exclude= ("field_name") def clean(self): self.cleaned_data["field_name"] = "whatever" return self.cleaned_dat...
1
2009-10-29T11:50:17Z
[ "python", "django", "forms", "models" ]
Django 1.1 forms, models and hiding fields
1,643,171
<p>Consider the following Django models:</p> <pre><code>class Host(models.Model): # This is the hostname only name = models.CharField(max_length=255) class Url(models.Model): # The complete url url = models.CharField(max_length=255, db_index=True, unique=True) # A foreign key identifying the host ...
3
2009-10-29T11:48:40Z
1,643,215
<p>Use <code>commit=False</code>:</p> <pre><code>result = form.save(commit=False) result.host = calculate_the_host_from(result) result.save() </code></pre>
3
2009-10-29T11:59:20Z
[ "python", "django", "forms", "models" ]
visualizing id, x, y, t data
1,643,265
<p>I have the following vehicle data</p> <pre><code>vehicle_id, position_x, position_y, time </code></pre> <p>The data represents the position of a vehicle at time 't' . The data is also available as a linear reference. I was wondering what's a simple way to visualize the vehicle movement as an animation? I would pre...
2
2009-10-29T12:08:24Z
1,643,318
<p>I'd imagine its best done on a map; consider integrating (Google) maps with a custom path representing the vehicle.</p>
2
2009-10-29T12:19:08Z
[ "python", "animation", "visualization" ]
visualizing id, x, y, t data
1,643,265
<p>I have the following vehicle data</p> <pre><code>vehicle_id, position_x, position_y, time </code></pre> <p>The data represents the position of a vehicle at time 't' . The data is also available as a linear reference. I was wondering what's a simple way to visualize the vehicle movement as an animation? I would pre...
2
2009-10-29T12:08:24Z
1,643,337
<p>What kind of animation did you have in mind? You can try <a href="http://www.pygame.org" rel="nofollow">PyGame</a> for desktop app. They have a nice tutorial about <a href="http://www.pygame.org/docs/tut/MoveIt.html" rel="nofollow">this</a>.</p>
3
2009-10-29T12:22:03Z
[ "python", "animation", "visualization" ]
visualizing id, x, y, t data
1,643,265
<p>I have the following vehicle data</p> <pre><code>vehicle_id, position_x, position_y, time </code></pre> <p>The data represents the position of a vehicle at time 't' . The data is also available as a linear reference. I was wondering what's a simple way to visualize the vehicle movement as an animation? I would pre...
2
2009-10-29T12:08:24Z
1,643,350
<p>Use pygame for it.</p>
2
2009-10-29T12:24:59Z
[ "python", "animation", "visualization" ]
'sys.excepthook' and threading
1,643,327
<p>I am using Python 2.5 and trying to use a self-defined <code>excepthook</code> in my program. In the main thread it works perfectly fine. But in a thread started with the threading module the usual <code>excepthook</code> is called.</p> <p>Here is an example showing the problem. Uncommenting the comment shows the d...
7
2009-10-29T12:20:24Z
1,643,363
<p>It looks like there is a related bug reported <a href="http://bugs.python.org/issue1230540">here</a> with workarounds. The suggested hacks basically wrap run in a try/catch and then call <code>sys.excepthook(*sys.exc_info())</code></p>
6
2009-10-29T12:27:07Z
[ "python", "multithreading", "exception", "exception-handling" ]